另一种常见情况是创建 JavaScript 函数来包装 C++ 函数,并返回到 JavaScript:

    1. // addon.cc
    2. #include <node.h>
    3. namespace demo {
    4. using v8::Context;
    5. using v8::Function;
    6. using v8::FunctionCallbackInfo;
    7. using v8::FunctionTemplate;
    8. using v8::Isolate;
    9. using v8::Local;
    10. using v8::Object;
    11. using v8::String;
    12. using v8::Value;
    13. void MyFunction(const FunctionCallbackInfo<Value>& args) {
    14. Isolate* isolate = args.GetIsolate();
    15. args.GetReturnValue().Set(String::NewFromUtf8(
    16. isolate, "hello world").ToLocalChecked());
    17. }
    18. void CreateFunction(const FunctionCallbackInfo<Value>& args) {
    19. Isolate* isolate = args.GetIsolate();
    20. Local<Context> context = isolate->GetCurrentContext();
    21. Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, MyFunction);
    22. Local<Function> fn = tpl->GetFunction(context).ToLocalChecked();
    23. // 可以省略这步使它匿名
    24. fn->SetName(String::NewFromUtf8(
    25. isolate, "theFunction").ToLocalChecked());
    26. args.GetReturnValue().Set(fn);
    27. }
    28. void Init(Local<Object> exports, Local<Object> module) {
    29. NODE_SET_METHOD(module, "exports", CreateFunction);
    30. }
    31. NODE_MODULE(NODE_GYP_MODULE_NAME, Init)
    32. } // namespace demo

    测试它:

    1. // test.js
    2. const addon = require('./build/Release/addon');
    3. const fn = addon();
    4. console.log(fn());
    5. // 打印: 'hello world'