本文介绍了使用python wasmtime来访问rust库的便捷方法,步骤极其简练,可以在生产环境中使用。
安装rust target wasm32-wasi
使用如下命令安装wasm32-wasi,用于便捷地将rust编译为wasm字节码。
rustup target add wasm32-wasi
编写rust库
- 使用cargo创建rust库
cd /mnt/d/workspace/rust
cargo new --lib wasmlib
- 编辑Cargo.toml文件
cd wasmlib
echo "[lib]" >> Cargo.toml
echo "crate-type = ['cdylib']" >> Cargo.toml
- 编辑rust源文件
编辑src/lib.rs
, 修改文件内容如下
#[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);
}
}
将rust库编译为wasm字节码
- 将rust库编译为wasm字节码
cargo build --release --target wasm32-wasi
- 查看生成的wasm文件
cd target/wasm32-wasi/release
ls
结果如下,其中wasmlib.wasm就是wasm字节码文件:
build deps examples incremental wasmlib.d wasmlib.wasm
安装python wasmtime库
pip3 install wasmtime
测试使用python wasmtime调用rust库(wasm字节码)
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 wasmtime.loader
>>> import wasmlib # 不需要加.wasm扩展名
>>> dir(wasmlib)
['__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'add', 'memory']
>>> wasmlib.add(2, 2)
4
>>> wasmlib.add(2, 4)
6
>>> wasmlib.add("a", "b")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/hzw/.local/lib/python3.10/site-packages/wasmtime/loader.py", 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
参考链接
https://docs.wasmtime.dev/
https://pypi.org/project/wasmtime/
转载:https://blog.csdn.net/huzhenwei/article/details/128517154
查看评论