Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to access the instance's memory in a shared host function? #7786

Closed
eigenein opened this issue Jan 17, 2024 · 2 comments
Closed

How to access the instance's memory in a shared host function? #7786

eigenein opened this issue Jan 17, 2024 · 2 comments

Comments

@eigenein
Copy link

eigenein commented Jan 17, 2024

👋 Hi team,

I'm instantiating a long-lived Engine and Linker, and then I'm adding some host functions to the linker (Rust API). Some of these functions should receive a string as a parameter, so an offset and a length in a guest's memory, for example:

let mut linker = wasmtime::Linker::new(&engine);
linker.func_wrap("logging", "info",
    |mut caller: Caller<'_, ()>, (offset, size): (u32, u32)| {
        // How do I access instance's memory here and read from it?
    },
)?;

I could use a closure as suggested in #2491 (comment), but I'm going to support a plugin system, and a shared host function may be called from any plugin. Also, Store is short-lived, and I wouldn't like to re-instantiate a Linker together with the closures for every host-to-guest call

Should I put a reference to Instance or to the instance's Memory into the instance's Store? That smells a little, since Caller already contains Store and all the memories are already owned by Store – so that would effectively be making a loop of references. Am I missing something?

@alexcrichton
Copy link
Member

There's an example for this on the documentation of Func::wrap where the gist of it is:

    let mem = match caller.get_export("memory") {
        Some(Extern::Memory(mem)) => mem,
        _ => anyhow::bail!("failed to find host memory"),
    };

One option is to store a Memory in the T of Store<T> (i.e. replace the () you're using currently), but the easiest option is probably to call caller.get_export(...)

@eigenein
Copy link
Author

@alexcrichton Thank you, just exactly what I needed and completely overlooked!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants