如何将C++类编译为.wasm文件以供wasmer使用?

4
我正在尝试将一个C++库(纯代码)编译成.wasm文件,以便在服务器端普遍运行,而不受操作系统的影响。但是,我发现很少有文档可以帮助我处理C++类。具体来说,我想要的所有有用函数都在一个名为Timer的C++类中,例如Timer.reset()。但是,似乎Wasmer只能在其文档中使用导出函数。因此,是否可以在Wasmer中使用导出的C++类,例如instance.exports.Timer.reset()?主要的困惑也在于如何在.wasm文件中包装这个Timer类。我查看了emscripten文档,显示如this,但该文档将它们编译为.js文件,而不是.wasm文件。综上所述,我发现很难获得使用C++类在其他编程语言中使用Wasmer的清晰流程。我希望我已经为愿意给一些提示的任何人提供了清晰的问题说明。最好的祝福。
2个回答

2
请查看以下拉取请求:启用访问类字段而不进行复制
使用它,您可以使用以下示例(来自PR)将C++类公开为属性:
class Foo {
public:
  int i;
};

class MyClass {
public:
  int x;
  Foo foo;
  int getY() const { return y; }
  void setY(int y_) { y = y_; }
private:
  int y;
};

EMSCRIPTEN_BINDINGS(test) {
  class_<MyClass>("MyClass")
    .constructor()
    .property("x", &MyClass::x) // Expose a field directly.
    .property("y", &MyClass::getY, &MyClass::setY) // Expose through a getter and setter.
    .property("readOnlyY", &MyClass::getY) // Expose a read only property.
    .property("foo", &MyClass::foo); // Expose a class field.
  class_<Foo>("Foo")
    .constructor()
    .property("i", &Foo::i);
}

然后在Javascript中,您可以使用以下代码来使用它们:
var myClass = new Module.MyClass();
myClass.x = 10;
myClass.x; // 10
myClass.y = 20;
myClass.y; // 20
myClass.readOnlyY; // 20
// Assign directly to the inner class.
myClass.foo.i = 30;
myClass.foo.i; // 30
// Or use Foo object to assign to foo.
var foo = new Module.Foo();
foo.i = 40;
// Note: this will copy values from the foo but the objects will remain separate.
myClass.foo = foo;
myClass.foo.i; // 40
myClass.delete();
foo.delete();

2

或者您可以使用“旧方法”,将其包装在C调用中:

#include <emscripten.h>
#include <emscripten/bind.h>

class Foo {
public:
  int i;
};

class MyClass {
public:
  int x;
  Foo foo;
};

typedef void *MyClassHandle, *FooHandle;

MyClassHandle createMyClass() {
    return static_cast<MyClassHandle>(new MyClass());
}

void destroyMyClass(MyClassHandle handle) {
    delete static_cast<MyClass *>(handle);
}

FooHandle getFoo(MyClassHandle handle) {
    MyClass *This = static_cast<MyClass *>(handle);
    return static_cast<FooHandle>(&This->foo);
}

int getFooInt(FooHandle foo) {
    return static_cast<Foo *>(foo)->i;
}

EMSCRIPTEN_BINDINGS(test) {
    function("createMyClass", &createMyClass, emscripten::allow_raw_pointers());
    function("destroyMyClass", &destroyMyClass, emscripten::allow_raw_pointers());
    function("getFoo", &getFoo, emscripten::allow_raw_pointers());
    function("getFooInt", &getFooInt, emscripten::allow_raw_pointers());
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接