v8toolkit  0.0.1
Utility library for embedding V8 Javascript engine in a c++ program
casts_impl.hpp
Go to the documentation of this file.
1 #pragma once
2 
3 namespace v8toolkit {
4 
5 template<class Return, class... Params>
6 std::function<Return(Params...)> CastToNative<std::function<Return(Params...)>>::operator()(v8::Isolate * isolate, v8::Local<v8::Value> value) const {
7  auto js_function = v8toolkit::get_value_as<v8::Function>(value);
8 
9  // v8::Global's aren't copyable, but shared pointers to them are. std::functions need everything in them to be copyable
10  auto context = isolate->GetCurrentContext();
11  auto shared_global_function = std::make_shared<v8::Global<v8::Function>>(isolate, js_function);
12  auto shared_global_context = std::make_shared<v8::Global<v8::Context>>(isolate, context);
13 
14  return [isolate, shared_global_function, shared_global_context](Params... params) ->Return {
15  v8::Locker locker(isolate);
16  v8::HandleScope sc(isolate);
17  auto context = shared_global_context->Get(isolate);
18  return v8toolkit::scoped_run(isolate, context, [&]() ->Return {
19  assert(!context.IsEmpty());
20  auto result = v8toolkit::call_javascript_function(context,
21  shared_global_function->Get(isolate),
22  context->Global(),
23  std::tuple<Params...>(params...));
24  return CastToNative<Return>()(isolate, result);
25  });
26  };
27 }
28 
29 } // end v8toolkit namespace
auto scoped_run(v8::Isolate *isolate, T callable) -> typename std::result_of< T()>::type
Definition: v8toolkit.h:111
internal::ReturnAction< R > Return(R value)
v8::Local< v8::Value > call_javascript_function(const v8::Local< v8::Context > context, const v8::Local< v8::Function > function, const v8::Local< v8::Object > receiver, const TupleType &tuple={})
Definition: v8toolkit.h:550