【问题标题】:Node.js addon object destructionNode.js 插件对象销毁
【发布时间】:2014-03-29 20:53:00
【问题描述】:

我正在编写一个 GPU 数据库并研究使用 javascript 作为语言来查询使用 node.js。

我一直在编写节点插件,因为我已经用 C++ 编写了 GPU 数据库。但是我的 node.js 插件有问题,因为我的 c++ 对象没有被破坏,但只有当我没有明确使用 new 运算符时。如果我使用 new 运算符,那很好,只是在调用创建新方法的方法时——比如 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();
}

【问题讨论】:

    标签: c++ node.js v8 embedded-v8


    【解决方案1】:

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

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

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

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

    Wrap/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 );
    }
    

    我没有测试代码,但它应该理论上可以工作

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-11
      • 2013-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-27
      相关资源
      最近更新 更多