Emscripten教程很好地解释了如何与C函数进行交互:https://github.com/kripken/emscripten/wiki/Interacting-with-code
但是你如何与C ++类交互:
答案 0 :(得分:13)
请检查:http://kripken.github.io/emscripten-site/docs/porting/connecting_cpp_and_javascript/embind.html
示例:
C ++代码:
#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)
;
}
JS代码:
var instance = new Module.MyClass(10, "hello");
instance.incrementX();
instance.x; // 12
instance.x = 20; // 20
Module.MyClass.getStringFromInstance(instance); // "hello"
instance.delete();
答案 1 :(得分:6)
我这样做的方法是创建执行必要操作的“代理”功能。例如:
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来试用代码。