在 Node.js 里“调原生库”一般指两种方式:
.node 文件,在 JS 里 require 使用下面分别说。
N-API 是 Node 官方稳定 ABI,不随 Node 版本频繁变动。
addon.c
#include <node_api.h>
napi_value Add(napi_env env, napi_callback_info info) {
napi_value result;
int sum = 3 + 4;
napi_create_int32(env, sum, &result);
return result;
}
napi_value Init(napi_env env, napi_value exports) {
napi_value fn;
napi_create_function(env, NULL, 0, Add, NULL, &fn);
napi_set_named_property(env, exports, "add", fn);
return exports;
}
NAPI_MODULE(NODE_GYP_MODULE_NAME, Init)
binding.gyp
{
"targets": [{
"target_name": "addon",
"sources": ["addon.c"]
}]
}
构建
npm install -g node-gyp
node-gyp configure
node-gyp build
JS 使用
const addon = require('./build/Release/addon.node');
console.log(addon.add()); // 7
#include <napi.h>
Napi::Number Add(const Napi::CallbackInfo& info) {
return Napi::Number::New(info.Env(), 3 + 4);
}
Napi::Object Init(Napi::Env env, Napi::Object exports) {
exports.Set("add", Napi::Function::New(env, Add));
return exports;
}
NODE_API_MODULE(addon, Init)
使用 napi-rs 或 neon
#[napi]
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
构建:
npm run build
JS:
import { add } from './index.js'
add(1, 2)
✅ 优点:内存安全、跨平台、易维护
ffi-napiconst ffi = require('ffi-napi');
const lib = ffi.Library('./libfoo.so', {
foo: ['int', ['int', 'int']]
});
console.log(lib.foo(1, 2));
⚠️ 注意:
ffi-napi 只支持 N-API 的旧版本const { execFileSync } = require('child_process');
const out = execFileSync('./mylib_cli', ['arg1', 'arg2']);
适合:
| 场景 | 推荐 |
|---|---|
| 新写高性能模块 | N-API / Rust |
| 已有 C/C++ 库 | Addon 封装 |
| 快速调用 | FFI |
| 不稳定 / 隔离 | 子进程 |
| 跨语言 | Rust + napi-rs |
如果你说的是:
告诉我具体场景,我可以直接给你可跑的示例。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。