use*_*260 1 c node.js node-ffi node.js-addon
我试图弄清楚如何在 C 库和 NodeJS 模块之间传递数据。我可以通过 NodeFFI 模块执行此操作吗?
或者我是否必须编写自己的 NodeJS 插件来开发 C-NodeJS 接口?
文档node-ffi指出:
node-ffi是一个 Node.js 插件,用于使用纯 JavaScript 加载和调用动态库。它可用于创建与本机库的绑定,而无需编写任何 C++ 代码。
您只需要按照node-ffi其他地方的说明和通过结果访问库。在他们的来源中,他们有一个例子。假设它们位于同一目录中:
文件factorial.c:
#include <stdint.h>
uint64_t factorial(int max) {
int i = max;
uint64_t result = 1;
while (i >= 2) {
result *= i--;
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
文件factorial.js:
//load the ffi module
var ffi = require('ffi');
//include the function
var libfactorial = ffi.Library('./libfactorial', {
'factorial': [ 'uint64', [ 'int' ] ]
});
if (process.argv.length < 3) {
console.log('Arguments: ' + process.argv[0] + ' ' + process.argv[1] + ' <max>');
process.exit();
};
//usage of the function
var output = libfactorial.factorial(parseInt(process.argv[2]));
console.log('Your output: ' + output);
Run Code Online (Sandbox Code Playgroud)
使用该模块,C 文件加载如下:
var libfactorial = ffi.Library('./libfactorial', {
'factorial': [ 'uint64', [ 'int' ] ]
});
Run Code Online (Sandbox Code Playgroud)
然后像这样访问:
//process.argv are the command line arguments
var argument = parseInt(process.argv[2]);
var output = libfactorial.factorial(argument);
Run Code Online (Sandbox Code Playgroud)