python調用wasm

安裝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!
posted @ 2022-09-30 19:16  七つ一旋桜  阅读(322)  评论(0)    收藏  举报