[英]Emscripten Class Constructor Taking std::vector<T>
I was wondering if anyone could help me with binding for a C++ class, which takes an std::vector<T>
as a constructor, in Emscripten. 我想知道是否有人可以帮助我绑定Emscripten中的
std::vector<T>
作为构造函数的C ++类。 I would like something along the lines of the following: 我想要以下几种方法:
EMSCRIPTEN_BINDINGS(my_class) {
emscripten::class_<test_class>("test_class")
.constructor<std::vector<float>>()
.property("x", &test_class::get_x, &test_class::set_x)
;
}
I read up on this post , and implemented a proxy function to take my JS float array created by var inputArray = new Float32Array([1,2,3]
, to an std::vector<float>
. 我阅读了这篇文章 ,并实现了一个代理功能,将由
var inputArray = new Float32Array([1,2,3]
创建的JS float数组带到std::vector<float>
。
However, when I use the inputArray
as a parameter to the class constructor I get the following warning: 但是,当我将
inputArray
用作类构造函数的参数时,会收到以下警告:
5258048 - Exception catching is disabled, this exception cannot be caught. Compile with -s DISABLE_EXCEPTION_CATCHING=0 or DISABLE_EXCEPTION_CATCHING=2 to catch.
I have added the DISABLE_EXCEPTION_CATCHING=2
flag to the emcc
step, however, this doesn't produce any different output. 我已将
DISABLE_EXCEPTION_CATCHING=2
标志添加到emcc
步骤,但是,这不会产生任何不同的输出。
Has anyone else come up with a solution? 还有其他人想出解决方案吗?
The key thing is to ensure that you've defined a mapping for std::vector using register_vector so you can pass the vector your copy function has created back to JavaScript and then back into C++. 关键是要确保使用register_vector为std :: vector定义了映射,以便可以将复制函数创建的向量传递回JavaScript,然后再传递回C ++。
This code seems to work for me, if I understand your problem correctly: 如果我正确理解了您的问题,此代码似乎对我有用:
#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);
);
}
This sample code does an inefficient copy from the Float32Array to the std::vector (represented as the VectorFloat proxy object in JS), assuming you've got that part working, and concentrates on passing the vector into the constructor. 假设您已使该部分正常工作,此示例代码会从Float32Array到std :: vector(在JS中表示为VectorFloat代理对象)进行无效复制,并将精力集中于将向量传递给构造函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.