首页 > 解决方案 > 从无法正常工作的 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

请让我知道代码有什么问题。

我参考了:链接

标签: javascriptcmemory-managementwebassemblyemscripten

解决方案


您在 C中使用Float32ArrayJavaScript 。int*

您应该执行以下任一操作:

  • 在您的 JavaScript 代码中更改Float32ArrayInt32Array
  • 在 C 代码中更改int*tofloat*"%d "to"%.0f "

推荐阅读