Closed
Description
Not sure if this is an issue of napi
or node-addon-api
, but we found this when using node-addon-api
so I post it here.
The code below:
#include <napi.h>
class MyObject : public Napi::ObjectWrap<MyObject> {
public:
static Napi::Object Init(Napi::Env env, Napi::Object exports);
MyObject(const Napi::CallbackInfo& info);
~MyObject();
};
Napi::Object MyObject::Init(Napi::Env env, Napi::Object exports) {
Napi::Function func =
DefineClass(env,
"MyObject",
{});
Napi::FunctionReference* constructor = new Napi::FunctionReference();
*constructor = Napi::Persistent(func);
env.SetInstanceData(constructor);
exports.Set("MyObject", func);
return exports;
}
MyObject::MyObject(const Napi::CallbackInfo& info)
: Napi::ObjectWrap<MyObject>(info) {
this->Ref(); // Nothing special except that we Ref() here to keep this object from been garbage collected while other resources still alive
}
MyObject::~MyObject() {
uint32_t count = -1;
count = this->Unref(); // And Unref() in destructor.
fprintf(stderr, "count %d\n", count); // Log the count.
}
Napi::Object InitAll(Napi::Env env, Napi::Object exports) {
return MyObject::Init(env, exports);
}
NODE_API_MODULE(addon, InitAll)
var addon = require('bindings')('addon');
new addon.MyObject(10); // Create an instance and wait the process to exit.
Running the code in Node.js 14.16 will get:
count 0
In Node.js 14.17, the result becomes:
count 1
Though the code snippet doesn't throw here, in our real programs, running similar codes in Node.js 14.17 causes:
When enable cpp exceptions i.e. NAPI_CPP_EXCEPTIONS
, run the script will result in:
// Mac
libc++abi.dylib: terminating with uncaught exception of type Napi::Error
// Debian
terminate called after throwing an instance of 'Napi::Error'
what(): Unknown failure
Aborted (core dumped)