2011-09-02 46 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