node-ffi - 将字符串指针传递给 C 库

node-ffi - Passing string pointer to C library

我在 C 库中有 API,如下所示

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

我想用 node-ffi 和 ref 将字符串指针传递给那个 API。我尝试了很多方法但没有成功。其他人可以帮我解决吗?

你打算如何防止缓冲区溢出?大多数输出​​字符串的函数还采用一个参数来指定已为该字符串分配的最大长度。这个问题没有解决,以下对我有用:

//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);

我也不肯定你的 c 函数有正确的声明。我正在连接的函数有一个签名,如下所示: void (__stdcall *myfunction)(char *outputString); 也许 EXPORT 会解决同样的问题,我只是最近没有做过任何 c 编程来记住。