wit-bindgen icon indicating copy to clipboard operation
wit-bindgen copied to clipboard

Importing and exporting from the same module with shared types

Open philpax opened this issue 1 year ago • 0 comments

I suspect this won't generally be possible until #292 is resolved, but worth asking anyway: I have a Rust guest and a Rust/wasmtime host. I'd like to import functionality from the host in the guest (functions to interact with the host etc), but I'd like to export a function from the guest using wit-bindgen at the same time.

As a more concrete example:

Shared:

record entity-id {
    namespace: u8,
    id: u64,
    gen: s32,
}

record vec3 {
    x: float32,
    y: float32,
    z: float32,
}

record event-player-spawn-data {
    id: entity-id,
}

variant event {
    player-spawn(event-player-spawn-data),
}

Host export/Guest import:

entity-spawn: func(object-ref: string, position: vec3) -> option<entity-id>

Guest export/Host import:

runtime-exec: func(evt: event)

runtime-exec does some work in the guest with the passed in event.

Right now, I'm using a hack where I assume memory layout and copy a repr-C version of the event that's available to both the host and the guest into the global memory of the guest. I'd much rather prefer passing it in with wit-bindgen's machinery so that I don't have to share the type between the boundary manually and avoid the general dodginess of memory manipulation.

Given that #292 restricts me to a single .wit file presently, is there a way to invert the direction of a binding for a single binding (e.g. all of the above bindings are in the same file, but runtime-exec is in the opposite direction of the rest of the bindings)?

philpax avatar Jul 28 '22 18:07 philpax