Embed a Wasm function
The project provides Rust macros for functions to accept and return complex data types, and then for Go functions to call such Rust functions running in WasmEdge. The full source code for the demo in this chapter is available here.
In the , all you need is to annotate your functions with a macro. Those annotated functions will be automatically instrumented by the Rust compiler and turned into WebAssembly functions that can be called from the wasmedge-bindgen
GO SDK. In the example below, we have several Rust functions that take complex call parameters and return complex values.
You can build the WebAssembly bytecode file using standard Cargo
commands.
Go host application
In the , you can create and set up the WasmEdge VM using the WasmEdge Go SDK. However, instead of calling , you should now call bindgen.Instantiate(vm)
to instantiate the VM and return a bindgen
object.
func main() { // Expected Args[0]: program name (./bindgen_funcs) // Expected Args[1]: wasm file (rust_bindgen_funcs_lib.wasm)) wasmedge.SetLogErrorLevel() var conf = wasmedge.NewConfigure(wasmedge.WASI) var vm = wasmedge.NewVMWithConfig(conf) var wasi = vm.GetImportModule(wasmedge.WASI) wasi.InitWasi( os.Args[1:], // The args os.Environ(), // The envs []string{".:."}, // The mapping preopens ) vm.LoadWasmFile(os.Args[1]) vm.Validate() // Instantiate the bindgen and vm bg := bindgen.Instantiate(vm)
Next, you can call any annotated functions in the VM via the bindgen
object.
Finally, you can build and run the Go host application.
go build ./bindgen_funcs rust_bindgen_funcs_lib.wasm
The standard output of this example will be the following.