另一种常见情况是创建 JavaScript 函数来包装 C++ 函数,并返回到 JavaScript:
// addon.cc#include <node.h>namespace demo {using v8::Context;using v8::Function;using v8::FunctionCallbackInfo;using v8::FunctionTemplate;using v8::Isolate;using v8::Local;using v8::Object;using v8::String;using v8::Value;void MyFunction(const FunctionCallbackInfo<Value>& args) {Isolate* isolate = args.GetIsolate();args.GetReturnValue().Set(String::NewFromUtf8(isolate, "hello world").ToLocalChecked());}void CreateFunction(const FunctionCallbackInfo<Value>& args) {Isolate* isolate = args.GetIsolate();Local<Context> context = isolate->GetCurrentContext();Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, MyFunction);Local<Function> fn = tpl->GetFunction(context).ToLocalChecked();// 可以省略这步使它匿名fn->SetName(String::NewFromUtf8(isolate, "theFunction").ToLocalChecked());args.GetReturnValue().Set(fn);}void Init(Local<Object> exports, Local<Object> module) {NODE_SET_METHOD(module, "exports", CreateFunction);}NODE_MODULE(NODE_GYP_MODULE_NAME, Init)} // namespace demo
测试它:
// test.jsconst addon = require('./build/Release/addon');const fn = addon();console.log(fn());// 打印: 'hello world'
