简体   繁体   English

如何找出 WebAssembly 缓冲区的地址并将其返回给 Javascript?

[英]How can I find out the address of a WebAssembly buffer and return it to Javascript?

I'm trying to obtain the memory address of a WebAssembly buffer and return it to Javascript, so that I can instaniate its memory as a Javascript ArrayBuffer and directly write in an array in the module's memory at the appropriate address.我正在尝试获取 WebAssembly 缓冲区的内存地址并将其返回给 Javascript,以便我可以将其内存实例化为 Javascript ArrayBuffer 并直接在模块内存中的适当地址处写入数组。

The c code: C代码:

#include <stdint.h>

uint8_t buff[10][100];

uint64_t addr(int buffer_index){
    return (uint64_t)&buff[buffer_index];
}

I compile it with:我编译它:

emcc project.c -Os -s WASM=1 -s SIDE_MODULE=1 -o project.wasm

The html: html:

<script>
var importObject = {
        env: {
            memoryBase: 0,
            tableBase: 0,
            setTempRet0:(x)=>{},
            memory: new WebAssembly.Memory({ initial:256 }),
            table: new WebAssembly.Table({ initial:0, element:'anyfunc' })
        }
    };

    fetch('http://localhost:9000/assets/wasm/project.wasm').then(
        response => response.arrayBuffer()
    ).then(
        bytes => WebAssembly.instantiate(bytes, importObject)
    ).then(
        results => {
            let module=results.instance
            let exports=module.exports
            let addr=exports._addr
            console.log(addr(0))
            console.log(addr(1))
            console.log(addr(2))
        }
    )
</script>

The result of the run:运行结果:

project.html:21 5242880
project.html:22 5242980
project.html:23 5243080

This looks sane, because the buffer has 100 byte chunks, and the returned addresses are 100 bytes apart.这看起来很正常,因为缓冲区有 100 个字节的块,返回的地址相距 100 个字节。

How can I find out where these addresses point in the module's memory?如何找出这些地址在模块内存中的位置?

Your have provided the module with memory via importObject.env.memory .您已经通过importObject.env.memory为模块提供了内存。 You simply have to use the offsets / addresses provided to inspect the memory allocated to your buff variable in your C code:您只需使用提供的偏移量/地址来检查 C 代码中分配给buff变量的内存:

// create a Uint8Array as a 'view' on the module linear memory
// starting at _addr(0), and with a length of 100 elements.
var buffer = new Uint8Array(importObject.env.memory.buffer, exports._addr(0), 100);

for (var i=0; i<buffer.length; i++) {
  var foo = buffer[i];
  // do something with foo here!
}

You can see a more complete example in my project that renders a Mandelbrot fractal .您可以在我的项目中看到一个更完整的示例,示例呈现 Mandelbrot 分形

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM