【问题标题】:Failed to invoke functions when running wasm file with wasmtime使用 wasmtime 运行 wasm 文件时调用函数失败
【发布时间】: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


【解决方案1】:

不同之处在于,Rust 工具链对接口类型具有实验性支持,而不幸的是,对于 C 语言尚不存在。 render 函数上方的 #[wasm_bindgen]render 转换为使用接口类型绑定导出的函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-15
    • 2021-03-26
    • 1970-01-01
    • 2023-03-29
    相关资源
    最近更新 更多