Search code examples
node.jsffirefnode-ffi

Calling C function from returned pointer in NodeJS


I'm trying to call a function in NodeJS that was returned as a pointer by a function called via ffi. I'm getting segmentation fault. What am I doing wrong?

The ffi imported function gets a pointer to char as argument (that informs to what function the returned pointer should point to) and then return a pointer to void. In ffi.Library declaration, I've tried many return types, I.E.: ref.types.void; ref.reftype(ref.types.void) and now I'm using ref.refType(getDevList), that is the type of my function.

C Function:

void *GetFunctionAddress(const char* fctName)
{
  void *address;
  ...
  return address;
}

NodeJS code:

var ffi = require('ffi');
var Gateway;

var DeviceList = StructType({
    deviceNumber: ref.types.uint16,
}) 
DeviceList.defineProperty('device', 
ArrayType(ref.refType(DeviceList)))

var deviceListPtr = ref.refType(DeviceList);
var getDevList = ffi.Function(deviceListPtr, []);

Gateway = ffi.Library('./GatewayManager.so', {

  'InitializeGateway': ['bool',['void']],
  'ReloadConfig' : ['void',['void']],
  'ReadPar' : ['uint',['uint','uint','uint', dwordType]],
  'WritePar' : ['uint',['uint','uint','uint', dwordType]],
  'GetDatablockAddress' : [wordType,['uint','uint','uint']],
  'GetFunctionAddress' :  [ref.refType(getDevList),['char *']]

});

var retPtr =                 
Gateway.GetFunctionAddress(ref.allocCString('GetDevList'));
var GetDevList = retPtr.deref();
var DeviceListPtr = GetDevList();
res.send(DeviceListPtr);
console.log(DeviceListPtr);

I'm getting segmentation fault when the following line is in code:

var DeviceListPtr = GetDevList();

Solution

  • You do not need ref.refType() in the following line:
    'GetFunctionAddress' : [ref.refType(getDevList),['char *']]
    Change it to:
    'GetFunctionAddress' : [getDevList,['char *']]
    It should work.