【发布时间】:2019-10-17 02:34:20
【问题描述】:
Mozilla 在其blog post 中分享了 WASI 以及如何使用 Wasmtime 运行 .wasm 文件。他们演示的编程语言是 Rust:
#[wasm_bindgen]
pub fn render(input: &str) -> String {
let parser = Parser::new(input);
let mut html_output = String::new();
html::push_html(&mut html_output, parser);
return html_output;
}
但是,我想在 C 中做同样的事情。
我已经下载了wasi-libc 并尝试使用 Clang 构建一个“hello world”程序。
我在 test.c 中创建了两个函数:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int foo1()
{
printf("Hello foo1()\n");
return 0;
}
int foo2(char* filename)
{
printf("Hello foo2()\n");
printf("filename is %s\n", filename);
return 0;
}
使用命令构建它:
clang --target=wasm32-wasi --sysroot=/mnt/d/code/wasi-libc/sysroot test.c -o test.wasm -nostartfiles -Wl,--no-entry,--export=foo1,--export=foo2
运行 wasm 文件以调用函数:
$ wasmtime test.wasm --invoke foo1
Hello foo1()
warning: using `--render` with a function that returns values is experimental and may break in the future
0
$ wasmtime test.wasm --invoke foo2 "hello"
warning: using `--render` with a function that takes arguments is experimental and may break in the future
error: failed to process main module `test.wasm`
caused by: invalid digit found in string
我无法使用输入参数调用函数。
Rust 和 C 有什么区别? Rust 目前是构建 wasm lib 文件的唯一方法吗?
【问题讨论】:
-
这可能是C和Rust中字符串的表示方式不同造成的。
-
@TheWaywardDeveloper 我该如何解决这个问题? Rust 目前是构建 wasm 库的唯一方法吗?
-
我不知道如何用 Wasmtime 解决它,但你当然可以使用 C 来编写 WebAssembly 模块。尝试使用 Wasmer 运行您的模块。
-
@TheWaywardDeveloper 我检查了所有 wasmer 示例。似乎 wasmer 只能运行包含 main() 函数的 wasm 文件。没有示例显示如何运行库模块。
-
可以使用C API调用导出函数:medium.com/wasmer/…
标签: c webassembly wasi wasmtime