Emscripten Class 构造函数采用 std::vector<T>

Emscripten Class Constructor Taking std::vector<T>

我想知道是否有人可以帮助我绑定 Emscripten 中的 C++ class,它采用 std::vector<T> 作为构造函数。我想要以下内容:

EMSCRIPTEN_BINDINGS(my_class) {

    emscripten::class_<test_class>("test_class")
        .constructor<std::vector<float>>()
        .property("x", &test_class::get_x, &test_class::set_x)
        ;
}

我阅读了 this post,并实现了一个代理函数,将 var inputArray = new Float32Array([1,2,3] 创建的我的 JS 浮点数组带到 std::vector<float>

但是,当我使用 inputArray 作为 class 构造函数的参数时,我收到以下警告:

5258048 - Exception catching is disabled, this exception cannot be caught. Compile with -s DISABLE_EXCEPTION_CATCHING=0 or DISABLE_EXCEPTION_CATCHING=2 to catch.

我已将 DISABLE_EXCEPTION_CATCHING=2 标志添加到 emcc 步骤,但是,这不会产生任何不同的输出。

有没有其他人提出解决方案?

关键是要确保您已经使用 register_vector 为 std::vector 定义了一个映射,这样您就可以将复制函数创建的向量传回 JavaScript,然后回到 C++。

如果我正确理解你的问题,这段代码似乎对我有用:

#include <vector>

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

class test_class {
    float x;

public:
    test_class(std::vector<float> arr);
    float get_x() const;
    void set_x(float val);
};

test_class::test_class(std::vector<float> arr) {
    x = 0;
    for (size_t i = 0; i < arr.size(); i++) {
        x += arr[i];
    }
    x = x / arr.size();
}

float test_class::get_x() const {
    return x;
}

void test_class::set_x(float val) {
    x = val;
}

EMSCRIPTEN_BINDINGS(my_class) {

    emscripten::register_vector<float>("VectorFloat");

    emscripten::class_<test_class>("test_class")
        .constructor<std::vector<float>>()
        .property("x", &test_class::get_x, &test_class::set_x)
        ;
}

int main() {
    EM_ASM(
        var arr = new Float32Array([1.0, 2.0, 0.5]);
        var vec = new Module.VectorFloat();
        for (var i = 0; i < arr.length; i++) {
            vec.push_back(arr[i]);
        }
        var obj = new Module.test_class(vec);
        console.log('obj.x is ' + obj.x);
    );
}

此示例代码执行从 Float32Array 到 std::vector(在 JS 中表示为 VectorFloat 代理对象)的低效复制,假设您已经使该部分正常工作,并专注于将向量传递到构造函数。