I am trying to figure out how to pass data between a C library and a NodeJS module. Would I be able to do so via the NodeFFI module?
Or will I have to write my own NodeJS addon to develop a C-NodeJS interface?
The node-ffi documentation states:
node-ffiis a Node.js addon for loading and calling dynamic libraries using pure JavaScript. It can be used to create bindings to native libraries without writing any C++ code.
You just need to access libraries as stated in node-ffi and the pass results elsewhere. In their source, they have an example. Assuming they're in the same directory:
File factorial.c:
#include <stdint.h>
uint64_t factorial(int max) {
int i = max;
uint64_t result = 1;
while (i >= 2) {
result *= i--;
}
return result;
}
File factorial.js:
//load the ffi module
var ffi = require('ffi');
//include the function
var libfactorial = ffi.Library('./libfactorial', {
'factorial': [ 'uint64', [ 'int' ] ]
});
if (process.argv.length < 3) {
console.log('Arguments: ' + process.argv[0] + ' ' + process.argv[1] + ' <max>');
process.exit();
};
//usage of the function
var output = libfactorial.factorial(parseInt(process.argv[2]));
console.log('Your output: ' + output);
Using the module, the C file is loaded with this:
var libfactorial = ffi.Library('./libfactorial', {
'factorial': [ 'uint64', [ 'int' ] ]
});
and then accessed like this:
//process.argv are the command line arguments
var argument = parseInt(process.argv[2]);
var output = libfactorial.factorial(argument);