Search code examples
javascriptc++emscripten

Update emscripten bindings for member values


Is there a way to update member variables. If they are smart pointers, everything works fine, but if they're not, the values aren't updated. Thank you!

C++

#ifdef EMSCRIPTEN

#include <emscripten/bind.h>
#include <memory>

using namespace emscripten;

struct Point{
    uint32_t x = 0;
};

struct Node{
    Point pos; // This doesn't work.
    // std::shared_ptr<Point> pos; // This works.
    // Node() { pos = std::make_shared<Point>(); }
};

EMSCRIPTEN_BINDINGS(mllow)
{
    class_<Point>("Point")
        .constructor()
        // .smart_ptr<std::shared_ptr<Point>>("Point")
        .property("x", &Point::x);

    class_<Node>("Node")
        .constructor()
        .property("pos", &Node::pos);
}

#endif

JS

node = new Module.Node
node.pos.x = 10
console.log(node.pos.x) // Prints 0 if not a smart pointer.

Solution

  • If you are not exposing them as pointers, when you retrieve them in JS, they are copied instead, so any update would go to the copied instance, not the original one.

    To be able to update the original member instance, either expose them as smart pointers or as raw pointers / references.