node-api使用

https://github.com/nodejs/node-addon-api

参考例子

https://github.com/nodejs/node-addon-examples

主要使用方式: node-gyp、cmake-js

macOS使用分析

hello.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <assert.h>
#include <node_api.h>

static napi_value Method(napi_env env, napi_callback_info info) {
napi_status status;
napi_value world;
status = napi_create_string_utf8(env, "world", 5, &world);
assert(status == napi_ok);
return world;
}

#define DECLARE_NAPI_METHOD(name, func) \
{ name, 0, func, 0, 0, 0, napi_default, 0 }

static napi_value Init(napi_env env, napi_value exports) {
napi_status status;
napi_property_descriptor desc = DECLARE_NAPI_METHOD("hello", Method);
status = napi_define_properties(env, exports, 1, &desc);
assert(status == napi_ok);
return exports;
}

NAPI_MODULE(NODE_GYP_MODULE_NAME, Init)
hello.js
1
2
var addon = require('./hello.node');
console.log(addon.hello());
build.sh
1
2
3
4
5
# brew install node
# clang -o hello.o hello.c -I/opt/homebrew/include/node -c
clang -c hello.c -I${HOMEBREW_PREFIX}/include/node -o hello.o
clang -undefined dynamic_lookup hello.o -o hello.node
node hello.js

使用例子

electron-cpp

写一个EventEmitter类,包含on,emit,off,once方法
https://blog.csdn.net/rraxx/article/details/115064099

NAPI 开发 C++ Addon
https://www.cnblogs.com/Asp1rant/p/14765222.html

https://github.com/nodejs/node-addon-examples.git