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 文件的唯一方法吗?
最佳答案
不同之处在于 Rust 工具链对接口(interface)类型提供了实验性支持,而不幸的是,C 尚不支持。 render
函数上方的 #[wasm_bindgen]
是将 render
转换为通过接口(interface)类型绑定(bind)导出的函数。
关于c - 使用 wasmtime 运行 wasm 文件时无法调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58424072/