WebAssembly / wasm-c-api

Wasm C API prototype
Apache License 2.0
534 stars 77 forks source link

How to import a native func to "env"? #191

Closed MrHate closed 4 months ago

MrHate commented 4 months ago

I'm new to this wasm-c-api but I couldn't find any doc or example about it. I'm trying some wasm applications that import native functions from the env 'env' (commonly compiled with emcc), what is a correct way to achieve this with the wasm-c-api interface?

rossberg commented 4 months ago

You can find various examples in the example/ directory of this repo. In particular, the callback example shows how to create a host function and provide that as an import.

The other half of your question seems to be how to populate the "env" import of Emscripten-compiled code. That is merely a naming convention used by Emscripten. On the raw Wasm level it simply amounts to a set of imports whose module name is "env". However, in the C API, import names are irrelevant. You simply provide the imports to a module as a vector of extern values in the order declared by that module.

MrHate commented 4 months ago

Thanks a lot for replying, but sorry I don't follow you.

However, in the C API, import names are irrelevant. You simply provide the imports to a module as a vector of extern values in the order declared by that module.

Is this impossible to achieve or any feasible way with specific code as example? I've checked the examples in the example/ dir but none enlightens me.

rossberg commented 4 months ago

Unfortunately, I don't have time to spell out an Emscripten example, especially since I never use it. But from the API perspective it is straightforward. For example, if you look at threads.wat then this module has two imports, a function and a global. The corresponding C code instantiating it constructs a C array that matches this import list, in the same order. That works for any number of imports; names are irrelevant for this.

To instantiate a module created by Emscripten the hard part is knowing its entire list of imports (e.g. by inspecting it with a tool). But once you have implemented all the functions, you construct a matching array in the same way as above. Most Emscripten imports will happen to use "env" as a part of their import name, but again, that is completely irrelevant when using the C API — all that matters is the order of the individual imports.

MrHate commented 4 months ago

I see. My test code indeed works without "env" annotation in function imports. Thank you very much for explanation.