使用包含来自 Node.js 的 char 数组的结构调用 C++ dll

Dav*_*own 5 c++ pointers node.js node-ffi

我正在使用 Node.js ffi插件来调用 C++ DLL。

我遇到的问题是我提供的结构 - 它包含一个 char 数组 - 我不相信我的设置正确。结果我无法访问内容。

C++头文件中的例程定义:

int GetSysConfig(MyConfig * config);
Run Code Online (Sandbox Code Playgroud)

MyConfig结构体在 C++ 中定义如下:

typedef struct{
    int attribute;
    char path[256];
}MyConfig;
Run Code Online (Sandbox Code Playgroud)

我对应的 Node.js 结构定义:

var ffi = require('ffi');
var ref = require('ref');
var StructType = require('ref-struct');
var ArrayType = require('ref-array');

// This seems to be the problematic part?
var charArray = ArrayType('char');
charArray.length = 256;

var MyConfig = StructType({
    'attribute' : 'int',
    'path' : charArray
})
Run Code Online (Sandbox Code Playgroud)

注意:下面是我从 Node.js 调用 DLL 的地方 - 我不认为这里有问题,尽管我可能是错的。

// Create a pointer to the config - we know we expect to supply this to the C++ routine.
var myConfigPtr  = ref.refType(MyConfig);

var lib = ffi.Library('my.dll', {
 "GetSysConfig": ["int", [myConfigPtr]]
});

var myConfigObj = new MyConfig();

lib.GetSysConfig.async(myConfigObj.ref(), function(err, res) {
    console.log("attribute: " + myConfigObj.attribute);
    // This is always empty [] - when it shouldn't be.
    console.log("path: " + JSON.Stringify(myConfigObj.path));
});
Run Code Online (Sandbox Code Playgroud)

有谁知道我哪里出了问题?

Dav*_*own 4

对于包含数组的结构:应将其大小指定为 ArrayType 的参数来定义。

例如:

ArrayType('char', 256) 
Run Code Online (Sandbox Code Playgroud)

因此,我的问题的解决方法如下:

var MyConfig = StructType({
    'attribute' : 'int',
    'path' : ArrayType('char', 256)
})
Run Code Online (Sandbox Code Playgroud)