Calling Javascript function from a C++ callback in V8

前端 未结 3 559
花落未央
花落未央 2020-12-14 04:10

I\'m trying to call a registered JS function when a c++ callback is called, but I\'m getting a segfault for what I assume is a scoping issue.

 Handle

        
3条回答
  •  不知归路
    2020-12-14 05:03

    When you declare Persistent fn in your code, fn is a stack-allocated variable.

    fn is a Persistent, which is a handle class, and it will contain a pointer to some heap-allocated value of type Function, but fn itself is on the stack.

    This means that when you call registerListener(&callback, &fn), &fn is taking the address of the handle (type Persistent), not the address of the Function on the heap. When your function exits, the handle will be destroyed but the Function itself will remain on the heap.

    So as a fix, I suggest passing the address of the Function instead of the address of the handle, like this:

    Persistent fn = Persistent::New(Handle::Cast(args[0]));
    Local num = Number::New(registerListener(&callback, *fn));
    

    (note that operator* on a Persistent returns a T* rather than the more conventional T&, c.f. http://bespin.cz/~ondras/html/classv8_1_1Handle.html)

    You'll also have to adjust callback to account for the fact that context is now a raw pointer to a Function, like this:

    Persistent func = static_cast(context);
    func->Call((* func), 1, args);
    

    Creating a Persistent from a raw Function pointer here is OK because we know that context is actually a persistent object.

    I've also changed (*func)->Call(...) to func->Call(...) for brevity; they do the same thing for V8 handles.

提交回复
热议问题