node-ffi:使用回调函数调用c lib

时间:2016-04-24 05:38:05

标签: node-ffi

我想调用一个c lib,像这样的.h文件:

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

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

在node-ffi中,如何定义函数并使用它?

1 个答案:

答案 0 :(得分:1)

你可以这样做:

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
});

C库可以使用另一个线程调用此回调。这很安全。在这种情况下,回调的javascript函数将在主事件循环中触发,调用者线程将等待调用返回。返回值也传递给调用者线程。

请注意,您需要以某种方式保留对ffi.Callback返回的回调指针的引用,以避免垃圾回收。

相关问题