Node ffi pointer to struct

荒凉一梦 提交于 2019-12-24 18:59:04

问题


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"]

回答1:


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' ] ],
});


来源:https://stackoverflow.com/questions/49766938/node-ffi-pointer-to-struct

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!