我在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的垃圾收集器想要它.我该怎么做?