nodejs调c/c++

  • 当前环境

    • mac

不同环境下动态库的类型不一样windows下是.dll,linux下是.so,mac下是.dylib。但本质上都是通过c/c++编译得到的。

原理:先将C编译成动态库,ffi再调用动态库来实现nodejs调用c/c++

编写C代码

  1. // add.c
  2. int add(int a,int b)
  3. {
  4. return a+b;
  5. }
  6. int axb(int a,int b)
  7. {
  8. return a*b;
  9. }

编译c为dylib

  1. gcc -dynamiclib add.c -o add.dylib

node调用dylib

  • 安装ffi
  1. npm i ffi -s
  • 编写调用dylib的js
  1. const ffi = require('ffi');
  2. const path = require('path')
  3. const dllPath = path.resolve(__dirname,'./cpp/libadd.dylib');
  4. var lib = ffi.Library(dllPath, {
  5. 'add': [ 'int', [ 'int','int' ]],
  6. 'axb': [ 'int', [ 'int','int' ]],
  7. });
  8. console.log(lib.add(3,6));// 9
  9. console.log(lib.axb(3,6));// 18

其他

  • mac下系统动态库在/usr/lib可创建软连到自己的动态库下就不用指定dylib的路径了