【问题标题】:node-ffi - Passing string pointer to C librarynode-ffi - 将字符串指针传递给 C 库
【发布时间】:2015-08-21 06:51:40
【问题描述】:

我在 C 库中有如下 API

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

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

【问题讨论】:

    标签: node.js ref node-ffi


    【解决方案1】:

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

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

    【讨论】:

    • 感谢您的帮助。此问题已得到解决。但无论如何,你的答案看起来很棒
    猜你喜欢
    • 1970-01-01
    • 2014-02-20
    • 2022-10-09
    • 2014-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-03
    • 2015-06-03
    相关资源
    最近更新 更多