Rust :与C交互

rust调用C端的库函数,有很多方法。今天介绍通过cc库,通过build生成脚本的方式,实现rust调用c端库函数。

1、相关准备:

在ffi目录下,创建了c_part和rust_ffi文件夹。 c_part下放了ctools.c文件,里面有一些库函数,需要让rust调用。当然,ctools.c也可以放在其它地方,只需要后面的地址一致即可以。

2、cargo toml部分
这里需要注意:

bash 复制代码
build="build.rs"
libc ="0.2"
cc ="0.2"

有一些依赖和说明。

3、ctools.c

bash 复制代码
// ctools.c 代码
int add(int i,int j){
    return i+j;
}
int two_times(int input){
    return input*2;
}
int three_times(int input){
    return input*3;
}

4、build.rs文件

bash 复制代码
extern crate cc;

fn main(){
    cc::Build::new().file("../c_part/ctools.c").compile("libctools.a");

}

需要注意的是,file中ctool.c文件地址一定要准确,否则会有如下报错信息(但没有明示说路径不对,找不到文件之类)。报错可能如下(下面标红处路径是故意写错路径的情况):
5、rust端:main.rs

bash 复制代码
extern crate libc;
use libc::c_int;
extern "C" {
    fn add(i:c_int,j:c_int)  ->c_int;
    fn two_times(input:c_int) ->c_int;
    fn three_times(input:c_int) ->c_int; 
}

fn main() {
    println!("Hi guys, welcome rust ffi !");
    let twotimes_value:i32 = unsafe{two_times(-8)};
    println!("twotimes_value  : {:?}",twotimes_value);
    let add_value = unsafe{add(2,3)};
    println!("add_value       : {:?}",add_value);
    let threetimes_value = unsafe{three_times(3)};
    println!("threetimes_value: {:?}",threetimes_value);
}

引入libc库,以及c_int类型。

6、cargo build

如果配置正确,在rust_ffi目录下(build.rs所在目录),运行cargo build:可见build成功。

7、cargo run

相关结果表明,rust端已经正确调用了ctools.c中几个库函数。

注意的是,因为已经是ffi调用,均需要加unsafe。

相关推荐
柯南46684 小时前
【AI开发之Rust】第 18 课:SQLite 持久化与本地缓存 —— 给 store 填上真实现
rust·编程语言
柯南46684 小时前
【AI开发之Rust】第 17 课:项目总览与核心架构 —— AI 助手 Rust 核心从 0 到 1
rust·编程语言
柯南46684 小时前
【AI开发之Rust】第 16 课:FFI 手写绑定与内存布局 —— 把 Rust 交给别的语言
rust·编程语言
达子6664 小时前
RUST 图解 第 2 章:写小游戏
rust
Amos_Web4 小时前
Rspack 源码解析(十四):Resolver 与 NormalModuleFactory
前端·rust·源码
Kapaseker4 小时前
秒懂 Rust 的 7 个核心概念
rust
RobinDevNotes4 小时前
用 godot-rust 给 Godot 写 Rust 扩展
rust·游戏开发
十万公里通票4 小时前
Rust 高级特性秀场:spawn 闭包的类型约束
rust
WAKU4 小时前
C#: 爸爸再爱我一回! 写在微软使用Rust重写GitHub Copilot之后的碎碎念
microsoft·rust·微软·c#·编程语言
晓蛋6 天前
c语言指的是什么意思
c语言·编译器·编程开发·集成开发环境·程序实例