rttr icon indicating copy to clipboard operation
rttr copied to clipboard

RTTR on the web - binding C++ for JavaScript

Open dand-oss opened this issue 6 years ago • 1 comments

Binding C++ and JavaScript — WebIDL Binder and Embind https://emscripten.org/docs/porting/connecting_cpp_and_javascript/Interacting-with-code.html#binding-c-and-javascript-webidl-binder-and-embind

// quick_example.cpp
#include <emscripten/bind.h>

using namespace emscripten;

float lerp(float a, float b, float t) {
    return (1 - t) * a + t * b;
}

EMSCRIPTEN_BINDINGS(my_module) {
    function("lerp", &lerp);
}

also

class MyClass {
public:
  MyClass(int x, std::string y)
    : x(x)
    , y(y)
  {}

  void incrementX() {
    ++x;
  }

  int getX() const { return x; }
  void setX(int x_) { x = x_; }

  static std::string getStringFromInstance(const MyClass& instance) {
    return instance.y;
  }

private:
  int x;
  std::string y;
};

// Binding code
EMSCRIPTEN_BINDINGS(my_class_example) {
  class_<MyClass>("MyClass")
    .constructor<int, std::string>()
    .function("incrementX", &MyClass::incrementX)
    .property("x", &MyClass::getX, &MyClass::setX)
    .class_function("getStringFromInstance", &MyClass::getStringFromInstance)
    ;
}

Compiling C++ to WASM via Emscripten is getting real.

Autodesk ported 15 million lines to a web app https://www.infoq.com/presentations/autocad-webassembly, and cpython/scipy/numpy/scikit have been compiled to the browser https://www.erp5.com/NXD-Blog.Scipy.and.Scikit.Learn.Compiled.To.WebAssembly.In.Pyodide

Emscripten bindings look just like RTTR bindings as above. Every C++ instance in the browser needs a RTTR style wrapper.

How can RTTR enable reflected codebases to run in the web browser without making IDL or duplicating registration?

dand-oss avatar Apr 11 '19 07:04 dand-oss

With the new visitor, this might be possible. Because you will get access to the raw function pointers and property members. But I have not looked into emscripten to much how modular this registration is. Try out the new visitor class. https://www.rttr.org/doc/master/classrttr_1_1visitor.html#details There is also an example in the unit tests using chai script: https://github.com/rttrorg/rttr/tree/master/src/examples/scripting Give it a try.

acki-m avatar May 21 '19 20:05 acki-m