Davie Brown Davie Brown -5 years ago 493
Node.js Question

Call C++ dll with struct containing char array from Node.js

I'm using the Node.js ffi addon to call a C++ DLL.

The problem I'm having is with the struct I'm supplying - it contains a char array - I don't believe I'm setting this up correctly.
As a result I am unable to access the contents.

Routine's definition from C++ header file:

int GetSysConfig(MyConfig * config);

The MyConfig struct is defined in C++ as follows:

typedef struct{
int attribute;
char path[256];

My corresponding Node.js struct definition:

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

Note: Below here is where I call the DLL from Node.js - I don't think there's a problem here although I could be wrong.

// 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));

Does anyone know where I'm going wrong with this?

Answer Source

For structs containing arrays: These should be defined with their size specified as a parameter to ArrayType.

For example:

ArrayType('char', 256) 

Therefore the fix for my problem is the following struct:

var MyConfig = StructType({
    'attribute' : 'int',
    'path' : ArrayType('char', 256)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download