安裝wasm-pack
cargo install wasm-pack
新建rust lib 項目
cargo new --lib <project name>
配置Cargo.toml
[package]
name = "rust_wasm"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[lib]
crate-type = ["cdylib"]
[dependencies]
wasm-bindgen = "0.2.78"
[package.metadata.wasm-pack.profile.release]
wasm-opt = false
首先指定构建目标 crate-type = ["cdylib"]
,然后记得关闭 wasm-opt = false
編寫rust代碼
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
extern "C" {
fn alert(s: &str);
}
#[wasm_bindgen]
pub fn add(a: usize, b:usize) -> usize {
a + b
}
編譯代碼爲wasm
wasm-pack build
目錄中多出了pkg
目錄,將其中的rust_wasm_bg.wasm
文件移動到根目錄並重命名爲simple.wasm
備用
編寫python代碼
from wasmer import engine, Store, Module, Instance
import os
__dir__ = os.path.dirname(os.path.realpath(__file__))
module = Module(Store(), open(__dir__ + '/simple.wasm', 'rb').read())
# Now the module is compiled, we can instantiate it.
instance = Instance(module)
# Call the exported `add` function.
result = instance.exports.add(5, 37)
print(result) # 42!
标签:__,bindgen,python,add,wasm,調用,rust,pack
From: https://www.cnblogs.com/poifa/p/16745910.html