pmed / v8pp

Bind C++ functions and classes into V8 JavaScript engine
http://pmed.github.io/v8pp/
Other
898 stars 120 forks source link

Flexible callback argument support #49

Closed tim-janik closed 7 years ago

tim-janik commented 7 years ago

Is there a nbind::cbFunction equivalent in v8pp? I.e. as described here: https://github.com/charto/nbind#callbacks

tim-janik commented 7 years ago

As tentative answer, v8pp supports v8::Local values as bound function arguments, so there's no problem binding e.g. the following method via set():

void connect (v8::Local<v8::Function> v8value) {
  printf ("%s: expecting function: IsFunction=%d\n", __func__, v8value->IsFunction());
}
X_class.set ("connect", &Class::connect);
pmed commented 7 years ago

Yes, that's right, you can use V8 values as function arguments and return values in v8pp, something like this:

class Session
{
    void connect(std::string const& address, v8::Local<v8::Function> js_callback)
    {
       bool const success = perform_connect();
        // invoke the callback to notify JS side as js_callback(error, result)
       v8::Local<v8::Object> receiver = js_callback;
       v8::Local<v8::Value> error = success? v8::Undefined() : v8pp::throw_ex(isolate, "connect error");
       v8::Local<v8::Object> result; // fill the connect result ...      
        v8pp::call_v8(isolate,  js_callback, receiver, error, result);
    }
};

In case of asynchronous operation, you probably would have to store the callback function in some persistent handle for further invocation.