Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node-ffi:call c lib with callback function

Tags:

node-ffi

I want call a c lib,the .h file like this:

typedef void (*ConnectEventCallBack)(int iBaseID, int iMode, const char* sInfo);

extern "C" __declspec(dllexport) void SetConnectEventCallBack(ConnectEventCallBack cb);

in node-ffi,how to define the function and use it?

like image 356
kom551 Avatar asked Jan 22 '26 06:01

kom551


1 Answers

You can do it in this way:

var ffi = require('ffi');

// Interface into the native lib
var libname = ffi.Library('./libname', {
  'SetConnectEventCallBack': ['void', ['pointer']]
});

// Callback from the native lib back into js
var callback = ffi.Callback('void', ['int', 'int', 'string'],
  function(iBaseId, iMode, sInfo) {

    console.log("iBaseId: ", iBaseId);
    console.log("iMode: ", iMode);
    console.log("sInfo: ", sInfo);

  });

console.log("registering the callback");
libname.SetConnectEventCallBack(callback);
console.log('Done');

// Make an extra reference to the callback pointer to avoid GC
process.on('exit', function() {
  callback
});

The C library can call this callback using another thread. It is safe. In this case the javascript function for the callback will be fired in the main event loop and the caller thread will wait until the call returns. The return value is passed to the caller thread too.

Note that you need to keep a reference to the callback pointer returned by ffi.Callback in some way to avoid garbage collection.

like image 187
Bernardo Ramos Avatar answered Jan 26 '26 11:01

Bernardo Ramos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!