[英]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: 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 像这样:
#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:并编译:
emcc --bind -o class_cpp.js class.cpp
我可以创建 class 实例并运行它的 function 通过以下方式:
<!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?但是如何在 nodejs 后端程序中调用它呢? I tried to create the instance but it reported error that
MyClass
is not a constructor.我试图创建实例,但它报告了
MyClass
不是构造函数的错误。 Anyone has any idea?有人有什么想法吗? thanks.
谢谢。
As in the web version you should import your Module:在 web 版本中,您应该导入您的模块:
var Module = require('./path/to/class_cpp.js');
And then make sure that the runtime is initialized:然后确保运行时已初始化:
Module.onRuntimeInitialized = async function {
// My code...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.