2013-04-29 70 views
-1

我想弄清楚如何在C库和NodeJS模块之间传递数据。 我可以通过NodeFFI模块做到吗?NodeJS-C接口

或者我将不得不编写自己的NodeJS插件来开发C-NodeJS接口?

回答

4

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

文件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); 

使用的模块,C文件被加载这样的:

var libfactorial = ffi.Library('./libfactorial', { 
    'factorial': [ 'uint64', [ 'int' ] ] 
}); 

然后像这样访问:

//process.argv are the command line arguments 
var argument = parseInt(process.argv[2]); 
var output = libfactorial.factorial(argument);