Node.js插件对象销毁

Node.js addon object destruction

本文关键字:对象 插件 js Node      更新时间:2023-10-16

我正在编写一个GPU数据库,并考虑使用javascript作为使用node.js.进行查询的语言

我一直在写一个节点插件,就像我在C++中写GPU数据库一样。然而,我的node.js插件有问题,因为我的c++对象没有被破坏,而是只有在我没有显式使用新运算符的情况下。如果我使用新运算符,那没关系,只是当调用一个创建新方法的方法时,比如copy()等。我使用V8::AdjustAmountOfExternalAllocatedMemory(size())来指示V8我已经分配了外部内存(在GPU上)。

请给我一些建议。

1.正确释放GPU内存的代码

这段代码通过调用对象析构函数正确地释放GPU内存,该函数调用以释放GPU内存:

var gpudb = require('./build/Release/gpudb');
var n = 1000000;
for (var i = 0; i < 10000; ++i) {
var col = new gpudb.GpuArray(n);
}

2.然而,这段代码并没有调用对象的析构函数来释放GPU内存

var gpudb = require('./build/Release/gpudb');
var n = 1000000;
var col = new gpudb.GpuArray(n);
for (var i = 0; i < 10000; ++i) {
var copyOfCol = col.copy();
}

3.现在,这里分别是构造函数和复制函数的函数

Handle<Value> GpuVector::New(const Arguments& args) {
HandleScope scope;
if (args.IsConstructCall()) {
// Invoked as constructor: `new GpuVector(...)`
int value = args[0]->IsUndefined() ? 0 : args[0]->NumberValue();
GpuVector* obj = new GpuVector(value);
obj->Wrap(args.This());
return args.This();
} else {
// Invoked as plain function `GpuVector(...)`, turn into construct call.
const int argc = 1;
Local<Value> argv[argc] = { args[0] };
return scope.Close(constructor->NewInstance(argc, argv));
}
}
Handle<Value> GpuArray::Copy(const Arguments& args) {
HandleScope scope;
GpuArray* in = ObjectWrap::Unwrap<GpuVector>(args.This());
GpuArray* out = new GpuArray(in); // creates new gpu memory slot and copies the data over
out->Wrap(args.This());
return args.This();
}

如果没有GpuArray构造函数,就很难判断出了什么问题。

但我可以看到一些不正确的东西:

Handle<Value> GpuArray::Copy(const Arguments& args) {
//...
GpuArray* in = ObjectWrap::Unwrap<GpuVector>(args.This());
//...
}

您正在从GpuArray对象中打开GpuVector对象,这是错误的。

Wrappe/Unwrap方法应该用于在c++对象和它们各自的js对象之间建立连接,而不是在不同的对象之间。

从你发布的代码来看,你试图克隆对象(但我可能错了),如果我是对的,应该这样做:

Handle<Value> GpuArray::Copy(const Arguments& args) {
HandleScope scope;
GpuArray* in = ObjectWrap::Unwrap<GpuArray>( args.This() );
//build argc and argv here
Local<Object> outJs = constructorOfGpuArray->NewInstance( argc, argv );
GpuArray* out = ObjectWrap::Unwrap<GpuArray>( outJs );
//set members/etc of the "out" object so it looks identical to the "in" object
//return the js object to the caller.
return scope.Close( outJs );
}

我没有测试代码,但理论上它应该可以运行。