我使用一个节点插件返回多个对象。
#include <napi.h>
#include "myobject.h"
#include "myobject1.h"
#include "myobject2.h"
#include <iostream>
Napi::Object CreateObject(const Napi::CallbackInfo& info)
{
int num = info[0].As<Napi::Number>().Int32Value();
switch (num)
{
case 1:
std::cout << "Object 1" << std::endl;
return MyObject::NewInstance(info.Env(), info[0]);
break;
case 2:
std::cout << "Object 2" << std::endl;
return MyObject1::NewInstance(info.Env(), info[0]);
break;
case 3:
std::cout << "Object 3" << std::endl;
return MyObject2::NewInstance(info.Env(), info[0]);
break;
}
}
Napi::Object InitAll(Napi::Env env, Napi::Object exports) {
Napi::Object new_exports = Napi::Function::New(env, CreateObject, "CreateObject");
return MyObject::Init(env, new_exports);
}
NODE_API_MODULE(addon, InitAll)
使用上述代码的 js 文件是这样的。
var createObject = require('bindings')('addon');
var obj = createObject(1);
var obj2 = createObject(2);
var obj3 = createObject(3);
插件代码编译得很好,但是 js 给出了以下错误。致命错误:错误::新 napi_get_last_error_info 1: 00007FF68F1F046F napi_wrap+109311 2: 00007FF68F195156 v8::internal::OrderedHashTable<v8::internal::OrderedHashMap,2>::NumberOfElementsOffset+33302 3: 00007FF68F195156 : 00007FF68F1957C9 v8::internal::OrderedHashTable<v8::internal::OrderedHashMap,2>::NumberOfElementsOffset+34953 5: 00007FF68F1BE2EC napi_fatal_error+156 6: 00007FF8677D14E7 public: static void __cdecl Napi::Error::F __ptr64,char const * __ptr64)+23 7: 00007FF8677D1475 public: 静态类 Napi::Error cdecl Napi::Error::New(struct napi_env* __ptr64)+421 8: 00007FF8677D413C Napi::EscapableHandleScope::EscapableHandleScope+60 [C:\Project\abi-stable-node-addon-examples-master\7_factory_wrap\node-addon-api\node_modules\node-addon-api \napi-inl.h]:L3445