java

自动生成 JNI 代码

javascript

对 V8 的支持过低,仅能演示 hello-world

安装 swig

  1. # win
  2. scoop install swig

手动编译

node-gyp 手动编译单个 C++ 文件

  1. # hello.cc
  2. # 1. v8 包裹 C/C++ 代码
  3. #include <node.h>
  4. namespace demo {
  5. using v8::FunctionCallbackInfo;
  6. using v8::Isolate;
  7. using v8::Local;
  8. using v8::Object;
  9. using v8::String;
  10. using v8::Value;
  11. void Method(const FunctionCallbackInfo<Value>& args) {
  12. Isolate* isolate = args.GetIsolate();
  13. args.GetReturnValue().Set(String::NewFromUtf8(
  14. isolate, "world").ToLocalChecked());
  15. }
  16. void Initialize(Local<Object> exports) {
  17. NODE_SET_METHOD(exports, "hello", Method);
  18. }
  19. NODE_MODULE(NODE_GYP_MODULE_NAME, Initialize)
  20. } // namespace demo
  21. # binding.gyp
  22. # 2. node_gyp 配置
  23. {
  24. "targets": [
  25. {
  26. "target_name": "addon",
  27. "sources": [ "hello.cc" ]
  28. }
  29. ]
  30. }
  31. # 3. node-gyp 编译
  32. # 4. hello.js 调用
  33. const addon = require('./build/Release/addon');
  34. console.log(addon.hello());
  35. # Prints: 'world'

swig 编译

暂时需要手动编译,swig 编译生成的 wrapper 文件不支持 v8 新语法

# 生成目标文件 example.java example_wrap.c exampleJNI.java
cd simple

# 编译生成 v8 包裹的 C++ 文件
swig -c++ -javascript -node example.i

# 编译 C++ 文件为 js
node-gyp configure build

参考

  1. swig 官方教程
  2. NodeJs官方教程