node.js native addon – 包装类的析构函数不运行

我正在用C ++编写node.js插件。 我使用node :: ObjectWrap封装了一些类实例,将本地实​​例与一个javascript对象关联起来。 我的问题是,包装的实例的析构函数从不运行。

这里是一个例子:

point.cc

#include <node.h> #include <v8.h> #include <iostream> using namespace v8; using namespace node; class Point :ObjectWrap { protected: int x; int y; public: Point(int x, int y) :x(x), y(y) { std::cout << "point constructs" << std::endl; } ~Point() { std::cout << "point destructs" << std::endl; } static Handle<Value> New(const Arguments &args){ HandleScope scope; // arg check is omitted for brevity Point *point = new Point(args[0]->Int32Value(), args[1]->Int32Value()); point->Wrap(args.This()); return scope.Close(args.This()); } static void Initialize(Handle<Object> target){ HandleScope scope; Local<FunctionTemplate> t = FunctionTemplate::New(New); t->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(t, "get", Point::get); target->Set(String::NewSymbol("Point"), t->GetFunction()); } static Handle<Value> get(const Arguments &args){ HandleScope scope; Point *p = ObjectWrap::Unwrap<Point>(args.This()); Local<Object> result = Object::New(); result->Set(v8::String::New("x"), v8::Integer::New(p->x)); result->Set(v8::String::New("y"), v8::Integer::New(p->y)); return scope.Close(result); } }; extern "C" void init(Handle<Object> target) { HandleScope scope; Point::Initialize(target); }; 

test.js

 var pointer = require('./build/default/point'); var p = new pointer.Point(1,2); console.log(p.get()); 

我假设我必须设置一个WeakPointerCallback,如果V8的垃圾收集器想要的话,它会删除手动分配的对象。 我该怎么做?

垃圾收集在V8中不能保证 – 只有当引擎内存不足时才会执行垃圾收集。 不幸的是,这意味着如果你需要释放资源,你可能需要手动调用一个发布函数 – 对于一个JS API的用户来说这不会太好。 (你可以附加到process.on('exit')来确保它被调用。)

V8评论