与Emscripten中的C ++类进行交互 [英] Interaction with C++ classes in Emscripten

查看:52
本文介绍了与Emscripten中的C ++类进行交互的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Emscripten教程很好地解释了如何与C函数交互: https://github.com/kripken/emscripten/wiki/Interacting-with-code

The Emscripten tutorial give a good explanation of how to interact with C functions: https://github.com/kripken/emscripten/wiki/Interacting-with-code

但是如何与C ++类交互:

But how do you interact with C++ classes:

  • 调用构造函数创建对象
  • 删除obj
  • 防止类及其方法的死代码消除

推荐答案

检查此内容: 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();

这篇关于与Emscripten中的C ++类进行交互的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆