Wednesday, June 22, 2011

a short code example of an embedded V8 Engine

ExecuteScript() and all the other methods are found at, from the v8 examples;

the following code will:

- update a map from the c++ code
- update a map from the javascript code
- execute a c++ function within the javascript code
- execute a javascript function within a c++ code

int main()
string file("c:/temp/test.js");

map<string, string> config;
config["adrian"] = "1234";

HandleScope scope;
Handle<ObjectTemplate> global = ObjectTemplate::New();
global->Set(String::New("log"), FunctionTemplate::New(LogCallback));
global->Set(String::New("callback"), ObjectTemplate::New());

Handle<Context> context = Context::New(NULL, global);
Context::Scope context_scope(context);

context->Global()->Set(String::New("config"), WrapMap(&config));

Handle<String> script = ReadFile(file);

if (!ExecuteScript(script)) {
fprintf(stderr, "Error executing script.\n");
return 1;


Local<Value> callback = context->Global()->Get(String::New("callback"));

if (callback->IsObject())
Local<Value> extfn1 = callback->ToObject()->Get(String::New("extfn1"));
if (extfn1->IsFunction())
Handle<Function> fn = Handle<Function>::Cast(extfn1);

for (int i=0; i<3; ++i) {
fn->Call(fn, 0, NULL);

return 0;