简体   繁体   English

如何使用 WebAssembly 和 JS 将命令行 arguments 传递给 C 代码?

[英]How to pass command line arguments to C code with WebAssembly and JS?

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:我正在尝试使用 WebAssembly 和纯 JS 在 web 上运行一些小型 C 演示,并且我正在使用 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.然后我使用这个小的 JS 库来实现 WASI 函数。 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.但我不知道如何将字符串数组作为参数传递给main

I don't want to use Node or Emscripten, which is why I went with a minimal JS implementation.我不想使用 Node 或 Emscripten,这就是我使用最小 JS 实现的原因。

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.为了添加命令行 arguments,我从编译器调用中删除了-nostartfiles和 -Wl -Wl,--no-entry ,并从 WASI 标准中实现了args_getargs_sizes_get From there, it was as simple as calling _start from the wasm 's exported functions.从那里开始,就像从wasm的导出函数调用_start一样简单。

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.如果您想使用 WASI,那么将 args 传递给 main 的方法是实现wasi_snapshot_preview1.args_getwasi_snapshot_preview1.args_sizes_get系统调用,WASI 程序使用它们来访问 argv 值。 In that case you would want to call _start rather than main .在这种情况下,您需要调用_start而不是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.如果您想绕过它并直接调用main ,则需要以某种方式在线性 memory 中分配和数组char *指针,然后您可以将其作为您的 argv 值传递。 The problem that you face if you try to take this approach is that allocating memory (eg via malloc) before calling main is hard.如果您尝试采用这种方法,您将面临的问题是在调用 main 之前分配 memory(例如通过 malloc)很难。 My advise would be to go with the first method which is to call _start and implement that wasi syscall needed to access argv .我的建议是 go 使用第一种方法是调用_start并实现访问argv所需的wasi系统调用。 (You can call also then remove the -Wl,--no-entry from your link command). (您也可以调用,然后从链接命令中删除-Wl,--no-entry )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM