bytecodealliance / wasmtime-dotnet

.NET embedding of Wasmtime https://bytecodealliance.github.io/wasmtime-dotnet/
Apache License 2.0
409 stars 52 forks source link

unknown import: `xxxmodule::xxxFunc` has not been defined #260

Closed zxyao145 closed 1 year ago

zxyao145 commented 1 year ago

Hi, I am trying to interact with multiple modules using wasmtime. I exported a func main.add in the module go-wasm-module. wasm and imported it in WasmLib.wasm. However, when executing inker.Instantiate (store, wasmLibModule), it failed and resulted in the following exception:

unknown import: `go-wasm-module::main.add` has not been defined

How can I solve it? And here are my core sample code and some key outputs:

var wasi = new WasiConfiguration()
    .WithInheritedStandardInput()
    .WithInheritedStandardOutput()
    .WithInheritedStandardError();
var engine = new Engine();
var store = new Store(engine);
store.SetWasiConfiguration(wasi);
var linker = new Linker(engine);
linker.DefineWasi();

var wasmFile = "../../../../WasmLib/bin/Debug/net6.0/WasmLib.wasm";
var goWasmFile = "../../../../wasm-module/go-wasm-module/go-wasm-module.wasm";

linker.DefineFunction("env", "hello_from_env", () =>
{
    Console.WriteLine("Hello from the Dotnet Host!");
});

using var goWasmModule = Module.FromFile(engine, goWasmFile);
using var wasmLibModule = Module.FromFile(engine, wasmFile);

// go-wasm-module
Console.WriteLine(goWasmModule.Name);
// True
Console.WriteLine(goWasmModule.Exports.Any(x=>x.Name == "main.add"));

var goWasmIns = linker.Instantiate(store, goWasmModule);
var r = goWasmIns.GetFunction("main.add")?.Invoke(1, 3);
// 4
Console.WriteLine(r);

// exception: unknown import: `go-wasm-module::main.add` has not been defined
var wasmLibIns = linker.Instantiate(store, wasmLibModule);
// ...
zxyao145 commented 1 year ago

I got the reason, the linker does not know what the corresponding Module instance for go-wasm-module is. It can be defined through the following code:

linker.DefineModule(store, goWasmModule);

or

linker.DefineInstance(store, "go-wasm-module", goWasmIns);