
Introduction
Who never wondered how virtual machines work? But, better than creating your own virtual machine, what if you can use one done by a big company focusing on improving the speed to the VM? In this article, I'll introduce how to use the V8 in your application, which is Google's open source JavaScript engine inside Chrome - Google’s new browser.
Background
This code uses the V8 as an embedded library to execute JavaScript code. To get the source of the library and more information, go to the V8 developer page. To effectively use the V8 library, you need to know C/C++ and JavaScript.
Using the Code
Let's see what is inside the demo. The demo shows:
- How to use the V8 library API to execute JavaScript source code.
- How to access an integer and a string inside the script.
- How to create your own function which can be called inside the script.
- How to create your own C++ class which can be called inside the script.
First, let's understand how to initialize the API. Look at this simple example of embedded V8 on C++:
#include <v8.h>
using namespace v8;
int main(int argc, char* argv[]) {
HandleScope handle_scope;
Handle<Context> context = Context::New();
Context::Scope context_scope(context);
Handle<String> source = String::New("'Hello' + ', World!'");
Handle<Script> script = Script::Compile(source);
Handle<Value> result = script->Run();
String::AsciiValue ascii(result);
printf("%s\n", *ascii);
return 0;
}
Well, but this doesn't explain how we can control variables and functions inside the script. OK, the script does something... but, we need to get this information somehow, and have customized functions to control specific behavior inside the script.
The Global Template
First, we need a global template to control our modifications:
v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New();
This creates a new global template which manages our context and our customizations. This is important because in V8, each context is separated, and can have its own global template. In V8, a context is an execution environment that allows separate, unrelated, JavaScript applications to run in a single instance of V8.
Adding Customized Functions
After that, we can add a new function named "plus":
v8::Handle<v8::Value> Plus(const v8::Arguments& args)
{
unsigned int A = args[0]->Uint32Value();
unsigned int B = args[1]->Uint32Value();
return v8_uint32(A + B);
}
global->Set(v8::String::New("plus"), v8::FunctionTemplate::New(Plus));
Customized functions need to receive const v8::Arguments& as a parameter and must return v8::Handle<v8::Value>. Using the global template pointer created before, we add the function to the template, and associates the name "plus" to the callback "Plus". Now, each time we use the "plus" function on our script, the function "Plus" will be called. The Plus function does just one thing: get the first and the second parameters and return the sum.
OK, now we can use a customized function in the JavaScript side:
plus(120,44);
and we can use this function's result inside the script:
x = plus(1,2);
if( x == 3){
}
Accessors - Variables Accessible Inside the Script!
Now, we can create functions... but wouldn't it be cooler if we can use something defined outside inside the script? Let's do it! The V8 have a thing called Accessor, and with it, we can associate a variable with a name and two Get / Set functions, which will be used by the V8 to access the variable when running the script.
global->SetAccessor(v8::String::New("x"), XGetter, XSetter);
This associates the name "x" with the "XGetter" and "XSetter" functions. The "XGetter" will be called by V8 each time the script needs the value of the "x" variable, and the "XSetter" will be called each time the script must update the value of "x". And now, the functions:
int x;
static v8::Handle<v8::Value> XGetter( v8::Local<v8::String> name,
const v8::AccessorInfo& info) {
return v8::Number::New(x);
}
static void XSetter( v8::Local<v8::String> name,
v8::Local<v8::Value> value, const v8::AccessorInfo& info) {
x = value->Int32Value();
}
In the XGetter, we only need to convert "x" to a number type value managed by V8. In the XSetter, we need to convert the value passed as parameter to an integer value. There is one function to each basic type (NumberValue for double, BooleanValue for bool, etc.)
Now, we can do the same again for string (char*):
char username[1024];
v8::Handle<v8::Value> userGetter(v8::Local<v8::String> name,
const v8::AccessorInfo& info) {
return v8::String::New((char*)&username,strlen((char*)&username));
}
void userSetter(v8::Local<v8::String> name, v8::Local<v8::Value> value,
const v8::AccessorInfo& info) {
v8::Local<v8::String> s = value->ToString();
s->WriteAscii((char*)&username);
}
For the string, things changed a little. The "userGetter" creates a new V8 string in the same way the XGetter does, but the userSetter needs first to access the internal string buffer by using the ToString function. Then, using the pointer to the internal string object, we use the WriteAscii function to write its content to our buffer. Now, just add the accessor, and voila!
global->SetAccessor(v8::String::New("user"),userGetter,userSetter);
Printing
The "print" function is another customized function which catches all parameters and prints them using the "printf" function. As we have done before with the "plus" function, we register our new function on the global template:
global->Set(v8::String::New("print"), v8::FunctionTemplate::New(Print));
"print" implementation
v8::Handle<v8::Value> Print(const v8::Arguments& args) {
bool first = true;
for (int i = 0; i < args.Length(); i++)
{
v8::HandleScope handle_scope;
if (first)
{
first = false;
}
else
{
printf(" ");
}
v8::String::AsciiValue str(args[i]);
printf("%s", *str);
}
printf("\n");
return v8::Undefined();
}
For each parameter, the v8::String::AsciiValue object is constructed to create a char* representation of the passed value. With it, we can convert other types to their string representation and print them!
Sample JavaScript
Inside the demo program, we have this sample JavaScript to use what we have created so far:
print("begin script");
print(script executed by + user);
if ( user == "John Doe"){
print("\tuser name is invalid. Changing name to Chuck Norris");
user = "Chuck Norris";
}
print("123 plus 27 = " + plus(123,27));
x = plus(3456789,6543211);
print("end script");
This script uses the "x" variable, the "user" variable, and the "plus" and "print" functions.
Accessors with C++ Objects!

Preparing the Environment for our Class
Now, how to map a class to the JavaScript using C++? First, the sample class:
class Point
{
public:
Point(int x, int y):x_(x),y_(y){}
void Function_A(){++x_; }
void Function_B(int vlr){x_+=vlr;}
int x_;
};
For this class to be fully on JavaScript, we need to map both the functions and internal variable. The first step is to map a class template on our context:
Handle<FunctionTemplate> point_templ = FunctionTemplate::New();
point_templ->SetClassName(String::New("Point"));
We create a "function" template, but this can be seen as a class. This template will have the "Point" name for later usage (like create new instances of it inside the test script).
Then. we access the prototype class template to add built-in methods for our class:
Handle<ObjectTemplate> point_proto = point_templ->PrototypeTemplate();
point_proto->Set("method_a", FunctionTemplate::New(PointMethod_A));
point_proto->Set("method_b", FunctionTemplate::New(PointMethod_B));
After this, the class "knows" that it has two methods and callbacks. But, this is still in the prototype, we can't use it without accessing an instance of the class.
Handle<ObjectTemplate> point_inst = point_templ->InstanceTemplate();
point_inst->SetInternalFieldCount(1);
The SetInternalFieldCount function creates space for the C++ class pointer (will see this later).
Now, we have the class instance and can add accessors for the internal variable:
point_inst->SetAccessor(String::New("x"), GetPointX, SetPointX);
Then, we have the "ground" prepared... throw the seed:
Point* p = new Point(0, 0);
The new class is created, but can only be accessed in C++. To access it, we need:
Handle<Function> point_ctor = point_templ->GetFunction();
Local<Object> obj = point_ctor->NewInstance();
obj->SetInternalField(0, External::New(p));
Well, GetFunction returns the point constructor (on the JavaScript "side"), and with it, we can create a new instance using NewInstance. Then, we set our internal field (which we have created "space" for with SetInternalFieldCount) with the class pointer. With that, the JavaScript will have access to the object through the pointer.
Only one step is missing. We only have a class template and instance, but no name to access it from the JavaScript:
context->Global()->Set(String::New("point"), obj);
This last step links the "point" name to the instance obj. With these steps, we just emulate the creation of class Point with the name point in our script (before loading or running it!).
Accessing a Class Method Inside the JavaScript
OK, but this doesn't explain how we can access Function_A inside the Point class...
Let's look at the PointMethod_A callback:
Handle<Value> PointMethod_A(const Arguments& args)
{
Local<Object> self = args.Holder();
Local<External> wrap = Local<External>::Cast(self->GetInternalField(0));
void* ptr = wrap->Value();
static_cast<Point*>(ptr)->Function_A();
return Integer::New(static_cast<Point*>(ptr)->x_);
}
Like a normal accessor, we must handle the arguments. But, to have access to our class, we must get the class pointer from the internal field (first one). After mapping the internal field to "wrap", we get the class pointer by retrieving its "value". Now, it's a matter of cast...
Now, we have the class pointer for the "point" class being used (which called method_a, which called the callback PointMethod_A).
The sample v8_embedded_demo_with_object.zip implements all these steps.
I hope this helps, and if something is wrong or unclear, please don't hesitate to contact.
Points of Interest
Before trying to use the V8 library, I've tried to use Lua as an embedded scripting language to support easy configuration and changes by the user. I got amazed by V8 as it's faster and easier to use than Lua to implement scripting functionality in my own software. I hope this article help others in this task.
Look also for Google's documentation on the V8 library!
History
- 9/5/2008 - First implementation.
- 9/8/2008 - Lua vs. V8 benchmark and sample using dynamic variables.
- 9/11/2008 - Lua benchmark updated (version 2), and finally, object access inside the JavaScript.
|
|
 |
 | Is it possible to embed google v8 js virtual machine (only) into my application? jjshean | 7:56 6 Feb '10 |
|
 |
I need to embed JS virtual machin into my code, just VM without any compilators. Is it possible to extract it from google v8 source and embed into my application (theoretically)? thanks
|
|
|
|
 |
 | Problems creating a customized function (like the plus example in the article) Phil. Roy | 16:40 31 Aug '09 |
|
 |
I tried to follow the instructions from this article to implement a customized function, but failed (although I did succeed in exposing my C++ objects into javascript, thanks to this article).
Here's my code:
Handle<ObjectTemplate> global;
Handle<Value> JSAlert(const Arguments& args) { Handle<Value> result; String::AsciiValue ascii0(args[0]); MessageBox(NULL, *ascii0, "Javascript message", MB_OK); return result; }
void InitJavascriptGlobal() { if (global.IsEmpty()) { global = v8::ObjectTemplate::New(); global->Set(String::New("alert"), FunctionTemplate::New(JSAlert)); } }
Called once in the main after the creation of the context:
int _tmain(int argc, _TCHAR* argv[]) { HandleScope handle_scope; Persistent<Context> context = Context::New(); Context::Scope context_scope(context); InitJavascriptGlobal(); ... }
Result:
ExecuteString compile : Uncaught ReferenceError: alert is not defined 
Any advice on how to get that fixed would be welcome... 
|
|
|
|
 |
|
 |
Hi, sorry about my delay to answer your question. You need to remove the check: "if (global.IsEmpty())"
This is not good as the object is not really initialized and could have "default" information which prevents your "alert" function to be initialized inside it.
Also take a look in the v8_embedded_demo functions and use it as a "template" to check if you forgot something. I think you're looking for this:
#include "stdafx.h" #include <v8.h> #include <string.h>
v8::Handle<v8::ObjectTemplate> global; v8::HandleScope handle_scope; v8::Handle<v8::Context> context;
Handle<Value> JSAlert(const Arguments& args) { String::AsciiValue ascii0(args[0]); MessageBox(NULL, *ascii0, "Javascript message", MB_OK); return v8::Undefined(); }
// Executes a string within the current v8 context. bool ExecuteString(v8::Handle<v8::String> source,v8::Handle<v8::String> name) { //access global context within this scope v8::Context::Scope context_scope(context); //exception handler v8::TryCatch try_catch; //compile script to binary code - JIT v8::Handle<v8::Script> script = v8::Script::Compile(source, name); bool print_result = true;
//check if we got problems on compilation if (script.IsEmpty()) {
// Print errors that happened during compilation. v8::String::AsciiValue error(try_catch.Exception()); printf("%s\n", *error); return false; } else { //no errors , let's continue v8::Handle<v8::Value> result = script->Run();
//check if execution ended with errors if(result.IsEmpty()) { // Print errors that happened during execution. v8::String::AsciiValue error(try_catch.Exception()); printf("%s\n", *error); return false; } else { if (print_result && !result->IsUndefined()) { // If all went well and the result wasn't undefined then print // the returned value. v8::String::AsciiValue str(result); printf("script result [%s]\n", *str); } return true; } } }
int _tmain(int argc, _TCHAR* argv[]) { char *script = "alert(\"message from my script\");";
char *script_name = "internal_script"; //convert the string with the script to a v8 string v8::Handle<v8::String> source = v8::String::New(script, strlen(script));
//each script name must be unique , for this demo I just run one embedded script, so the name can be fixed v8::Handle<v8::String> name = v8::String::New(script_name,strlen(script_name));
// Create a template for the global object. global = v8::ObjectTemplate::New();
//associates "plus" on script to the Plus function global->Set(v8::String::New("alert"), v8::FunctionTemplate::New(JSAlert));
//create context for the script context = v8::Context::New(NULL, global);
//simple javascritp to test ExecuteString(source,name);
return 0; }
best regards, Gabriel
Gabrielwf
|
|
|
|
 |
 | Good article Gavriloaie Andrei | 2:11 10 Jun '09 |
|
 |
Excellent article. I have some questions though...
You exemplified creating a point instance and expose it to the JS. Can you give us an example where we instantiate the Point from JS?
I mean, being able to execute the following script:
var p=new Point(); p.x=100; p.y=101;
Thanks
RFC1925
With sufficient thrust, pigs fly just fine. However, this is not necessarily a good idea. It is hard to be sure where they are going to land, and it could be dangerous sitting under them as they fly overhead.
|
|
|
|
 |
|
|
 |
|
 |
I figure it out in the end. And is working excellent. There is only one catch.... How do I detect that the point object is garbage collected? I need to do it because I need to free the C++ point pointer
#include <stdlib.h> #include <v8.h> using namespace v8;
#define FILE_NAME "/tmp/test.js"
Handle<Value> Print(const Arguments& args); Handle<String> ReadFile(const char* name); const char* ToCString(const String::Utf8Value& value);
Handle<Value> PointConstructor(const Arguments& args); Handle<Value> PointGetX(Local<String> property, const AccessorInfo& info); void PointSetX(Local<String> property, Local<Value> value, const AccessorInfo& info); Handle<Value> PointGetY(Local<String> property, const AccessorInfo& info); void PointSetY(Local<String> property, Local<Value> value, const AccessorInfo& info);
class Point { private: int _x; int _y; public:
Point(int x, int y) { _x = x; _y = y; }
virtual ~Point() {
}
int X() { return _x; }
void X(int x) { _x = x; }
int Y() { return _y; }
void Y(int y) { _y = y; } };
int main(int argc, char** argv) { HandleScope handle_scope;
Handle<ObjectTemplate> global = ObjectTemplate::New();
global->Set(String::New("print"), FunctionTemplate::New(Print));
Handle<FunctionTemplate> point_templ = FunctionTemplate::New(PointConstructor); point_templ->SetClassName(String::New("Point")); Handle<ObjectTemplate> point_proto = point_templ->PrototypeTemplate(); point_proto->SetAccessor(String::New("x"), PointGetX, PointSetX); point_proto->SetAccessor(String::New("y"), PointGetY, PointSetY); Handle<ObjectTemplate> point_inst = point_templ->InstanceTemplate(); point_inst->SetInternalFieldCount(1);
global->Set(String::New("Point"), point_templ);
Handle<Context> context = Context::New(NULL, global);
Context::Scope context_scope(context);
Handle<String> name = String::New(FILE_NAME); Handle<String> source = ReadFile(FILE_NAME);
Handle<Script> script = Script::Compile(source, name);
Handle<Value> result = script->Run();
return (EXIT_SUCCESS); }
Handle<String> ReadFile(const char* name) { FILE* file = fopen(name, "rb"); if (file == NULL) return Handle<String > ();
fseek(file, 0, SEEK_END); int size = ftell(file); rewind(file);
char* chars = new char[size + 1]; chars[size] = '\0'; for (int i = 0; i < size;) { int read = fread(&chars[i], 1, size - i, file); i += read; } fclose(file); Handle<String> result = String::New(chars, size); delete[] chars; return result; }
Handle<Value> Print(const Arguments& args) { bool first = true; for (int i = 0; i < args.Length(); i++) { HandleScope handle_scope; if (first) { first = false; } else { printf(" "); } String::Utf8Value str(args[i]); const char* cstr = ToCString(str); printf("%s", cstr); } printf("\n"); fflush(stdout); return Undefined(); }
const char* ToCString(const String::Utf8Value& value) { return *value ? *value : "<string conversion failed>"; }
Handle<Value> PointConstructor(const Arguments& args) { Local<Object> obj = args.This();
Point* p = new Point(args[0]->ToInteger()->Int32Value(), args[1]->ToInteger()->Int32Value()); obj->SetInternalField(0, External::New(p));
return Undefined(); }
Handle<Value> PointGetX(Local<String> property, const AccessorInfo& info) { Local<Object> self = info.This(); Local<External> wrap = Local<External>::Cast(self->GetInternalField(0)); void* ptr = wrap->Value(); int value = static_cast<Point*> (ptr)->X(); return Integer::New(value); }
void PointSetX(Local<String> property, Local<Value> value, const AccessorInfo& info) { Local<Object> self = info.This(); Local<External> wrap = Local<External>::Cast(self->GetInternalField(0)); void* ptr = wrap->Value(); static_cast<Point*> (ptr)->X(value->Int32Value()); }
Handle<Value> PointGetY(Local<String> property, const AccessorInfo& info) { Local<Object> self = info.This(); Local<External> wrap = Local<External>::Cast(self->GetInternalField(0)); void* ptr = wrap->Value(); int value = static_cast<Point*> (ptr)->Y(); return Integer::New(value); }
void PointSetY(Local<String> property, Local<Value> value, const AccessorInfo& info) { Local<Object> self = info.This(); Local<External> wrap = Local<External>::Cast(self->GetInternalField(0)); void* ptr = wrap->Value(); static_cast<Point*> (ptr)->Y(value->Int32Value()); }
RFC1925
With sufficient thrust, pigs fly just fine. However, this is not necessarily a good idea. It is hard to be sure where they are going to land, and it could be dangerous sitting under them as they fly overhead.
|
|
|
|
 |
|
|
 |
 | Not faster than LuaJIT saptor | 10:23 30 Oct '08 |
|
 |
Don't get me wrong, V8 is awesome. It's really the first fast Javascript VM that is very nicely separated from anything browser related which makes it great for embedding. It even comes with a Visual Studio project for building it and it builds 100% clean on all the platforms.
In most tests however, LuaJIT (with -O) is faster than V8. There are a few benchmarks where V8 wins but generally speaking LuaJIT is still faster, especially when it comes to larger scale general purpose programs (versus micro-sized benchmarks). Consider LuaJIT 2 should be out sometime (soon?) and it's much faster than the current LuaJIT.
Also, size-wise V8 is considerably larger than Lua which might be important when embedding.
Then there is the issue of making extensions to the engine (eg. wrapping native API's, etc). In Lua it's very straightforward and the code looks relatively nice. In V8 it's really awful with the mix of objects, templates, and various other oddities. Especially the String stuff can get very tedious. Makes for some not-so-pretty code. With that said, V8 is better than the other Javascript engines in this regard even though it's not as clean and easy as Lua.
Lua's documentation on the engine internals is better as well. That will hopefully change in time though.
Overall I really like the V8 engine and I have been working a lot with it. It has not replaced Lua for me though.
|
|
|
|
 |
|
 |
Hi, sorry on my delay to answer your email. I didn't know about LuaJIT and it looks like very interesting and could be faster / easier to use than V8. In fact V8 is not multiplatform enough for me and this is the main reason I'm using lua for some testing stuff on my work. I'm not satisfied with the little benchmark I've done in this article and I'm building a more "fair" test based on the alioth-shootout benchmark (lua and javascript) to see V8 against Lua (and now LuaJIT too). I'll also check if I can use the LuaJIT on tru64 and hp-ux machines (if it works then I'll use LuaJIT instead of normal Lua on my work ). thanks!
Gabrielwf
|
|
|
|
 |
|
 |
Why are you even bringing up LauJIT? We're talking about JavaScript here...
|
|
|
|
 |
 | Thank you. Just what I was looking for. dbbtvlzfpz | 15:34 20 Oct '08 |
|
 |
Hi. This is just a quick note to express my thanks. I was searching for some good sample projects using v8, and this is perfect. I thank you for taking the time to make it and then to share it.
|
|
|
|
 |
|
|
 |
 | Sobre C# roberto lapolli | 4:33 3 Oct '08 |
|
 |
Olá Gabriel. Existe alguma forma de usar C# com o V8?
|
|
|
|
 |
|
 |
ola roberto, tem sim, mas é necessário transformar a biblioteca v8 em dll para facilitar o processo. Eu nunca trabalhei com C# mas acho que ligacao com codigo c é algo mais facil em C# que em java.
// usando um metodo static da dll chamado "DoSomething" void __stdcall DoSomething(HWND hWnd)
//usando: public class InteropExample { [DllImport("MyDll.dll")] //v8.dll static private extern void DoSomething(IntPtr hwnd);//mapeando metodo da dll
static public void DoSomething(Control control) { DoSomething(control.Handle);//usando metodo } }
http://www.codeguru.com/forum/showthread.php?t=357680 http://www.codeproject.com/KB/dotnet/Cdecl_CSharp_VB.aspx
Gabrielwf
|
|
|
|
 |
 | Where is the "e? Member 3717457 | 9:06 9 Sep '08 |
|
 |
It does not compile anymore because I can't copy and paste 
|
|
|
|
 |
|
 |
the image for the source code was just a test, I changed back to the normal source-code-block
Gabrielwf
|
|
|
|
 |
 | fix corrupted code barto | 3:17 9 Sep '08 |
|
 |
Hi, this is a nice article. Could you please fix the code in the article. Often there is " instead of " and it seems some other things are missing (check the "source" in the first code)
|
|
|
|
 |
|
 |
Hi, sorry but I've tried to fix this quot; stuff everytime I update the article. It seems that the CodeProject wizard is having trouble with my post. I tried to use internet explorer, firefox and chrome and in all of them the source end with this ugly quot; istead of ". Hope this will be fixed soon 
What is missing in the source? Can you point it? Thanks!
Gabrielwf
|
|
|
|
 |
 | Very Nice! Member 3717457 | 9:57 8 Sep '08 |
|
 |
Just don't forget to mention the Accessors(Dynamic) and Interceptors defined in http://code.google.com/apis/v8/embed.html
|
|
|
|
 |
|
 |
Hi, thanks! I have added a demo of such construct and will explain it's usage soon.
Gabrielwf
|
|
|
|
 |
 | Excellent! Iggy Natich | 7:38 8 Sep '08 |
|
 |
Excellent article, though somewhat lacking. I'd like to see more about objects and at some performance comparison with lua and/or other scripting engines.
|
|
|
|
 |
|
 |
Hi, thanks! I have added a simple benchmark testing lua and v8. the lua script and v8 javascript do the same and you can write your own scripts to check the speed using this demo. I hope this helps  (also I'll post the topic about object - dynamic variable access - but for now here comes an example of using it)
Gabrielwf
|
|
|
|
 |
|
 |
The results are impressive, but currently you do both compilation and execution in your test. Could you separate measurement of compilation time and execution time?
|
|
|
|
 |
|
 |
Hi! you're right! I did put the compile step inside the time measurement... lol. I know that lua do the compilation time at least one time on script execution, but I can't control it from outside (to force only one compilation). I'll put the v8 compilation outside the time measurement but this is adding 1 compilation step for lua (at least). thanks!
Gabrielwf
|
|
|
|
 |
|
 |
You can try using precompiled lua script with luaL_loadfile.
|
|
|
|
 |
|
|