Run script in different context than it was compiled (or: reuse compiled scripts in different contexts)

277 views
Skip to first unread message

George Marques

unread,
Nov 13, 2016, 6:48:38 PM11/13/16
to v8-users
For starters, I want two things:
  1. Have a JS file with global functions to use in my application. I already the global object set with the C++ functions, but also need to mix the JS ones since it's a lot faster sometimes.
  2. Have a module system akin to Node.js/CommonJS and load JS files from the file system.
Also, I want both of those things to work across multiple contexts, since each script in my application runs in a different context and I have a bunch of scripts.

So, I expected that it would be possible to pre-compile a script in one temporary context then run it in each of the other contexts to add the global functions. It turned out that none of my tests to do so worked (and I really don't understand the cryptic error messages I get, something like that == 0 || (*reinterpret_cast<v8::internal::Object* const*>(that))->IsJSFunction() and similar stuff). Tried to use the same security token in both contexts, use ScriptCompiler::CompileUnbound() and Script::GetUnboundScript() (those failed when using BindToCurrentContext() later).

Maybe there's a better way to do this, but I am completely thrown off by the absence of documentation and reference material (or my inability to find them, though I accomplished quite a lot until now without needing to ask). Anyway, if there's some easy and fast way to do both of my points above without context-switching then please point me the way.

My main question that (I think) will solve my problem: How to share a compiled script between different contexts?

Thanks in advance.

Yang Guo

unread,
Nov 14, 2016, 1:55:33 AM11/14/16
to v8-users
If you are only interested in sharing code between contexts, but not actual objects, you don't have to set security tokens. You can use ScriptCompiler::CompileUnboundScript to compile a script. The compile result can be then bound to a context via UnboundScript::BindToCurrentContext and run.

Cheers,

Yang

George Marques

unread,
Nov 14, 2016, 10:21:01 AM11/14/16
to v8-users
I had tried that earlier but got an error when calling BindToCurrentContext. I'm gonna make a few more tests to see if I can make it work like that. Thanks for the suggestion.

George Marques

unread,
Nov 14, 2016, 3:36:08 PM11/14/16
to v8-users
That actually worked on my project though not on my test code. I'll take that as a win, thanks for the suggestion.


On Monday, November 14, 2016 at 4:55:33 AM UTC-2, Yang Guo wrote:
Reply all
Reply to author
Forward
0 new messages