DOM
DOM

Reputation: 53

ffi-napi How to accept a struct containing a char array as the return type?

I am passing a callback to a function in C++. This callback must accept a struct defined in the C++ code that contains a char array.

I looked at Call C++ dll with struct containing char array from Node.js, which discusses how to pass a struct containing a char array to a foreign C++ function. However, I am struggling to accept a struct of the same nature from a foreign C++ function.

The struct is defined as:

struct Info {
  long ID;
  char chName[128];
};

And here is my JavaScript code:

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

var Info = StructType({
    'ID' : 'long',
    'chName' : ArrayType('char', 128) 
});

var ffi = require('ffi-napi');

var lib = ffi.DynamicLibrary('lib.so', ffi.DynamicLibrary.FLAGS.RTLD_LAZY);

var SetCallback = ffi.ForeignFunction(
  lib.get('SetCallback'),
  'void',
  ['pointer']
);

var callback = ffi.Callback('void', [Info], (info) => {
    console.log(`ID: ${info.ID}`);
    console.log(`name: ${JSON.stringify(info.chName)}`);
});

SetCallback(callback);

When the callback is triggered, info.ID is correct, but info.chName is either an array of all 0's (and I know for sure this is not correct), or a seg fault occurs.

I feel I may be misunderstanding how C++ works here and would appreciate any help.

Upvotes: 3

Views: 1180

Answers (0)

Related Questions