【问题标题】:WebAssembly return string use CWebAssembly 返回字符串使用 C
【发布时间】:2020-05-14 10:35:37
【问题描述】:

如何从 WebAssembly 函数返回 JavaScript 字符串?

https://dev.to/azure/passing-strings-from-c-to-javascript-in-web-assembly-1p01 - not working

C

#include <stdio.h>
#include <string.h>

void jsPrintString(const char *s, uint16_t len);

void print() {
  const char* str = "Hello from C++!";
  jsPrintString(str, strlen(str));
}

编译器:

emcc -Os start.c  -s STANDALONE_WASM -s EXPORTED_FUNCTIONS="['_hello']" -s ERROR_ON_UNDEFINED_SYMBOLS=0 -Wl,--no-entry -o "test.wasm"

Javascript:

const memory = new WebAssembly.Memory({ initial: 1 });

    function handlePrintString (offset, length) {
      console.log(offset, length);
      const bytes = new Uint8Array(memory.buffer, offset, length);
      const string = new TextDecoder('utf8').decode(bytes);
      console.log(string); //empty ???????????????????????????????????
    }

    const importObject = {
      env: {
        jsPrintString: handlePrintString,
        memory: memory
      },

      js: { mem: memory }
    };

    WebAssembly.instantiateStreaming(fetch('/js/test.wasm'), importObject)
      .then(obj => {
        console.log(obj.instance.exports);
        console.log(obj.instance.exports.print());
      });

内存 ArrayBuffer [0,0,0,0,0,0,0,0,0,0,0.....] ???

【问题讨论】:

  • 您是否收到任何编译错误/警告?
  • emcc 调用中的 EXPORTED_FUNCTIONS 中的“_hello”是什么?它似乎不是您的源代码中的功能。这看起来像是一个复制粘贴问题,您修改了一些示例代码但没有更新命令。

标签: javascript c webassembly


【解决方案1】:

如何从 WebAssembly 函数返回 JavaScript 字符串?

你不能。您必须将其复制到与 JavaScript 共享的内存中。

void hello(char *array) {
    const my_string = "Hello from C++!";
    memcpy(array, my_string, strlen(my_string));
}
  (async () => {
    const response = await fetch('/js/test.wasm');
    const bytes = await response.arrayBuffer();
    const results = await WebAssembly.instantiate(bytes, {});
    const { instance: { exports: { memory, hello } }} = results;
    const array = new Uint8Array(memory.buffer, 0, 15);
    hello(array.byteOffset);
    console.log(new TextDecoder('utf8').decode(array)); // Hello from C++!
  })();

【讨论】:

    猜你喜欢
    • 2017-05-12
    • 2018-05-11
    • 2012-05-03
    • 1970-01-01
    • 2021-12-27
    • 2017-10-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多