绑定C++函数和类至V8 JavaScript引擎:v8pp
jopen
10年前
绑定C++函数和类至V8 JavaScript引擎:v8pp。这个已经在下环境测度过:
- Microsoft Visual C++ 2013 (Windows 7/8)
- GCC 4.8.1 (Ubuntu 13.10 with Linux kernel 3.11.0)
- Clang 3.5 (Mac OS X 10.2)
绑定示例
v8pp supports V8 versions after 3.21 withv8::Isolateusage in API. There are 2 targets for binding:
- v8pp::module, a wrapper class aroundv8::ObjectTemplate
- v8pp::class_, a template class wrapper aroundv8::FunctionTemplate
Both of them require a pointer tov8::Isolateinstance. They allows to bind from C++ code such items as variables, functions, constants with a functionset(name, item):
v8::Isolate* isolate; int var; int get_var() { return var + 1; } void set_var(int x) { var = x + 1; } struct X { X(int v, bool u) : var(v) {} int var; int get() const { return var; } voi set(int x) { var = x; } }; // bind free variables and functions v8pp::module mylib(isolate); mylib // set read-only attribute .set_const("PI", 3.1415) // set variable available in JavaScript with name `var` .set("var", var) // set function get_var as `fun` .set("fun", &get_var) // set property `prop` with getter get_var() and setter set_var() .set("prop", property(get_var, set_var)) // bind class v8pp::class_<X> X_class(isolate); X_class // specify X constructor signature .ctor<int, bool>() // bind variable .set("var", &X::var) // bind function .set("fun", &X::set) // bind read-only property .set("prop", property(&X::get)) // set class into the module template mylib.set("X", X_class); // set bindings in global object as `mylib` isolate->GetCurrentContext()->Global()->Set( v8::String::NewFromUtf8(isolate, "mylib"), mylib.new_instance());
经上述绑定之后,就可以在JavaScript中使用:
mylib.var = mylib.PI + mylib.fun(); var x = new mylib.X(1, true); mylib.prop = x.prop +x.fun();