Search code examples
javascriptcnode.jsffinode-ffi

Node ffi pointer to struct


FIrst of all, I'm asking here because there's neither a fast answer to usage of pointers in node ffi neither about pointers to structs, this is going to help

Here's my node ffi:

const struct_in_addr = Struct({
  's_addr': 'ulong',
});

const struct_sockaddr_in = Struct({
  'sin_family': 'short',
  'sin_port'  : 'ushort',
  'in_addr'   : struct_in_addr,
  'sin_zero'  : 'char',
});


var redir = ffi.Library('./libredir', {
  //'main'           : [ 'int' , [ 'int', 'char* []' ] ],
  //'parse_args'     : [ 'void', [ 'int', 'char* []' ] ],
  'target_init'    : [ 'int' , [ 'char *', 'int', [ struct_sockaddr_in, "pointer" ]] ],
  'target_connect' : [ 'int' , [ 'int', [ struct_sockaddr_in, "pointer" ] ] ],
  'client_accept'  : [ 'int' , [ 'int', [ struct_sockaddr_in, "pointer" ] ] ],
  'server_socket'  : [ 'int' , [ 'char *', 'int', 'int' ] ],
});

Here's the signature of target_init as an example:

int target_init(char *addr, int port, struct sockaddr_in *target)

Here's what I'm getting:

/home/lz/redir-controller/node_modules/ref/lib/ref.js:397
    throw new TypeError('could not determine a proper "type" from: ' + JSON.stringify(type))
    ^

TypeError: could not determine a proper "type" from: [null,"pointer"]
    at coerceType (/home/lz/redir-controller/node_modules/ref/lib/ref.js:397:11)
    at Array.map (<anonymous>)

I'm using https://github.com/troglobit/redir/blob/master/redir.c and compiling with gcc -shared -fpic redir.c -o libredir.so

I suspect it's a problem with struct_sockaddr_in but everything seems ok. I even tried to do as in https://github.com/node-ffi/node-ffi/wiki/Node-FFI-Tutorial#structs by doing:

const _struct_sockaddr_in = Struct({
  'sin_family': 'short',
  'sin_port'  : 'ushort',
  'in_addr'   : struct_in_addr,
  'sin_zero'  : 'char',
});

struct_sockaddr_in = ref.refType(_struct_sockaddr_in);

but now I get

TypeError: could not determine a proper "type" from: [{"indirection":2,"name":"StructType*"},"pointer"]

Solution

  • I don't know where I took 'pointer' from, but the followin works:

    const struct_in_addr = Struct({
      's_addr': 'ulong',
    });
    
    const _struct_sockaddr_in = Struct({
      'sin_family': 'short',
      'sin_port'  : 'ushort',
      'in_addr'   : struct_in_addr,
      'sin_zero'  : 'char',
    });
    
    struct_sockaddr_in = ref.refType(_struct_sockaddr_in);
    
    const redir = ffi.Library('./libredir', {
      //'main'           : [ 'int' , [ 'int', 'char* []' ] ],
      //'parse_args'     : [ 'void', [ 'int', 'char* []' ] ],
      'target_init'    : [ 'int' , [ 'char *', 'int', struct_sockaddr_in ] ],
      'target_connect' : [ 'int' , [ 'int',  struct_sockaddr_in ] ],
      'client_accept'  : [ 'int' , [ 'int',  struct_sockaddr_in ] ],
      'server_socket'  : [ 'int' , [ 'char *', 'int', 'int' ] ],
    });