How can I bind functions on the fly?

512 views
Skip to first unread message

danijar

unread,
Apr 1, 2013, 9:20:12 AM4/1/13
to v8-u...@googlegroups.com
This is a very brief question about V8. I know how to bind function templates to a context at the time creating that context.

v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::HandleScope handle_scope(isolate);
globals = v8::Persistent<v8::ObjectTemplate>::New(isolate, v8::ObjectTemplate::New());
globals->Set(v8::String::New(Name.c_str()), v8::FunctionTemplate::New(function));
context = v8::Context::New(NULL, globals);
context->Enter();


But is there a way to bind C++ functions to an already created context at runtime? Or maybe it is possible to recreate the context and adopt the state of the old context to a new one?

Stephan Beal

unread,
Apr 1, 2013, 9:49:41 AM4/1/13
to v8-u...@googlegroups.com
On Mon, Apr 1, 2013 at 3:20 PM, danijar <pfi...@gmail.com> wrote:
But is there a way to bind C++ functions to an already created context at runtime? Or maybe it is possible to recreate the context and adopt the state of the old context to a new one?

If i understand your question correctly, you simply need to add them to your 'globals' object. You can get the global object later (without a direct reference) with Context::GetCurrent()->Global().


--
----- stephan beal
http://wanderinghorse.net/home/stephan/

danijar

unread,
Apr 1, 2013, 10:26:13 AM4/1/13
to v8-u...@googlegroups.com
On Monday, April 1, 2013 3:49:41 PM UTC+2, Stephan Beal wrote:
If i understand your question correctly, you simply need to add them to your 'globals' object. You can get the global object later (without a direct reference) with Context::GetCurrent()->Global().

That sounds really nice. I tried to use the global object to add a function template.

v8::Local<v8::Object> global = context->Global();
global->Set(v8::String::New("print"), v8::FunctionTemplate::New(Print));

The since the Global() function return an v8::Object instead of an v8::TemplateObject its Set() function is different. The code doesn't compile and the compiler error reads the following.

error C2440: '=': cannot convert from 'v8::FunctionTemplate *' to 'v8::Value *volatile'

Could you please give me an advice?

By the way, is it correct that I don't have to store any handles for context or global object as long as I am only using a single context in my application? That would be great. For now I am storing the context handle as a member, as you might see from the example.

danijar

unread,
Apr 1, 2013, 10:35:25 AM4/1/13
to v8-u...@googlegroups.com
Ok, I figured it out. I had to call GetFunction().

v8::Local<v8::Object> global = context->Global();
global->Set(v8::String::New("print"), v8::FunctionTemplate::New(Print)->GetFunction());

It's working now. Thanks for the help. I am happy that V8 supports adding functions to the global object on the fly. 
Reply all
Reply to author
Forward
0 new messages