bytecodealliance / wasmtime

A fast and secure runtime for WebAssembly
https://wasmtime.dev/
Apache License 2.0
14.82k stars 1.24k forks source link

[question] Can we call specific functions in a wasm file? #8762

Closed nyue closed 2 weeks ago

nyue commented 4 weeks ago

I am studying this C and WASI approach

https://docs.wasmtime.dev/examples-c-wasi.html

Let's say I have something like this

fn myfunction1(first_name: &str) {
    println!("My function 1, {}!", first_name);
}

fn myfunction2(last_name: &str) {
    println!("My function 2, {}!", last_name);
}

Can I call myfunction1 and myfunction2 via wasmtime C-API ?

How would the C code call look like ? Is there some example I can reference for further studying ?

Cheers

ssnover commented 4 weeks ago

Check out the next page: https://docs.wasmtime.dev/examples-c-linking.html

There they get a function which was defined and exported from the wasm module called run, then call it. (the following pages show some examples of passing arguments to the exported function)

// Lookup our `run` export function
wasmtime_extern_t run;
bool ok = wasmtime_instance_export_get(context, &linking1, "run", 3, &run);
assert(ok);
assert(run.kind == WASMTIME_EXTERN_FUNC);
error = wasmtime_func_call(context, &run.of.func, NULL, 0, NULL, 0, &trap);
if (error != NULL || trap != NULL)
  exit_with_error("failed to call run", error, trap);
alexcrichton commented 4 weeks ago

To better understand how to work with a module like this in C you'll need to probably understand how Rust translates to wasm. For example the functions you listed above there's a number of issues:

Overall the tl;dr; is that calling functions like the ones you're outlining is going to require a good deal of work. Much of that is sort of just the reality of wasm, it's a "virtual CPU" and there's lots of stuff you need to do to interact with a CPU. This is one of the reasons we've been working on the component model is that it ends up handling much of this for you. That being said the component model does not have a C API at this time, so I bring this up mostly to put something on your radar, not to propose a solution for you at this time.

alexcrichton commented 2 weeks ago

I think this has been answered so I'm going to close this, but if there's still more questions feel free to comment and/or open another issue.