2010-06-30 71 views
2

我想添加功能到v8sharp項目,我有一些問題(我不是很擅長C++ - CLI,所以我很確定問題在於我缺乏C++ - CLI功能,而不是濫用V8)爲什麼這個指針指向無處?

v8value.cpp:

v8sharp::V8FunctionWrapper^ V8ValueWrapper::WrapFunction(v8::Handle<v8::Value> value) { 

    // Now we use the wrapper to make this safe to use 
    // this works 
    Console::WriteLine("IsFunction-First: {0}", value->IsFunction()); 
       // persistent so it doesn't get garbage collected 
    v8::Persistent<v8::Value> pval(value); 
       // create a function wrapper 
    V8FunctionWrapper^ bla = gcnew V8FunctionWrapper(pval); 
    return bla; 
} 

應當採用v8Handle<v8::Value>其中包含一個函數(它總是會因爲什麼調用這個函數),並返回一個不錯的.NET包裝,所以我們可以使用它在我的C#項目中。

問題就出在這裏 v8functionwrapper.cpp:

#include "v8functionwrapper.h" 
#include "v8value.h"; 


v8sharp::V8FunctionWrapper::V8FunctionWrapper(v8::Persistent<v8::Value> value) 
{ 
    // is this wrong? 
this->_value = &value; 
    // still true 
Console::WriteLine("Constructor: {0}", (*this->_value)->IsFunction()); 


} 

// This function is called by C# and triggers the javascript function 
Object^ v8sharp::V8FunctionWrapper::Call([ParamArray]array<Object ^>^args) 
{ 
// Get a refence to the function 
Console::WriteLine("Cast 2"); 
    // MEMORY VIOLATION: the _value no longer points to a valid object :(
Console::WriteLine("IsFunction: {0}", (*this->_value)->IsFunction()); 
Console::ReadLine(); 
-- snip -- 

} 

v8functionwrapper.h:

#pragma once 
#include "v8.h" 

using namespace System; 
using namespace System::Reflection; 

namespace v8sharp { 
public ref class V8FunctionWrapper 
{ 
public: 
delegate bool V8FunctionCallback(array<Object ^>^args); 
Object^ v8sharp::V8FunctionWrapper::Call([ParamArray]array<Object ^>^args); 
v8::Persistent<v8::Value> Unwrap(); 
V8FunctionWrapper(v8::Persistent<v8::Value> value); 
~V8FunctionWrapper(); 
!V8FunctionWrapper(); 

private: 
V8FunctionCallback^ _callback; 
v8::v8<Persistent::Value>* _value; 

}; 
} 

由此可見一斑線(調試代碼): Console::WriteLine("IsFunction: {0}", (*this->_value)->IsFunction()); 指針_value不再有效並導致異常。爲什麼我的指針無效?是因爲我指向構造函數中的參數並被刪除?如果是的話,我如何得到一個不會消失的指針。請記住,這是一個.net類,所以我不能混合和匹配原生類型。

+0

爲什麼那裏有星號? – 2010-06-30 01:04:06

+0

哪裏? [char limit] – 2010-06-30 01:05:08

+0

我很好奇你爲什麼使用'(* this - > _ value) - > IsFunction()'。 – 2010-06-30 01:06:58

回答

1

您需要實例化一個新的v8 :: Persistent值作爲類的成員,因爲傳入的是在堆棧中創建的,並且只要WrapFunction返回就會被銷燬。當你的對象被銷燬時,不要忘記刪除_value。

v8sharp::V8FunctionWrapper::V8FunctionWrapper(v8::Persistent<v8::Value> value) 
{ 
    this->_value = new v8::Persistent<v8::Value>(value) 
} 
+1

幾乎正確,除非你不想'gcnew'在這裏,而是新的。 – 2010-06-30 01:33:02

+0

這會產生此錯誤: '錯誤錯誤C2726:'gcnew'可能只用於創建託管類型的對象編輯:感謝logan:P – 2010-06-30 01:33:11

+0

@Logan - 謝謝我意識到這一點並儘快編輯它正如我張貼的那樣。 @Chris - 將gcnew換成新的:) – Gary 2010-06-30 01:38:51

相關問題