我这样做的方式是创建执行必要操作的“代理”函数。例如:
class HelloWorld
{
int x;
public:
HelloWorld() { x = 0; }
~HelloWorld() {}
void setX(int v) { x = v; }
int getX() { return x; }
// ...
};
//compile using "C" linkage to avoid name obfuscation
extern "C" {
//constructor, returns a pointer to the HelloWorld object
void *HW_constructor() {
return new HelloWorld();
}
void HW_setX(HelloWorld *hw, int x) {
hw->setX(x);
}
int HW_getX(HelloWorld *hw) {
return hw->getX();
}
void HW_destructor(HelloWorld *hw) {
delete hw;
}
};
然后在 JS 中,您必须构建一个调用代理函数的对象的克隆(我知道这很烦人,但目前我不知道更好的解决方案):
// get references to the exposed proxy functions
var HW_constructor = Module.cwrap('HW_constructor', 'number', []);
var HW_destructor = Module.cwrap('HW_destructor', null, ['number']);
var HW_setX = Module.cwrap('HW_setX', null, ['number', 'number']);
var HW_getX = Module.cwrap('HW_getX', 'number', ['number']);
function HelloWorld() {
this.ptr = HW_constructor();
}
HelloWorld.prototype.destroy = function () {
HW_destructor(this.ptr);
};
HelloWorld.prototype.setX = function (x) {
HW_setX(this.ptr, x);
};
HelloWorld.prototype.getX = function () {
return HW_getX(this.ptr);
};
重要提示请记住,为了使其正常工作,您需要在 emcc 命令中添加以下标志,告诉它不要将代理方法作为死代码剥离(注意:这里的下划线是故意的并且很重要!):
emcc helloworld.cpp -o helloworld.js \
-s EXPORTED_FUNCTIONS="['_HW_constructor','_HW_destructor','_HW_setX','_HW_getX']"
编辑:我创建了一个gist 供人们试用代码。