javascript - 从无法正常工作的 JavaScript 传递指向 WebAssembly 的指针
问题描述
下面给出的是我的 JavaScript 代码。
a = "hello"
a_ascii = [];
for (var i = 0; i < a.length; i ++)
a_ascii.push(a[i].charCodeAt(0));
a_typedArray = new Float32Array(a_ascii.length)
for (let i=0; i<a_ascii.length; i++) {
a_typedArray[i] = a_ascii[i]
}
a_buffer = Module._malloc(a_typedArray.length * a_typedArray.BYTES_PER_ELEMENT)
Module.HEAPF32.set(a_typedArray, a_buffer >> 2)
var result = Module.ccall(
"myFunction", // name of C function
null, // return type
[Number, Number], // argument types
[a_buffer, a.length] // arguments
);
下面给出的是C代码:
extern "C"
{
void EMSCRIPTEN_KEEPALIVE myFunction(int *a, int s)
{
printf("MyFunction Called\n");
for (int i = 0; i < s; i++) {
printf("%d ", a[i]);
}
printf("\n%d\n", s);
}
}
C代码的输出如下:
1120927744 1120534528 1121452032 1121452032 1121845248
5
虽然它应该是:
104 101 108 108 111
5
请让我知道代码有什么问题。
我参考了:链接
解决方案
您在 C中使用Float32Array
JavaScript 。int*
您应该执行以下任一操作:
- 在您的 JavaScript 代码中更改
Float32Array
为Int32Array
- 在 C 代码中更改
int*
tofloat*
和"%d "
to"%.0f "
推荐阅读
- java - Javafx Spring Boot - 运行应用程序时出错
- ruby-on-rails - 如何防止rails mailer在每次发送电子邮件时打开新的gmail登录会话
- javascript - 项目中不存在目标“/t:native_metrics”
- wolkenkit - 聚合上的 read() 函数的 API 是什么?
- c# - 将下拉 DataFieldCategory 移动到列表底部
- angular-material - Angular Material - 输入字段 - 显示重复字段
- php - 为什么我的 fread 不工作?
- javascript - 如何通过 2 层深的对象进行映射
- python - pytz 时区转换中显示的额外分钟数
- reactjs - 为什么将 React 组件包装在样式化组件中是个坏主意