简体   繁体   中英

How can I use emscripten-generated cpp class in backend js code?

I am learning emscripten from official document, and I need to implement a js-called cpp function inner a class, that is referenced from this page: https://emscripten.org/docs/porting/connecting_cpp_and_javascript/embind.html I created a cpp class like this:

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

And compile by: emcc --bind -o class_cpp.js class.cpp I can create the class instance and run its function by following way:

<!doctype html>
<html>
  <script>
    var Module = {
      onRuntimeInitialized: function() {
        var instance = new Module.MyClass(10, "hello");
        instance.incrementX();
        console.log(instance.x); // 12
        instance.x = 20;
        console.log(instance.x); // 20
        console.log(Module.MyClass.getStringFromInstance(instance)); // "hello"
        instance.delete();
      }
    };
  </script>
  <script src="class_cpp.js"></script>
</html>

But how to call it in a nodejs backend program? I tried to create the instance but it reported error that MyClass is not a constructor. Anyone has any idea? thanks.

As in the web version you should import your Module:

var Module = require('./path/to/class_cpp.js');

And then make sure that the runtime is initialized:

Module.onRuntimeInitialized = async function {
     // My code...
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM