c – node.js native addon – 包装类的析构函数不运行

前端之家收集整理的这篇文章主要介绍了c – node.js native addon – 包装类的析构函数不运行前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在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的垃圾收集器想要它.我该怎么做?

解决方法

V8中无法保证垃圾收集 – 只有在引擎内存不足时才会执行垃圾收集.不幸的是,这意味着如果您需要释放资源,您可能必须手动调用发布函数 – 这对JS API的用户来说不会太大. (您可以将它附加到process.on(‘exit’)以确保它被调用.)

Commentary on V8

原文链接:https://www.f2er.com/c/118107.html

猜你在找的C&C++相关文章