Is there a method for importing functions from the Web Assembly runtime when writing C? I know Emscripten has support for calling JS functions from C code, but I was wondering if there’s an easy way to do this without Emscripten (pure Clang)?
Yes, the trick is to declare the functions you want to import in your C source, then pass the --allow-undefined flag to wasm-ld when linking your wasm module. Here’s a complete example:
hello.c:
int print_int(int x);
int do_work(int x) {
print_int(x);
return x;
}
This will give you a wasm module that imports function “env” “print_int” and exports function “do_work”. Note that Wasm uses a two-level namespace for imports, but the first level will always be “env” unless you annotate the function declaration with __attribute__((import_module("my_other_namespace"))).