zoukankan      html  css  js  c++  java
  • [WASM] Read WebAssembly Memory from JavaScript

    We use an offset exporting function to get the address of a string in WebAssembly memory. We then create a typed array on top of the WebAssembly memory representing the raw string data, and decode that into a JavaScript string.

    WASM Fiddle: https://wasdk.github.io/WasmFiddle/?6wzgh

    Demo Repo: https://github.com/guybedford/wasm-intro

    C code:

    char str[] = "Hello World";
    
    char* getStrOffset () {
      return &str[0];
    }

    Here we created a pointer, point to the first chat of the string array.

    When we compile the C code to the WASM:

    (module
      (table 0 anyfunc)
      (memory $0 1)  
      (data (i32.const 16) "Hello World0")
      (export "memory" (memory $0)) # export memory to JS
      (export "getStrOffset" (func $getStrOffset))
      (func $getStrOffset (result i32)
        (i32.const 16) # getStrOffset function return the address in memory as i32.const 16
      )
    )

    Now inside JS, we can get the "memory":

    var wasmModule = new WebAssembly.Module(wasmCode);
    var wasmInstance = new WebAssembly.Instance(wasmModule, wasmImports);
    
    const memory = wasmInstance.exports.memory;

    And remember that it points to the first chat's address in memory.

    So we can use Unit8Array to read buffer:

    const strBuf = new Uint8Array(memory.buffer, wasmInstance.exports.getStrOffset(), 11); // read biffer from the memory, getStrOffset return the first chat address, and since string (Hello World) is 11 lenght
    const str = new TextDecoder().decode(strBuf);
    log(str); // Hello World
  • 相关阅读:
    Rocket
    Rocket
    Rocket
    Rocket
    Rocket
    PHPstorm快捷键大全
    PHP命名规则
    第二章:第2章PHP基础语法
    第一章:初识PHP
    jQuery适用技巧笔记整合
  • 原文地址:https://www.cnblogs.com/Answer1215/p/7096151.html
Copyright © 2011-2022 走看看