rust实现wss访问_Rust wasm:如何访问Webassembly。当前实例的内存(从Rust)?

bd96500e110b49cbb3cd949968f18be7.png

pub fn new_with_byte_offset_and_length(

buffer: &JsValue,

byte_offset: u32,

length: u32

) -> Uint8Array

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

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

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

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.

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 like you would in regular Rust code.

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

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

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::<:webassembly::memory>(), which, in turn, will let you access the buffer property should you need it.

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值