我正在尝试向 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 类,因此我无法在其中混合和匹配本机类型。