Interaction with C++ classes in Emscripten

Mortennobel picture Mortennobel · Apr 7, 2013 · Viewed 7.2k times · Source

The Emscripten tutorial give a good explanation of how to interact with C functions: https://github.com/kripken/emscripten/wiki/Interacting-with-code

But how do you interact with C++ classes:

  • Call a constructor to create an object
  • Delete an obj
  • Prevent dead code elimination of classes and its methods

Answer

Zardoz89 picture Zardoz89 · Dec 14, 2013

Check this : http://kripken.github.io/emscripten-site/docs/porting/connecting_cpp_and_javascript/embind.html

Example :

C++ code :

#include <emscripten/bind.h>

using namespace emscripten;

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;
};

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

JS code :

var instance = new Module.MyClass(10, "hello");
instance.incrementX();
instance.x; // 12
instance.x = 20; // 20
Module.MyClass.getStringFromInstance(instance); // "hello"
instance.delete();