node.js本地addon - 析构函数的包类不运行 [英] node.js native addon - destructor of wrapped class doesn't run

查看:245
本文介绍了node.js本地addon - 析构函数的包类不运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm writing a node.js addon in C++. I wrap some class instances using node::ObjectWrap, to associate the native instance with a javascript object. My problem is, the wrapped instance's destructor never runs.

这里是一个例子:

.cc

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的垃圾收藏家希望它。

I assume I have to set up an WeakPointerCallback, that deletes the manually allocated object, if the V8's garbage collector wants it to. How am I supposed to do that?

推荐答案

V8中无法保证垃圾收集 - 只有在引擎耗尽时才会执行的内存。不幸的是,如果您需要释放资源,您可能需要手动调用释放功能 - 这对于JS API的用户来说不会太大。 (您可以将其附加到process.on('exit'),以确保它被调用。)

Garbage collection is not guaranteed in V8 - it's only executed when the engine is running out of memory. Unfortunately that means you'll probably have to call a release function manually if you need to release resources - which would not be too great for the users of a JS API. (You can attach it to process.on('exit') to make sure it gets called.)

V8评论

这篇关于node.js本地addon - 析构函数的包类不运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆