[llvm-dev] WebAssembly - Import functions from runtime

348 views
Skip to first unread message

Vedant Roy via llvm-dev

unread,
Sep 13, 2020, 11:04:35 PM9/13/20
to llvm...@lists.llvm.org
Hi,

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)?

Best,
Ved


Thomas Lively via llvm-dev

unread,
Sep 14, 2020, 3:05:12 AM9/14/20
to Vedant Roy, llvm-dev
Hi Ved,

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;
}
```

clang -target wasm32 -c hello.c -o hello.o
wasm-ld hello.o -o hello.wasm --no-entry --allow-undefined --export=do_work

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")))`.

Best,

Thomas

_______________________________________________
LLVM Developers mailing list
llvm...@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-dev
Reply all
Reply to author
Forward
0 new messages