Search code examples
c++v8embedded-v8

Segmentation Fault when wrapping V8 in a class?


I want to use Google's Javascript Engine V8 in a project, and attempted to write a wrapper class for the engine. Parts of the Code are copied from samples/shell.cc, from the V8 Distribution.

However, it just aborts with a Segmentation fault, and I can't figure out why, although the problem is happening around v8::internal::Top::global_context() (due to an invalid context, which appears to be NULL).. The code itself looks fine to me, but maybe I did something incredibly stupid :-).

The Segmentation fault in my Code happens in v8::Script::Compile.

Code in Question (Updated): https://gist.github.com/4c28227185a14bb6288c

Thanks to Luis G. Costantini R.'s Answer, there is no longer a problem in Set (It doesn't abort anymore), however, exposed names are still not available and will result in a ReferenceError...


Solution

  • Thy to change v8::Context::Scope context_scope(context); from the constructor (line 134) to internal_executeString (before script = v8::Script::Compile(source, name);). That because the destructor of the class v8::Context::Scope exits from the context.

    I changed the method addFunction:

    void addFunction(const std::string& fname, v8::InvocationCallback func)
    {
        v8::HandleScope handle_scope;
        std::cout << "before ::Set()" << std::endl;
        v8::Context::Scope context_scope(context);
        context->Global()->Set(v8::String::New(fname.c_str()),
                               v8::FunctionTemplate::New(func)->GetFunction());
        std::cout << "after ::Set()" << std::endl;
    }
    

    The function must be added to the global object of the context used to execute the script. There is an excellent tutorial (in two parts) of V8: http://www.homepluspower.info/2010/06/v8-javascript-engine-tutorial-part-1.html and http://www.homepluspower.info/2010/06/v8-javascript-engine-tutorial-part-2.html