![](/img/trans.png)
[英]Calling a C style function pointer in a WebAssembly from JavaScript
[英]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的output代碼如下:
1120927744 1120534528 1121452032 1121452032 1121845248
5
雖然它應該是:
104 101 108 108 111
5
請讓我知道代碼有什么問題。
我參考了: 鏈接
您在 JavaScript 中使用Float32Array
,而在 C 中使用int*
。
您應該執行以下任一操作:
Int32Array
更改為Float32Array
int*
更改為float*
並將"%d "
更改為"%.0f "
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.