V8 C ++嵌入问题 [英] V8 C++ embedding issues

查看:124
本文介绍了V8 C ++嵌入问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是V8嵌入的新手,并且刚开始用V8库替换我当前的脚本语言.但是,我遇到了一些非常奇怪的问题(至少对我来说).有点像我是做自己正在做的事情的唯一人,我感觉自己在做愚蠢的事情.

I am new to V8 embedding, and have just started to replace my current scripting language with the V8 library. However I am running into some really odd (For me at least) issues. It kinda feels like I am the only one doing what I am doing and I feel like I am doing something stupid.

我制作了一个包装器类,用于包装V8引擎函数并在构造包装器时构造引擎(尝试忽略低劣的变量名或愚蠢的样式):

I have made a wrapper class to wrap V8 engine functions and to construct the engine when my wrapper is constructed (Try to ignore shitty variable names or silly styles):

engine.h:

namespace JSEngine {

class Engine
{
    public:
        Engine();
        virtual ~Engine();
        v8::Isolate* isolate;
        v8::Handle<v8::Context> context;
};
}

engine.cpp(其中包含engine.h):

engine.cpp (Which includes engine.h):

JSEngine::Engine::Engine()
{   
    v8::Locker locker();
    V8::Initialize();

    this->isolate = Isolate::GetCurrent();
    HandleScope scope(this->isolate);

    this->context = Context::New(this->isolate);
}

该代码很好用,但是一旦我尝试过:

That code is fine and dandy, however once I try this:

Server::jsEngine = new JSEngine::Engine();
HandleScope scope(Server::jsEngine->isolate);
Context::Scope context_scope(Server::jsEngine->context);

Handle<String> source = String::NewFromUtf8(Server::jsEngine->isolate, "'Hello' + ', World!'");
Handle<Script> script = Script::Compile(source);
Handle<Value> result = script->Run();

String::Utf8Value utf8(result);
printf("%s\n", *utf8);

我在此行出现SEGMENTATION FAULT:Context::Scope context_scope(Server::jsEngine->context);

I get SEGMENTATION FAULT on this line: Context::Scope context_scope(Server::jsEngine->context);

我不知道我在做什么错,或者这种方法是否是最佳实践.您能帮我解决SEGMENTATION FAULT错误吗?

I have no idea what I am doing wrong or if this approach is even best practice. Could you help me solve the SEGMENTATION FAULT error please?

推荐答案

您的上下文成员变量是本地句柄,在本地作用域中创建,并且在您的Engine构造函数完成后就无效,因为该作用域已被删除.您需要针对您的上下文的持久句柄.更改您的引擎声明以使用

Your context member variable is a local handle, created in the local scope and is invalid as soon as your Engine constructor completes because the scope is deleted. You need a persistent handle for your context. Change your Engine declaration to use

v8::Persistent<v8::Context> context;

,当您实际创建上下文时,请使用

and when you actually create the context, use

this->context.Reset(this->isolate, Context::New(this->isolate));

并在析构函数中使用

this->context.Reset();

这篇关于V8 C ++嵌入问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆