我想添加功能到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類,所以我不能混合和匹配原生類型。
爲什麼那裏有星號? – 2010-06-30 01:04:06
哪裏? [char limit] – 2010-06-30 01:05:08
我很好奇你爲什麼使用'(* this - > _ value) - > IsFunction()'。 – 2010-06-30 01:06:58