Hi there,
I need some help getting one of the basic doc examples to work:
https://emscripten.org/docs/porting/connecting_cpp_and_javascript/embind.html#classes
In other words, compile a basic example for Embind that instantiates a
C++ class from JavaScript and makes some calls on the instance methods.
This is the class with added imports as shown in the docs:
```cpp
// file: classes.cpp
#include <string>
#include <emscripten.h>
#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;
};
// 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)
;
}
```
And here is a JS snippet I will add as post-js:
```javascript
// file: classes_post.js
var instance = new Module.MyClass(10, "hello");
instance.incrementX();
instance.x; // 11
instance.x = 20; // 20
Module.MyClass.getStringFromInstance(instance); // "hello"
instance.delete();
```
My attempt to build:
em++ -O1 --bind -o classes.html --post-js classes_post.cpp classes.cpp
I serve the page with python simple-http-server, and when I open it, I
just get
But when I open the generated HTML, I only get:
```
classes.js:3553 Uncaught TypeError: Module.MyClass is not a constructor
at classes.js:3553
```
So I must be missing a crucial bit?
The problem is extra complicated for me because I'm not a C++
programmer, nor very good at JavaScript, so excuse me if I'm missing
something fundamental; I'm trying to port a C++ application to
WebAssembly, and this will be an important thing for me to solve.
The next step will be for me that I need to call instance methods from
JavaScript on an instance created from within C++ itself. How would I
pass an instance to JavaScript?
My naive attempt:
```cpp
int main() {
auto c = MyClass(10, "hello"); // I want to use _this_ instance
EM_ASM({
var instance = $0; // apparently that doesn't work
instance.incrementX(); // instance.incrementX is not a function
console.log('The value of x is now: ' + instance.x);
}, &c);
return 0;
}
```
If I log `$0`, that's an integer number, so I presume that is the heap
memory location of `&c`, and I need a way to map that to the binding API
in JavaScript.
Thanks!
Best,
.h.h.