SoFunction
Updated on 2024-12-19

How to call the wasm library generated by rust using python wasmtime

This article describes a convenient way to access the rust library using python wasmtime in extremely concise steps that can be used in a production environment.

Install rust target wasm32-wasi

Use the following command to install wasm32-wasi for conveniently compiling rust to wasm bytecode.

rustup target add wasm32-wasi

Preparation of rust libraries

Creating a rust library with cargo

cd /mnt/d/workspace/rust
cargo new --lib wasmlib

Edit file

cd wasmlib
echo "[lib]" >> 
echo "crate-type = ['cdylib']" >> 

Edit rust source file
compilersrc/, modify the document to read as follows

#[no_mangle]
pub extern "C" fn add(a: i32, b: i32) -> i32 {
    a + b
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn it_works() {
        let result = add(2, 2);
        assert_eq!(result, 4);
    }
}

Compile rust library to wasm bytecode

Compile rust library to wasm bytecode

cargo build --release --target wasm32-wasi

Viewing the generated wasm file

cd target/wasm32-wasi/release
ls

The result is as follows, which is the wasm bytecode file:

build  deps  examples  incremental    

Installing the python wasmtime library

pip3 install wasmtime

Test calling the rust library using python wasmtime (wasm bytecode)

hzw@hzwwin:/mnt/d/workspace/rust/wasmlib/target/wasm32-wasi/release$ python3
Python 3.10.4 (main, Apr  2 2022, 09:04:19) [GCC 11.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import 
>>> import wasmlib # Without the .wasm extension
>>> dir(wasmlib)
['__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'add', 'memory']
>>> (2, 2)
4
>>> (2, 4)
6
>>> ("a", "b")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/hzw/.local/lib/python3.10/site-packages/wasmtime/", line 89, in <lambda>
    item = lambda *args,func=func: func(store, *args)  # noqa
  File "/home/hzw/.local/lib/python3.10/site-packages/wasmtime/_func.py", line 83, in __call__
    param_vals = [Val._convert(ty, params[i]) for i, ty in enumerate(param_tys)]
  File "/home/hzw/.local/lib/python3.10/site-packages/wasmtime/_func.py", line 83, in <listcomp>
    param_vals = [Val._convert(ty, params[i]) for i, ty in enumerate(param_tys)]
  File "/home/hzw/.local/lib/python3.10/site-packages/wasmtime/_value.py", line 154, in _convert
    raise TypeError("don't know how to convert %r to %s" % (val, ty))
TypeError: don't know how to convert 'a' to i32

Reference Links

/  

/project/wasmtime/

to this article on how to use python wasmtime call rust generated wasm library is introduced to this article, more related python wasmtime call rust generated wasm library content, please search my previous articles or continue to browse the following related articles I hope that you will support me in the future more!