首页 > 解决方案 > 如何在后端 js 代码中使用 emscripten 生成的 cpp 类?

问题描述

我正在从官方文档中学习 emscripten,我需要在一个类中实现一个名为 cpp 的 js 函数,该函数引用自此页面:https ://emscripten.org/docs/porting/connecting_cpp_and_javascript/embind.html 我创建了一个像这样的cpp类:

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

并编译:emcc --bind -o class_cpp.js class.cpp 我可以通过以下方式创建类实例并运行它的功能:</p>

<!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>

但是如何在 nodejs 后端程序中调用它呢?我试图创建实例,但它报告了 MyClass不是构造函数的错误。有人有什么想法吗?谢谢。

标签: javascriptc++emscripten

解决方案


与网页版一样,您应该导入您的模块:

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

然后确保运行时已初始化:

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

推荐阅读