我想添加功能到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