You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

执行WASI教程遇wasmtime加载错误,求解决方案

问题描述

我正尝试按照WASI教程操作,但始终遇到错误。当前使用wasmtime-cli 1.0.0版本和clang 14.0.0版本。教程包含三个简单步骤:

  1. 将示例代码保存为demo.c(代码见下文);
  2. 执行clang demo.c -o demo.wasm编译;
  3. 执行wasmtime demo.wasm运行,此时出现错误:

Error: failed to run main module demo.wasm

Caused by:
cannot load precompiled module demo.wasm unless --allow-precompiled is passed

添加--allow-precompiled参数重新运行wasmtime --allow-precompiled demo.wasm后,又出现新错误:

Error: failed to run main module demo.wasm

Caused by:
bytes are not a compatible serialized wasmtime module

附demo.c代码:

// demo.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>

int main(int argc, char **argv) {
    ssize_t n, m;
    char buf[BUFSIZ];

    if (argc != 3) {
        fprintf(stderr, "usage: %s <from> <to>\n", argv[0]);
        exit(1);
    }

    int in = open(argv[1], O_RDONLY);
    if (in < 0) {
        fprintf(stderr, "error opening input %s: %s\n", argv[1], strerror(errno));
        exit(1);
    }

    int out = open(argv[2], O_WRONLY | O_CREAT, 0660);
    if (out < 0) {
        fprintf(stderr, "error opening output %s: %s\n", argv[2], strerror(errno));
        exit(1);
    }

    while ((n = read(in, buf, BUFSIZ)) > 0) {
        char *ptr = buf;
        while (n > 0) {
            m = write(out, ptr, (size_t)n);
            if (m < 0) {
                fprintf(stderr, "write error: %s\n", strerror(errno));
                exit(1);
            }
            n -= m;
            ptr += m;
        }
    }

    if (n < 0) {
        fprintf(stderr, "read error: %s\n", strerror(errno));
        exit(1);
    }

    return EXIT_SUCCESS;
}
问题原因

直接用clang demo.c -o demo.wasm编译出来的不是WASI兼容的WebAssembly模块,而是原生ELF可执行文件——哪怕后缀名改成了.wasm,实际格式完全不符合Wasm标准。Wasmtime误把这个文件当成了预编译的Wasm模块,因此抛出一系列错误。

解决方法

要编译出符合WASI标准的Wasm模块,必须使用clang的WASI目标工具链,具体步骤如下:

  1. 安装WASI SDK
    先确保本地安装了WASI SDK,可通过系统包管理器(如部分Linux发行版的wasi-sdk包)或官方渠道获取安装。

  2. 用WASI目标编译代码
    替换原来的编译命令,明确指定Wasm32-WASI目标架构:

    clang --target=wasm32-wasi demo.c -o demo.wasm
    

    如果系统没自动识别WASI SDK路径,需手动指定标准库路径:

    clang --target=wasm32-wasi --sysroot=/你的WASI安装路径/share/wasi-sysroot demo.c -o demo.wasm
    

    把路径替换成你实际的WASI SDK安装位置。

  3. 运行Wasm模块
    编译完成后,直接用Wasmtime运行即可,记得传入程序要求的两个参数(输入文件和输出文件):

    wasmtime demo.wasm input.txt output.txt
    

内容的提问来源于stack exchange,提问作者J'e

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 14:45:35