4

我在 C 库中有如下 API

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

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

4

1 回答 1

4

你将如何防止缓冲区溢出?大多数输出​​字符串的函数还带有一个参数来指定为该字符串分配的最大长度。尽管有这个问题,但以下内容对我有用:

//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 编程。

于 2016-08-09T14:31:18.743 回答