0

I'm trying to return a typed object from Rust to Typescript, and I ideally don't want to have to manually manage memory (performance is not the highest priority). While doing this, I'm trying to understand the generated JS.

Rust:

#[wasm_bindgen]
pub fn retjs() -> JsValue {
    // in my actual project I serialize a struct with `JsValue::from_serde`
    JsValue::from_str("")
}

#[wasm_bindgen]
pub fn retstruct() -> A {
    A {
        a: "".to_owned(),
    };
}

#[wasm_bindgen]
pub struct A {
    a: String,
}

#[wasm_bindgen]
impl A {
    #[wasm_bindgen]
    pub fn foo(&self) -> String {
        return self.a.clone();
    }
}

Generated JS:

export function retjs() {
    const ret = wasm.retjs();
    return takeObject(ret);
}

function takeObject(idx) {
    const ret = getObject(idx);
    dropObject(idx);
    return ret;
}

function dropObject(idx) {
    if (idx < 36) return;
    heap[idx] = heap_next;
    heap_next = idx;
}

export function retstruct() {
    const ret = wasm.retstruct();
    return A.__wrap(ret);
}


// generated class A omitted for brevity. Here relevant that it has a `free()` method.

Is my understanding correct that with the JsValue the memory is completely freed automatically? And that I've to do this manually with the struct? Is there a way to get around that?

I basically just want type safety in Typescript, so when I update the struct in Rust the Typescript code is automatically updated.

User
  • 31,811
  • 40
  • 131
  • 232
  • 1
    I believe that it's only partially possible, and it's currently under discussion ... not sure if you've looked at : https://github.com/wnfs-wg/rs-wnfs/issues/32 and https://github.com/rustwasm/wasm-bindgen/issues/1591#issuecomment-610540002 ... – Ahmed Masud Nov 19 '22 at 20:36
  • @AhmedMasud thanks for the links! here's it's documented: https://rustwasm.github.io/wasm-bindgen/reference/attributes/on-rust-exports/typescript_custom_section.html (so far tested it for the parameters)... do you happen to have an example for the `MyTypescriptExport` macro described there? I'll continue investigating next week otherwise / if there's no more feedback. – User Nov 19 '22 at 21:08
  • 1
    Is this https://docs.rs/typescript-type-def/latest/typescript_type_def/ something close to what you need? – Ahmed Masud Nov 19 '22 at 22:41
  • @AhmedMasud thanks! That exported the structs to JS. Not able yet to wire this JS from the wasm-bindgen exports. – User Nov 21 '22 at 19:06

0 Answers0