1. 程式人生 > 其它 >4.1 python中呼叫rust程式

4.1 python中呼叫rust程式

概述

使用rust-cpython將rust程式做為python模組呼叫;

通常為了提高python的效能;

參考

https://github.com/dgrunwald/rust-cpython

建立rust lib庫

cargo new rust2py --lib

或者使用IDE建立一個rust lib庫專案

Cargo.toml

[package]
name = "rust2py"
version = "0.1.0"
edition = "2018"


[lib]
name = "rust2py"
crate-type = ["cdylib"]

[dependencies.cpython]
version 
= "0.3" features = ["extension-module"]

lib.rs

#[cfg(test)]
mod tests {
    #[test]
    fn it_works() {
        assert_eq!(2 + 2, 4);
    }
}

#[macro_use]
extern crate cpython;

use cpython::{PyResult, Python, py_module_initializer, py_fn};


pub fn print_str(a: String) -> String {
    print!("
{:#?}",a); a } pub fn print_str_py(_: Python, a: String) -> PyResult<String>{ let mm = print_str(a); Ok(mm) } // logic implemented as a normal rust function fn sum_as_str(a:i64, b:i64) -> String { format!("{}", a + b).to_string() } // rust-cpython aware function. All of our python interface could be
// declared in a separate module. // Note that the py_fn!() macro automatically converts the arguments from // Python objects to Rust values; and the Rust return value back into a Python object. fn sum_as_str_py(_: Python, a:i64, b:i64) -> PyResult<String> { let out = sum_as_str(a, b); Ok(out) } py_module_initializer!(rust2py, init_rust2py, PyInit_rust2py, |py, m| { m.add(py, "__doc__", "This module is implemented in Rust.")?; m.add(py, "print_str", py_fn!(py, print_str_py(a: String)))?; m.add(py, "sum_as_str", py_fn!(py, sum_as_str_py(a: i64, b:i64)))?; Ok(()) });

注意:py_module_initializer方法的引數的中rust2py一定要與模組的名稱一致,這個不是隨便寫的字串名稱,比如PyInit_rust2py就表示將來在python中呼叫的模組名稱是rust2py

編譯並複製到python的模組

cargo build 
cp target/debug/librust2py.so /opt/app/anaconda3/lib/python3.8/site-packages/rust2py.so

注意:複製到python模組的so沒有lib字首

python呼叫模組

ai@aisty:/opt/app/anaconda3/lib/python3.8/site-packages$ python3.8
Python 3.8.5 (default, Sep  4 2020, 07:30:14) 
[GCC 7.3.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import rust2py
>>> rust2py.sum_as_str(2,5)
'7'
>>> rust2py.print_str("from rust")
'from rust'
>>> 

更多資料型別方法請參考

http://dgrunwald.github.io/rust-cpython/doc/cpython/