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

Rust构建Wasm插件供Wasmer加载时出现链接导入错误求助

问题

我有一个Rust项目需要使用以Wasm模块形式分发的插件,网上的指南大多针对Web场景,不符合我的需求。我创建了两个项目,但运行加载程序时出现panic。

插件库(plugin)代码与配置

lib.rs:

// lib.rs
use wasm_bindgen::prelude::*;

#[wasm_bindgen]
pub fn add(left: i32, right: i32) -> i32 {
    left + right
}

Cargo.toml:

[package]
name = "plugin"

[lib]
crate-type = ["cdylib", "rlib"]

[dependencies]
wasm-bindgen = "0.2.89"

构建命令:

rustup target add wasm32-unknown-unknown
cargo build --target wasm32-unknown-unknown

加载运行程序(core)代码与配置

main.rs:

// main.rs
use wasmer::{Store, Module, Instance, Value, imports};

fn main() {
    let bin = std::fs::read("/path/to/target/wasm32-unknown-unknown/debug/plugin.wasm").unwrap();
    let mut store = Store::default();
    
    let module = Module::from_binary(&store, &bin).expect("Should compile");

    let import_object = imports! {};
    let instance = Instance::new(&mut store, &module, &import_object).expect("Should create instance");

    let add = instance.exports.get_function("add").expect("Should get function");
    let result = add.call(&mut store, &[Value::I32(5), Value::I32(5)]).expect("Should call add");
    let value = result[0].i32();

    println!("Result: {:?}", value);
}

Cargo.toml:

[package]
name = "core"

[dependencies]
wasmer = "4.2.5"

运行命令:

cargo run

错误信息

运行时在Instance::new处触发panic:

Link(Import("__wbindgen_placeholder__", "__wbindgen_describe", UnknownImport(Function(FunctionType { params: [I32], results: [] }))))
解决方案

问题根源

你使用了wasm-bindgen导出函数,但wasm-bindgen是为Web环境设计的工具,它会给生成的Wasm模块添加大量Web相关的导入依赖(比如报错中的__wbindgen_describe),而Wasmer是原生Wasm运行时,并不提供这些Web环境的导入,因此导致链接失败。

修改步骤

1. 调整插件库(plugin)

移除wasm-bindgen依赖,改用原生Rust的C ABI导出方式:

修改lib.rs:

// lib.rs
#[no_mangle]
pub extern "C" fn add(left: i32, right: i32) -> i32 {
    left + right
}

修改Cargo.toml,删除wasm-bindgen相关配置:

[package]
name = "plugin"

[lib]
crate-type = ["cdylib"]  # 无需rlib,仅需生成Wasm动态库

重新构建插件:

cargo build --target wasm32-unknown-unknown

2. 验证加载程序

当前核心程序的代码已经兼容C ABI导出的Wasm函数,只需确保Wasm文件路径正确,重新执行cargo run即可得到预期输出Result: 10。

额外说明

如果需要复杂的插件交互(比如传递字符串、自定义结构体),可以使用Wasmer自带的类型绑定工具,或手动处理内存布局,避免依赖面向Web的wasm-bindgen。

内容的提问来源于stack exchange,提问作者David Alsh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 17:40:17