nodejs 可以通过FFI 库调用so 文件里的函数,一般来说注意下nodejs参数类型和C语言参数类型转换就好了。
但是对于回调函数,就稍微复杂一点。
一种情况是so 里面的函数作为回调函数被nodejs 调用。
这种方式在FFI 教程里面有提及。
signature:
ffi.Callback(returnType, [ arg1Type, arg2Type, ... ], function);
Example:
var ffi = require('ffi');
// Interface into the native lib
var libname = ffi.Library('./libname', {
'setCallback': ['void', ['pointer']]
});
// Callback from the native lib back into js
var callback = ffi.Callback('void', ['int', 'string'],
function(id, name) {
console.log("id: ", id);
console.log("name: ", name);
});
console.log("registering the callback");
libname.setCallback(callback);
console.log('done');
// Make an extra reference to the callback pointer to avoid GC
process.on('exit', function() {
callback
});
另外一种情况是 so里面的函数需要回调函数,而这个回调函数来自nodejs里面的函数。
这里提供一个方式来处理这种问题,就是 nodejs 调用代理so文件,再由代理so 调用目标so文件。
比如,我们想调用test.so 里面的abc 函数,而这 abc 函数需要回调函数作为参数。我们可以创建test-agent.so ,这个so 主要负责nodejs和C 之间参数类型转换和函数绑定,然后test-agent.so再调用test.so.
这样的话可以nodejs的函数可以作为C 语言函数的回调函数了。