当我编写一个返回一个js_sys::Uint8Array的函数时(以Rust表示):
#[wasm_bindgen]
pub extern "C" fn gen_pubKey(seed: &[u8]) -> Uint8Array {
let (privKey, pubKey) = ed25519::keypair(&seed);
unsafe { Uint8Array::view(&pubKey) }
}然后使用wasm-pack编译它,然后从js/typescript端以这种方式调用wasm函数:
let seed = new Uint8Array([0, 0, 1, 1, 2, 2]);
let pubKey: Uint8Array = gen_pubKey(seed);
console.log({ pubKey });通过类型记录将结果pubKey正确地转换为Uint8Array。
现在,如何从一个生锈函数返回两个Uint8Array**s,并使它们正确地转换为** Uint8Array ?。
我试过以下几种方法:
Uint8Array放到结构中,然后从gen_keypair()返回结构 #[wasm_bindgen]
pub struct KeyPairJS {
pub privKey: Uint8Array,
pub pubKey: Uint8Array,
}这甚至不能编译,因为js_sys::Uint8Array没有实现IntoWasmAbi
*const Uint8Arrays放入这个结构中,并从gen_keypair()返回 #[wasm_bindgen]
pub struct KeyPairJS {
pub privKey: *const Uint8Array,
pub pubKey: *const Uint8Array,
}这不起作用,因为*const Uint8Array只是一个数字。在类型记录方面,它没有实现Uint8Array的所有方法
IntoWasmAbi又包含足够信息的类型,以便在内存中找到Uint8Array的内容,并从类型记录端重新创建该类型: #[wasm_bindgen]
#[derive(Copy, Clone)]
pub struct Bytes {
offset: *const u8,
size: usize,
}
#[wasm_bindgen]
impl Bytes {
pub fn new(bytes: &[u8]) -> Bytes {
Bytes {
offset: bytes.as_ptr(),
size: bytes.len(),
}
}
pub fn offset(&self) -> *const u8 {
self.offset
}
pub fn size(&self) -> usize {
self.size
}
}在这里,我不确定如何访问当前wasm实例的内存缓冲区( 防锈或从打字本),我需要重新创建原始Uint8Array的
Uint8Array的数组,但没有任何成功。发布于 2022-09-20 00:55:09
Wasm Bindgen要求复制公共方法。解决方案之一是将struct字段设置为私有字段和实现getter/setter方法。使用Box而不是Uint8Array:
#[wasm_bindgen]
pub struct KeyPairJS {
privKey: Box<[u8]>,
pubKey: Box<[u8]>,
}
#[wasm_bindgen]
impl KeyPairJS {
#[wasm_bindgen(constructor)]
pub fn new() -> Self {
// Keypair generation here
}
#[wasm_bindgen(getter)]
pub fn privKey(&self) -> Box<[u8]> {
self.privKey
}
}然后,您可以从javascript访问它,就像它是一个常规类字段一样。
var keys = new KeyPairJS();
var privateKey = keys.privKeyhttps://stackoverflow.com/questions/60215271
复制相似问题