javascript - 如何在后端 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
不是构造函数的错误。有人有什么想法吗?谢谢。
解决方案
与网页版一样,您应该导入您的模块:
var Module = require('./path/to/class_cpp.js');
然后确保运行时已初始化:
Module.onRuntimeInitialized = async function {
// My code...
}
推荐阅读
- r - 用户上传文件时的R ggplot
- php - Laravel 每个用户只有一个friend_id
- c# - 如何以自定义格式 dd/MM/yyyy 在 SQL Server 数据库中插入 Datetimepicker 值
- angular - 角度反应形式设置值不起作用
- python - 错误:(wheel).whl 不是此平台上支持的轮子
- typescript - 如何在 NgRx createAction props<>() 中使用泛型类型
- mysql - 在 Laravel 中使用 whereDate 从连接表查询
- c++ - C++ 数组到 HDF5
- android - 无法从 Android 清单锁定屏幕旋转
- ios - 如何从 Swift 框架回调到 Flutter 项目?