Rust wasm:如何访问Webassembly.当前实例的内存(从Rust)? [英] Rust wasm: How to access Webassembly.Memory of current instance (from Rust)?

查看:558
本文介绍了Rust wasm:如何访问Webassembly.当前实例的内存(从Rust)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

查看 js_sys::Uint8Array::new_with_byte_offset_and_length

pub fn new_with_byte_offset_and_length(
    buffer: &JsValue,
    byte_offset: u32,
    length: u32
) -> Uint8Array

它需要一个参数buffer,该参数引用当前wasm实例的内存缓冲区.

It needs an argument buffer which refers to the current wasm instance's memory buffer.

如何从Rust侧访问此类对象? (被编译为wasm)

How do I access such an object from the Rust side ? (that gets compiled to wasm)

推荐答案

它需要一个参数缓冲区,该缓冲区引用当前wasm实例的内存缓冲区.

It needs an argument buffer which refers to the current wasm instance's memory buffer.

首先,值得注意的是,这不一定是正确的.该绑定适用于标准JavaScript API- Uint8Array -允许您从任意缓冲区或容量创建字节数组.

First of all, it's worth noting that this is not necessarily true. That binding is for a standard JavaScript API - Uint8Array - which allows you to create byte arrays from arbitrary buffers or capacity.

如果您只想将字节数组视图传递给Rust内存或将Rust内存中的字节返回给JavaScript,则实际上并不需要此构造函数-为此,请使用wasm-bindgen的标准功能并通过/返回&[u8]Vec<u8>就像在常规Rust代码中一样.

You don't really need this constructor if you just want to pass a byte array view to Rust memory or return bytes in a Rust memory to JavaScript - for that, instead use wasm-bindgen's standard capabilities and pass/return &[u8] or Vec<u8> like you would in regular Rust code.

但是,以防万一,回答问题的第二部分

However, to answer your second part of the question just in case

如何从Rust侧访问此类对象? (被编译为wasm)

How do I access such an object from the Rust side ? (that gets compiled to wasm)

在Rust方面,您可以使用 wasm_bindgen::memory ,它将为您提供一个内存实例.默认情况下,它作为通用JsValue返回,但是您可以将其转换为使用.unchecked_into::<js_sys::WebAssembly::Memory>() ="nofollow noreferrer"> WebAssembly.Memory ,从而可以根据需要访问buffer属性.

From the Rust side you can use wasm_bindgen::memory, which will give you a memory instance. By default it returns it as a generic JsValue, but you can cast it into WebAssembly.Memory using .unchecked_into::<js_sys::WebAssembly::Memory>(), which, in turn, will let you access the buffer property should you need it.

请注意,这样在Rust内存中创建短期Uint8Array视图也可以在内置API

Note that creating short-lived Uint8Array views to Rust memory like that is also implemented in a built-in API js_sys::Uint8Array::view, but it's marked unsafe for a good reason: buffer can get invalidated on any allocation, which lots of built-in APIs invoke, so you need to handle such views very carefully and make sure that they are used immediately after creation. Best way to avoid issues is, again, not relying on such low-level access at all, and instead using #[wasm_bindgen] to generate any bindings.

这篇关于Rust wasm:如何访问Webassembly.当前实例的内存(从Rust)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆