Hi there,

I solve the first problem, and found a work-around the second

On 28/12/2020 01:06, Hanns Holger Rutz wrote:
[...]
> And here is a JS snippet I will add as post-js:

It seems that `--post-js` not necessarily runs after the module is
initialized. So that code must be wrapped in `addOnPostRun`, like so:

```javascript
addOnPostRun(function() {
  console.log("here: 1");
  var instance = new Module.MyClass(10, "hello");
  instance.incrementX();
  var x1 = instance.x; // 11
  console.log("x is now: " + x1);
  instance.x = 20; // 20
  var s = Module.MyClass.getStringFromInstance(instance); // "hello"
  console.log("string is now: " + s);
  instance.delete();
  console.log("here: 2");
});
```

(see https://github.com/emscripten-core/emscripten/issues/13116)

[...]
> 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?

I haven't solved passing an actual instance, but in my case I will only
ever have _one_ instance of the class. In this case, one can use a
singleton-pattern as described here:

https://groups.google.com/g/emscripten-discuss/c/MimQol7peuQ

Ex:

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

class MyClass {
public:
  MyClass() {}

  void doSomething() {
    printf("Doing something\n");
  }
};

static MyClass* singleton_val;

MyClass* singleton() {
  if (singleton_val == NULL) {
    singleton_val = new MyClass;
  }
  return singleton_val;
}

EMSCRIPTEN_BINDINGS(my_module) {
  emscripten::class_<MyClass>("MyClass")
    .function("doSomething", &MyClass::doSomething);
  function("singleton", &singleton, emscripten::allow_raw_pointers());
}

int main() {
  EM_ASM({
    Module.singleton().doSomething();
  });
  return 0;
}
```


Best, .h.h.

-- 
You received this message because you are subscribed to the Google Groups 
"emscripten-discuss" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/emscripten-discuss/ad317cca-32b5-8bce-4bb8-a71f9b315145%40sciss.de.

Attachment: OpenPGP_signature
Description: OpenPGP digital signature

Reply via email to