我开始学习V8,但我一直坚持实施拦截器。我在此代码中遇到运行时错误。
#include "..\v8\\v8.h"
#include "..\common\common.h"
#include <iostream>
#include "JsPoint.h"
#include "GlobalVar.h"
int main(int argc, char *argv[]) {
if( argc != 2 ) {
std::cout << "Usage: " << argv[0] << " < js file name > \n";
return 1;
}
using namespace v8;
v8::Locker locker;
v8::HandleScope scope;
v8::Handle<ObjectTemplate> globalTemplate = v8::ObjectTemplate::New();
Local<FunctionTemplate> pointTemplate;
Local<ObjectTemplate> instanceTemplate;
// ----------- Accessor -------------------------------------------------------------------------------
pointTemplate = FunctionTemplate::New(PointConstructor);
pointTemplate->SetClassName(String::New("Point"));
instanceTemplate = pointTemplate->InstanceTemplate();
instanceTemplate->SetInternalFieldCount(1);
instanceTemplate->SetAccessor(String::New("x"), AccessorGetter(PointGetX), AccessorSetter(PointSetX));
instanceTemplate->SetAccessor(String::New("y"), AccessorGetter(PointGetY), AccessorSetter(PointSetY));
// --------------end Accessor -------------------------------------------------------------------------
// In accessor we know what is the name after . like .x and .y
// but when you do not, use interceptors.
// ----------- Interceptor ----------------------------------------------------------------------------
Handle<ObjectTemplate> globalVarTemplate = ObjectTemplate::New();
//globalVarTemplate->NewInstance();
globalVarTemplate->SetInternalFieldCount(1);
globalVarTemplate->SetNamedPropertyHandler(GetGlobalVar, SetGlobalVar);
auto it = Persistent<ObjectTemplate>::New(globalVarTemplate);
Handle<ObjectTemplate> hit = it;
Handle<Object> gv_instance = hit->NewInstance(); // **Failing HERE !!!**
Handle<External> gv_to_set = External::New(MyGlobalVar::getInstance());
gv_instance->SetInternalField(0, gv_to_set);
//-------------- end Interceptor ----------------------------------------------------------------------
globalTemplate->Set(String::New("Global"), gv_instance, ReadOnly);
globalTemplate->Set(String::New("Point"), pointTemplate, ReadOnly);
Persistent<v8::Context> context = v8::Context::New(NULL, globalTemplate);
Context::Scope cscope = Context::Scope(context);
executeScript( argv[1], context );
context.Dispose();
v8::V8::Dispose();
return 0;
}
当我评论拦截器部分时,它完美地工作。它在Interceptor的NewInstance()
调用时失败了。由于我是V8的新手,如果你发现任何其他错误,请指出它们。
感谢。