title: Calling Javascript function from a C++ callback in V8
body: <p>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. </p>
  
  <pre><code> Handle&lt;Value&gt; addEventListener( const Arguments&amp; args ) {
      HandleScope scope;
      if (!args[0]-&gt;IsFunction()) {
          return ThrowException(Exception::TypeError(String::New("Wrong arguments")));
      }
  
      Persistent&lt;Function&gt; fn = Persistent&lt;Function&gt;::New(Handle&lt;Function&gt;::Cast(args[0]));
      Local&lt;Number&gt; num = Number::New(registerListener(&amp;callback, &amp;fn));
      scope.Close(num);
  }
  </code></pre>
  
  <p>When an event happens, the following method is called. I'm assuming that this probably happens on another thread to which V8 is executing JS. </p>
  
  <pre><code>void callback(int event, void* context ) {
      HandleScope scope;
      Local&lt;Value&gt; args[] = { Local&lt;Value&gt;::New(Number::New(event)) };
      Persistent&lt;Function&gt; *func = static_cast&lt;Persistent&lt;Function&gt; *&gt;(context);
      (* func)-&gt;Call((* func), 1, args);
  
      scope.Close(Undefined());
  }
  </code></pre>
  
  <p>This causes a Segmentation fault: 11. Note that if I call the callback function directly with a reference to Persistent from addEventListener(), it executes the function correctly. </p>
  
  <p>I'm assuming that I need a Locker or Isolate? It also looks like libuv's uv_queue_work() might be able to solve this, but since I don't start the thread, I can't see how you would use it.</p>