批里批里 (゜-゜)つ🍺 干杯~|

七つ一旋桜

园龄:4年2个月粉丝:6关注:3

2022-09-30 19:16阅读: 269评论: 0推荐: 0

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!

本文作者:七つ一旋桜

本文链接:https://www.cnblogs.com/poifa/p/16745910.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   七つ一旋桜  阅读(269)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起