rust使用动态连接库实现两个数的求和

发布时间 2023-12-02 18:56:28作者: NAVYSUMMER

1.1 创建库项目

cargo new --lib plugin
cd plugin

1.2 编写加法功能函数

vim src/lib.rs
#[no_mangle]
pub extern fn add(left: usize, right: usize) -> usize {
    left + right
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn it_works() {
        let result = add(2, 2);
        assert_eq!(result, 4);
    }
}

1.3 修改配置

vim Cargo.toml
[package]
name = "plugin"
version = "0.1.0"
edition = "2023"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[lib]
crate-type = ["cdylib"]

[dependencies]

1.4 编译成库

cargo build --release

2. 1 创建测试项目

cargo new test-plugin
cd test-plugin

  

2.2 编写配置文件

vim Cargo.toml
[package]
name = "test-plugin"
version = "0.1.0"
edition = "2023"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
libloading = "0.6"

2.3 编写测试代码

vim src/main.rs
use std::path::Path;
use libloading::{Library, Symbol};

fn main() {
    // 指定动态连接库路径
    let library_path = Path::new("/home/navy/Desktop/test/plugin/target/release/libplugin.so");

    // 加载动态连接库
    let lib = Library::new(library_path).expect("Failed to load library");

    // 获取动态连接库中的add函数
    unsafe {
        let add: Symbol<unsafe extern "C" fn(usize, usize) -> usize> =
            lib.get(b"add").expect("Failed to get symbol");

        // 调用add函数
        let a = 1;
        let b = 2;
        let result = add(a, b);
        println!("{} + {} = {}", a,b,result);
    }
}

2.4 运行测试

cargo run

3 项目目录结构