5

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];
}MyConfig;

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?

1 Answer 1

4

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:

var MyConfig = StructType({
    'attribute' : 'int',
    'path' : ArrayType('char', 256)
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.