为什么这个指针无处指向?

时间:2010-06-30 00:54:54

标签: .net pointers visual-c++ c++-cli v8

我正在尝试为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类,所以我不能将原生类型混合和匹配。

1 个答案:

答案 0 :(得分:1)

您需要将新的v8 :: Persistent值实例化为您的类的成员,因为您传入的值是在堆栈上创建的,并且一旦WrapFunction返回就会被销毁。当你的对象被销毁时也不要忘记删除_value。

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