节点.js本机插件 - 包装类的析构函数不运行
node.js native addon - destructor of wrapped class doesn't run
我正在用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);
};
. 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注释
相关文章:
- 使用 boost::thread 运行函子,但析构函数被错误地调用
- 如何在关闭Qt控制台应用程序之前运行我的析构函数?
- 析构函数在 lambda 捕获说明符中声明的类实例上运行两次
- 为什么析构函数在删除对象之前运行
- 是否可以在析构函数运行时不销毁 obj
- 在类中运行析构函数时退出程序
- CArray的析构函数运行大约需要30秒
- 离开 c++ 应用程序而不运行全局静态对象的析构函数
- 析构函数在应用程序出口处重新运行
- 向量:清除/pop_back不会运行析构函数
- boost::asio::io_service析构函数运行很长时间
- 在纯虚拟类的析构函数中等待线程死亡会导致运行时错误
- C++-在基元上运行析构函数
- C++析构函数运行时错误:无法munmap
- 添加析构函数定义将创建运行异常
- 是否有可能在c++中调用delete时阻止析构函数运行?
- 调用exit()时是否运行析构函数
- 节点.js本机插件 - 包装类的析构函数不运行
- 导致运行时错误的析构函数
- 在析构函数中调用CloseHandle会导致运行时内存错误,即如何正确关闭结构/类中的文件句柄