I am trying to use node-ffi to access cpp library and use the functions. math.cc is cc file with definition of all the functions. used node-gyp to build the code. and generating .so file which is accessed by math.js.
math.cc
#include "math.h"
int add(int x, int y)
{
return x + y;
}
int minus(int x, int y)
{
return x - y;
}
int multiply(int x, int y)
{
return x * y;
}
Header file
int add(int a, int b);
int minus(int a, int b);
int multiply(int a, int b);
math.js which exports the functions
var ffi = require('ffi');
var ref = require('ref');
var int = ref.types.int;
var platform = process.platform;
var mathlibLoc = null;
if (platform === 'win32'){
mathlibLoc = './math.dll';
}else if(platform === 'linux'){
mathlibLoc = './build/Release/obj.target/math.so';
}else if(platform === 'darwin'){
mathlibLoc = './math.dylib'
}else{
throw new Error('unsupported plateform for mathlibLoc')
}
var math = ffi.Library(mathlibLoc, {
"add": [int, [int, int]],
"minus": [int, [int, int]],
"multiply": [int, [int, int]]
});
module.exports = math;
Accessing functions
test.js
var math = require('./math');
var result = null;
result = math.add(5, 2);
console.log('5+2='+result);
result = math.minus(5, 2);
console.log('5-2='+result);
result = math.multiply(5, 2);
console.log('5*2='+result);
Gives the error. Please help.
As code is in cpp, we need to do extern "C" if we want to access cpp library in node-ffi.
#include <stdint.h>
#if defined(WIN32) || defined(_WIN32)
#define EXPORT __declspec(dllexport)
#else
#define EXPORT
#endif
extern "C" EXPORT int add(int a, int b) {
return a + b;
}
This will solve the error.