简体   繁体   English

如何协调主机 JS 和 Wasm 模块之间的内存访问?

[英]How can I coordinate Memory access between the host JS and the Wasm module?

At present, Webassembly only supports a handful of parameter types , namely fixed sized integers and floating point numbers.目前,Webassembly 仅支持少数参数类型,即固定大小的整数和浮点数。 This means that I can only define and export functions from my C/Rust modules that accept and return numeric values.这意味着我只能从接受和返回数值的 C/Rust 模块中定义和导出函数。

However, according to the Mozilla Developer Network , I can manipulate the module's memory from the host Javascript:但是, 根据 Mozilla Developer Network ,我可以从主机 Javascript 操作模块的内存:

[M]emory created by JavaScript or in WebAssembly code will be accessible and mutable from both JavaScript and WebAssembly. [M] 由 JavaScript 或 WebAssembly 代码创建的内存将可以从 JavaScript 和 WebAssembly 访问和可变。

This sounds very promising--it indicates that I could designate part of the memory as a byte buffer in which to shuttle more complex data back and forth across the language barrier.这听起来很有希望——它表明我可以将内存的一部分指定为字节缓冲区,在其中来回传输更复杂的数据跨越语言障碍。 Functions in my module could accept and return pointers (which are themselves i32 , fixed size integers), thereby working within the current constraints.我的模块中的函数可以接受和返回指针(它们本身是i32 ,固定大小的整数),从而在当前约束内工作。

Unfortunately, it is not clear how I should go about managing this memory.不幸的是,我不清楚应该如何管理这个内存。 If I need to pass data to the Wasm process from JS, I need to write to the Memory object directly but won't know which regions in the Memory are free.如果我需要从 JS 向 Wasm 进程传递数据,我需要直接写入 Memory 对象,但不知道 Memory 中的哪些区域是空闲的。

What's the safest strategy?什么是最安全的策略? Should I export a pair of malloc -and- free -style functions that give the JS a way to request memory before calls into Wasm?我应该导出一对mallocfree风格的函数,让 JS 在调用 Wasm 之前请求内存吗? Or is there an established best practice?或者是否有既定的最佳实践?

I think the easiest thing is to use Emscripten, and use its built-in malloc / free.我认为最简单的方法是使用 Emscripten,并使用其内置的 malloc/free。 Then export a function which, in C++, allocates the memory requested through that malloc / free, and returns the pointer.然后导出一个函数,该函数在 C++ 中分配通过 malloc / free 请求的内存,并返回指针。 That way JavaScript can call into WebAssembly to get a usable memory region which isn't already used.这样 JavaScript 就可以调用 WebAssembly 以获取尚未使用的可用内存区域。

I've detailed how to share strings to / from JS / wasm in this answer , which has details on some of the above.我在这个答案中详细介绍了如何与 JS/wasm 共享字符串/从 JS/wasm 共享字符串,其中包含上述某些内容的详细信息。

Note that pointers in WebAssembly aren't really a thing.请注意,WebAssembly 中的指针并不是真正的东西。 C++ simply maps them to the Memory, which starts at 0. So when you index the ArrayBuffer you just need the pointer from C++, no extra mapping required. C++ 只是将它们映射到从 0 开始的内存。因此,当您索引 ArrayBuffer 时,您只需要来自 C++ 的指针,不需要额外的映射。

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

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