前言
Rust 是一个现代版的 C/C++ 程式语言,它加入物件导向、套件安装(cargo)、函数式程式设计(Functional Programming)、WebAssembly...等等的设计模式与观念,同时改善C最致命的缺点 -- 记忆体洩漏(Memory Leak),是一个值得投资的语言。
另外,也可以与Python整合,弥补Python直译器不能建置为执行档的缺憾,既可以加速执行的速度,程式码又可以免于公开。
Rust 安装
安装程序非常简单,只要两步骤:
下载且安装:
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
按 Enter 即可。
验证:
rustc --version
建立 C 相关环境:
sudo apt install build-essential
写一支 Rust 程式
建立专案,不要用大写:cargo new hello_world
编译专案:cd hello_world# 编译cargo build# 执行cargo run
显示 Hello, world!
可修改 src/main.rs 程式。
也可以编译 main.rs,成为执行档:
rustc main.rs
之后就可以执行,不可以在档案管理员 double click,因为目前路径不在预设搜寻路径中:
./main
可以修改登入档(gedit ~/.bashrc),加入目前路径在预设搜寻路径中:
export PATH=$PATH:.
Python 与 Rust 整合
请参阅『Rust Inside Other Languages』说明,
建立专案,不要用大写:cargo new embed
src/main.rs改名为lib.rs,程式码如下,主要是产生10个执行緖,每个执行緖累加0至5百万:use std::thread;#[no_mangle]pub extern fn process() { let handles: Vec<_> = (0..10).map(|_| { thread::spawn(|| { let mut x = 0; for _ in 0..5000000 { x += 1 } x }) }).collect(); for h in handles { println!("Thread finished with count={}", h.join().map_err(|_| "Could not join a thread!").unwrap()); } println!("Rust done!");}
修改 Cargo.toml,在档案尾巴加入以下设定:[lib]name = "embed"crate-type = ["dylib"]
建置专案:cargo build --release
产生函数库 target/release/libembed.so。
新增 Python 档案 embed.py,程式码如下:from ctypes import cdll# linuxlib = cdll.LoadLibrary("target/release/libembed.so")# Windows#lib = cdll.LoadLibrary("target/release/embed.dll")lib.process()print("done!")
测试,以 Python 呼叫 Rust:python embed.py
输出如下:
Thread finished with count=5000000Thread finished with count=5000000Thread finished with count=5000000Thread finished with count=5000000Thread finished with count=5000000Thread finished with count=5000000Thread finished with count=5000000Thread finished with count=5000000Thread finished with count=5000000Thread finished with count=5000000Rust done!done!
胜利成功,Happy Coding !!