我试图Uint8Array
在编码后将字符串保存在 Wasm 堆中,并将指向字符串的指针和长度保存在 Struct 中,以便以后可以访问该字符串。下面是我的代码rust
#[wasm_bindgen]
pub struct CustomString{
ptr : *const u8,
len: usize
}
#[wasm_bindgen]
impl CustomString{
pub fn create(len:usize) -> Self{
let mut d = Vec::with_capacity(len);
log!("{}",len);
CustomString{
ptr: d.as_ptr(),
len
}
}
pub fn as_ptr(&self) -> *const u8{
self.ptr
}
pub fn print_string(&self){
let js = unsafe { std::slice::from_raw_parts(self.ptr, self.len) };
let js = unsafe { std::str::from_utf8_unchecked(js) };
log!("{}",js)
}
}
我的 JS 端代码如下:
function myTest (){
debugger;
const { memory } = wasm;
let encoder = new TextEncoder();
let mystring = "Ujjal";
let encodedString = encoder.encode(mystring);
let length = encodedString.length;
console.log(length)
let cs = CustomString.create(length);
let ptr = cs.as_ptr();
const asBytes = new Uint8Array(memory.buffer, ptr, length);
asBytes.set(encodedString);
return cs;
}
let cs = myTest();
function decode(cs){
cs.print_string();
}
decode(cs);
理想情况下,它应该打印给定的字符串,但它会显示一些不相关的垃圾值。无法弄清楚出了什么问题,因为我对 rust 和 wasm 还很陌生。