綁定C++函數和類至V8 JavaScript引擎:v8pp

jopen 9年前發布 | 32K 次閱讀 v8pp JavaScript開發

綁定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)
  • </ul>

    綁定示例

    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();

    項目主頁:http://www.baiduhome.net/lib/view/home/1425217334444

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!