[node-ffi] Using function pointers - callback

1,124 views
Skip to first unread message

Christian Guimaraes

unread,
Jul 13, 2015, 3:34:17 PM7/13/15
to nod...@googlegroups.com
Hi!

I'm trying to wrap a C library using node-ffi and I have some doubts regarding function pointers.

The C library has a following callback function:

// typedef void (*logfunc_t) (context_t *context, loglevel_t loglevel, const char *file, unsigned int line, const char *function, const char *message, void *userdata);
var logFunctionPtr = ffi.Function( ref.refType(ref.types.void), [ contextTPtr, "int", "string", "int", "string", "string", ref.refType(ref.types.void) ]);

And below the FFI definition that I did:

var myLib = ffi.Library("mylib", {
  // dc_status_t -> type int
  // dc_status_t context_set_logfunc (context_t *context, logfunc_t logfunc, void *userdata);
  "context_set_logfunc": [ "int", [ contextTPtr, logFunctionPtr, ref.refType(ref.types.void) ] ]
});

1. Is it the code above ok?

2. How should I pass the callback (as parameter, in red) to the function call? I'm trying this:

myLib.context_set_logfunc(context.ref(), ref.alloc(logFunctionPtr), null);

I'm having trouble trying to find some node-ffi examples where/how a callback function is defined and used?

Thanks.

--
Christian Guimarães


Nathan Rajlich

unread,
Jul 13, 2015, 10:30:59 PM7/13/15
to nodejs
Currently the best place for examples of ffi.Function usage would be in the test files: https://github.com/node-ffi/node-ffi/blob/master/test/function.js#L31-L42

As for your case:

 1) I believe that you need to just use "void" rather than ref.refType(ref.types.void) for the logFunctionPtr return value, since it looks like the C declaration is defined that way.
 2) When invoking context_set_logfunc(), you pass the JS function directly where the `logfunc` argument goes. So probably something like:

myLib.context_set_logfunc(context.ref(), function(context, loglevel, file, line, fn, message, userData) {
  // do something with the arguments!
}, null);

Hope that helps. Cheers!

--
Job board: http://jobs.nodejs.org/
New group rules: https://gist.github.com/othiym23/9886289#file-moderation-policy-md
Old group rules: https://github.com/joyent/node/wiki/Mailing-List-Posting-Guidelines
---
You received this message because you are subscribed to the Google Groups "nodejs" group.
To unsubscribe from this group and stop receiving emails from it, send an email to nodejs+un...@googlegroups.com.
To post to this group, send email to nod...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/nodejs/b2181056-1089-49be-838f-3bfef504235b%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Christian Guimaraes

unread,
Jul 14, 2015, 8:29:29 AM7/14/15
to nod...@googlegroups.com
Hey Nathan! 

This has helped me a lot!

Thanks.


Reply all
Reply to author
Forward
0 new messages