1

我开始学习 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;
}

当我注释掉拦截器部分时,它工作得很好。NewInstance()它在拦截器的调用中失败。由于我是 V8 新手,如果您发现任何其他错误,也请指出。

谢谢。

4

0 回答 0