|
#include <v8.h> |
|
|
|
using namespace v8; |
|
|
|
// This is the variable we are going to share |
|
int x = 15; |
|
|
|
// Gets called when the value of x is requested |
|
Handle<Value> XGetter(Local<String> property, |
|
const AccessorInfo& info) { |
|
// Create a new Javascript int from the |
|
// current value of "x" |
|
return Integer::New(x); |
|
} |
|
|
|
// Gets called when "x" is set to a new value |
|
void XSetter(Local<String> property, Local<Value> value, |
|
const AccessorInfo& info) { |
|
// Change the value of the "x" in the C++ |
|
// to a 32-Bit representation of the value passed |
|
x = value->Int32Value(); |
|
} |
|
|
|
void CompileAndPrint(const Handle<String> source) { |
|
// Compile the source code. |
|
Handle<Script> script = Script::Compile(source); |
|
|
|
// Run the script to get the result. |
|
Handle<Value> result = script->Run(); |
|
|
|
// Convert the result to an ASCII string and print it. |
|
String::AsciiValue ascii(result); |
|
printf("%s\n", *ascii); |
|
} |
|
|
|
int main(int argc, char* argv[]) { |
|
|
|
// Create a stack-allocated handle scope. |
|
HandleScope handle_scope; |
|
|
|
// Create a new ObjectTemplate |
|
Handle<ObjectTemplate> global_templ = ObjectTemplate::New(); |
|
|
|
// Set the XGetter and XSetter function |
|
// to be called when the value of "x" is requested |
|
// or "x" is set to a different value. |
|
global_templ->SetAccessor(String::New("x"), XGetter, XSetter); |
|
|
|
// Create a new context. |
|
Persistent<Context> context = Context::New(NULL, global_templ); |
|
|
|
// Enter the created context for compiling and |
|
// running the hello world script. |
|
context->Enter(); |
|
|
|
// x is still equal to 15 here |
|
Handle<String> s1 = String::New("x;"); |
|
CompileAndPrint(s1); |
|
|
|
// Here we change x to 250 |
|
Handle<String> s2 = String::New("x = 250;"); |
|
CompileAndPrint(s2); |
|
|
|
// We print out x in C++ to see if the value has changed |
|
printf("%d\n", x); |
|
|
|
// Dispose the persistent context. |
|
context.Dispose(); |
|
return 0; |
|
} |