开发者

如何使用python wasmtime调用rust生成的wasm库

目录
  • 安装rust target wasm32-wasi
  • 编写rust库
  • 将rust库编译为wasm字节码
  • 安装python wasmtime库
  • 参考链接

本文介绍了使用python wasmtime来访问rust库的便捷方法,步骤极其简练,可以在生产环境中使用。

安装rust target wasm32-wasi

使用如下命令安装wasm32-wasi,用于便捷地将rust编译为wasm字节码。

rustup target add wasm32-wasi

编写rust库

使用cargo创建rust库

cd /mnt/d/workspace/rust
carjavascriptgo new --lijsb 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.php4 (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: funcpython(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)]
开发者_JS学习  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/

到此这篇关于如何使用python wasmtime调用rust生成的wasm库的文章就介绍到这了,更多相关python wasmtimwww.devze.come调用rust生成的wasm库内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新开发

开发排行榜