将 JS 数字数组传递给 emscripten C++而不reinterpret_cast
Passing JS number array to emscripten C++ without reinterpret_cast
我在 JS 中有大量数组,我想传递给C++进行处理。恕我直言,最有效的方法是让 JS 直接写入C++堆,并在直接调用中将指针作为参数传递,例如:
var size = 4096,
BPE = Float64Array.BYTES_PER_ELEMENT,
buf = Module._malloc(size * BPE),
numbers = Module.HEAPF64.subarray(buf / BPE, buf / BPE + size),
i;
// Populate the array and process the numbers:
parseResult(result, numbers);
Module.myFunc(buf, size);
用于处理数字的C++函数如下所示:
void origFunc(double *buf, unsigned int size) {
// process the data ...
}
void myFunc(uintptr_t bufAddr, unsigned int size) {
origFunc(reinterpret_cast<double*>(bufAddr), size);
}
这按预期工作,但我想知道是否有机会直接从 Javascript 调用origFunc
以摆脱myFunc
和丑陋 的reinterpret_cast
。
当我尝试通过以下方式绑定 origFunc 时:
EMSCRIPTEN_BINDINGS(test) {
function("origFunc", &origFunc, emscripten::allow_raw_pointers());
}
。并直接调用它:
Module.origFunc(buf, size);
我收到错误:
未捕获的未绑定类型错误:由于未绑定类型,无法调用 origFunc:Pd
这是对 emscripten 的一般限制,还是有比reinterpret_cast
解决方法"不那么脏"的解决方案?
您可以使用
static_cast
,如果您
指定函数采用
void *
而不是uintptr_t
;不要使用
EMSCRIPTEN_BINDINGS
,而是使用EMSCRIPTEN_KEEPALIVE
+cwrap
/ccall
方式来传达JS->C++。出于某种原因,当我尝试它时,EMSCRIPTEN_BINDINGS
方式导致了getTypeName is not defined
异常。
所以函数看起来像:
extern "C" int EMSCRIPTEN_KEEPALIVE myFunc(void *bufAddr, unsigned int size) {
origFunc(static_cast<double *>(bufAddr), size);
return 0;
}
可以从Javascript调用
Module.ccall('myFunc', 'number' ['number', 'number'], [buf, size]);
相关文章:
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 有充分的理由在h文件中使用include保护而不是cpp文件吗
- 为什么使用SFINAE而不是函数重载
- 为什么这个函数将"const char*"转换为"void* const"而不是"const void*"
- 如何将这个C++哈希表转换为动态扩展和收缩,而不是使用硬设置的最大值
- 为什么使用__LINE_的代码在发布模式下在MSVC下编译,而不是在调试模式下
- MSVC是否支持C++11样式的属性而不是__declspec
- CoInitialize()在单独的线程上崩溃而不返回
- 为什么文件名被设置为一个点,而不是在读取矢量中的文件名时
- 是否有类似std::lower_bound的函数,而不需要排序/分区输入
- GlobalAlloc而不是其他分配方法
- 当比特(而不是字节)的顺序至关重要时的持久性
- 为什么复制而不是移动数据元素?
- 为什么lambda在clang上崩溃而不是在gcc上崩溃
- 为什么我应该在异常处理中使用std::cerr而不是std::cout
- () 函子后面的括号,而不是函数指针?
- 为什么是谷神星协方差.计算()似乎永远运行而不返回?
- C++,在int数组中输入字符串或字符会输出0,而不是ascii或error
- 将所有模板类型传递给运算符,而不指定所有类型
- 为什么我们要为avl树实现返回一个指向节点的指针,而不是void函数