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

时间:2015-08-21 06:51:41

标签: node.js ref node-ffi

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

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

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

1 个答案:

答案 0 :(得分:3)

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

//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编程以便记住。