从 JavaScript 传递指向 WebAssembly 的指针无法正常工作
Passing a pointer to WebAssembly from JavaScript which is not working correctly
下面给出的是我的 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
请让我知道代码有什么问题。
我参考了:link
您在 JavaScript 中使用 Float32Array
,而在 C 中使用 int*
。
您应该执行以下任一操作:
- 在您的 JavaScript 代码中将
Float32Array
更改为 Int32Array
- 在您的 C 代码中将
int*
更改为 float*
,将 "%d "
更改为 "%.0f "
下面给出的是我的 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
请让我知道代码有什么问题。
我参考了:link
您在 JavaScript 中使用 Float32Array
,而在 C 中使用 int*
。
您应该执行以下任一操作:
- 在您的 JavaScript 代码中将
Float32Array
更改为Int32Array
- 在您的 C 代码中将
int*
更改为float*
,将"%d "
更改为"%.0f "