2011-09-02 44 views
0

我读过教程“编写的Node.js原生扩展”:https://www.cloudkick.com/blog/2010/aug/23/writing-nodejs-native-extensions本地C++扩展的Node.js:在构造函数中“克隆”本地< Value >

代码工作的罚款(https://github.com/pquerna/node-extension-examples/blob/master/helloworld/helloworld.cc

现在我想改变:

class HelloWorld: ObjectWrap 
{ 
private: 
    int m_count; 
public: 
(...) 
HelloWorld() : 
    m_count(0) 
    { 
    } 
(...) 
static Handle<Value> Hello(const Arguments& args) 
    { 
    HandleScope scope; 
    HelloWorld* hw = ObjectWrap::Unwrap<HelloWorld>(args.This()); 
    hw->m_count++; 
    Local<String> result = String::New("Hello World"); 
    return scope.Close(result); 
    } 
(...) 
} 

到类似的东西(在构造函数中复制参数和返回它“你好()”):

class HelloWorld: ObjectWrap 
{ 
private: 
    Local<Value> myval;/* <===================== */ 
public: 
(...) 
HelloWorld(const Local<Value>& v) : 
    myval(v) /* <===================== */ 
    { 
    } 
(...) 
static Handle<Value> Hello(const Arguments& args) 
    { 
    HandleScope scope; 
    HelloWorld* hw = ObjectWrap::Unwrap<HelloWorld>(args.This()); 
    return scope.Close(hw->myval);/* <===================== */ 
    } 
(...) 
} 

我的代码似乎没有工作,你好()似乎返回一个整数

var h=require("helloworld"); 
var H=new h.HelloWorld("test"); 
console.log(H.hello()); 

什么是在构造函数中复制设为myVal和返回功能设为myVal正道“你好()” ?我应该在析构函数中管理一些东西吗?

谢谢。

皮埃尔

+0

您是否尝试过在构造函数中使用'args.This()'?自从我修改了V8 C++扩展之后,这已经有一段时间了,但是由于您没有在实际实例上设置myval,所以会发生这种情况。 –

回答

1

“本地”变量将被自动清除,所以你不能只保存它们的副本这样。你需要使用'持久'手柄。

class HelloWorld: ObjectWrap 
{ 
private: 
    Persistent<Value> myval; 
public: 
(...) 
    HelloWorld(const Local<Value>& v) : 
    myval(Persistent<Value>::New(v)) { 

    } 
(...) 
static Handle<Value> Hello(const Arguments& args) 
    { 
    HandleScope scope; 
    HelloWorld* hw = ObjectWrap::Unwrap<HelloWorld>(args.This()); 
    return scope.Close(hw->myval); 
    } 
(...) 
} 
+0

它工作。谢谢 ! – Pierre