gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 00:41:40 25 4
gpt4 key购买 nike

我在 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 编程,所以记不清了。

关于node.js - node-ffi - 将字符串指针传递给 C 库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32134106/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com