2010-06-30 46 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

相关问题