Get in C++ a constructor defined in JavaScript

41 views
Skip to first unread message

George Marques

unread,
Nov 25, 2016, 8:19:53 PM11/25/16
to v8-users
Hey, it's me again.

I'm trying to use a global JavaScript file with internal definitions from a game engine. So far so good, but I need to get one of those constructors defined in the JavaScript to create a new object in C++ land.

What I tried is something like this:

v8::Local<v8::Context> ctx = p_isolate->GetCurrentContext();
v8
::Local<v8::Function> constructor = v8::Local<v8::Function>::Cast(ctx->Global()->Get(
 v8
::String::NewFromUtf8(p_isolate, "Vector2")));

v8
::Local<v8::Value> cargs[] = { v8::Number::New(p_isolate, vec.x), v8::Number::New(p_isolate, vec.y) };
v8
::Local<v8::Object> instance = v8::Local<v8::Object>::Cast(constructor->CallAsConstructor(2, cargs));

However, this give an error as it can't find the Vector2 constructor. I can use the constructor normally in JavaScript land.

If I make the Vector2 constructor as a C++ function, this code works perfectly. However, I believe it has a better performance to reimplement those core types in JS than to keep passing around an object and calling C++ functions with a bunch of handles (I might be wrong though). This would also mitigate the memory management overhead, I think, which I haven't yet got into.

Ben Noordhuis

unread,
Nov 28, 2016, 2:59:54 AM11/28/16
to v8-users
The constructor should be visible from C++. Is your JS code wrapped in an IIFE?

George Marques

unread,
Nov 28, 2016, 1:32:52 PM11/28/16
to v8-users
No, it's not wrapped in an IIFE.

Ben Noordhuis

unread,
Nov 30, 2016, 6:23:47 AM11/30/16
to v8-users
On Mon, Nov 28, 2016 at 7:32 PM, George Marques <george...@gmail.com> wrote:
> No, it's not wrapped in an IIFE.

Okay. Can you post a complete code example? Complete as in 'compiles
and runs.'
Reply all
Reply to author
Forward
0 new messages