Reputation: 105
I'm trying to run some small C demos on the web with WebAssembly and pure JS, and I'm compiling my code using WASI-SDK/WASI-libc:
clang --target=wasm32-unknown-wasi --sysroot=<sysroot> -nostartfiles -O3 -flto -Wl,--no-entry -Wl,--export=malloc -Wl,--export-all -Wl,--lto-O3 src.c -o src.wasm
I'm then using this small JS library to implement the WASI functions. This works fine for printing with stdout, and I've even tested passing strings and other types into different functions. But I can't figure out how to pass an array of strings into main
as an argument.
I don't want to use Node or Emscripten, which is why I went with a minimal JS implementation.
Edit:
To add command line arguments, I removed both -nostartfiles
and -Wl,--no-entry
from my compiler call and implemented args_get
and args_sizes_get
from the WASI standard. From there, it was as simple as calling _start
from the wasm
's exported functions.
Upvotes: 1
Views: 1403
Reputation: 3022
If you want to use WASI then the way to pass args to main is to implement the wasi_snapshot_preview1.args_get
and wasi_snapshot_preview1.args_sizes_get
syscalls which are used by WASI programs to access the argv values. In that case you would want to call _start
rather than main
.
If you want to bypass that and call main
directly you would need to somehow allocate and array of char *
pointers in the linear memory which you could then pass as your argv value. The problem that you face if you try to take this approach is that allocating memory (e.g. via malloc) before calling main is hard. My advise would be to go with the first method which is to call _start
and implement that wasi
syscall needed to access argv
. (You can call also then remove the -Wl,--no-entry
from your link command).
Upvotes: 2