Kim Thi Kim Thi - 2 months ago 26
Node.js Question

node-ffi - Passing string pointer to C library

I have API in C library as bellow

EXPORT void test(char *a) {
// Do something to change value of "a"
}


And I want to passing a pointer of string to that API with node-ffi and ref. I was tried many ways but unsuccessful. Someone else can help me resolve it?

Answer

How are you going to prevent a buffer overflow? Most functions which output a string also take a parameter to specify the max length that has been allocated for that string. This issue not withstanding, the following worked for me:

//use ffi and ref to interface with a c style dll
var ffi = require('ffi');
var ref = require('ref');

//load the dll. The dll is located in the current folder and named customlib.dll
var customlibProp = ffi.Library('customlib', {
    'myfunction': [ 'void', [ 'char *' ] ]
});

var maxStringLength = 200;
var theStringBuffer = new Buffer(maxStringLength);
theStringBuffer.fill(0); //if you want to initially clear the buffer
theStringBuffer.write("Intitial value", 0, "utf-8"); //if you want to give it an initial value

//call the function
customlibProp.myfunction(theStringBuffer);

//retrieve and convert the result back to a javascript string
var theString = theStringBuffer.toString('utf-8');
var terminatingNullPos = theString.indexOf('\u0000');
if (terminatingNullPos >= 0) {theString = theString.substr(0, terminatingNullPos);}
console.log("The string: ",theString);

I'm also not positive that your c function has the right declaration. The function I was interfacing with had a signature that was like: void (__stdcall *myfunction)(char *outputString); Maybe EXPORT will resolve to the same thing, I just haven't done any c programming recently enough to remember.

Comments