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。

相关推荐
The️3 分钟前
Linux驱动开发之Read_Write函数
linux·运维·服务器·驱动开发·ubuntu·交互
shimly1234564 分钟前
(done) 速通 rustlings(24) 错误处理2 --- 涉及Traits
rust
shimly12345634 分钟前
(done) 速通 rustlings(23) 特性 Traits
rust
Sunsets_Red1 小时前
P8277 [USACO22OPEN] Up Down Subsequence P 题解
c语言·c++·算法·c#·学习方法·洛谷·信息学竞赛
小刘爱玩单片机1 小时前
【stm32简单外设篇】- 测速传感器模块(光电)
c语言·stm32·单片机·嵌入式硬件
hateregiste1 小时前
嵌入式软件开发中常见知识点问答集锦!
c语言·单片机·嵌入式软件
极客小张1 小时前
基于STM32的智能水质监测与远程预警系统设计与实现
c语言·python·stm32·单片机·嵌入式硬件·物联网
Once_day1 小时前
GCC编译(7)链接脚本LinkerScripts
c语言·c++·编译和链接·程序员自我修养
shimly1234561 小时前
(done) 速通 rustlings(17) 哈希表
rust
小刘爱玩单片机2 小时前
【stm32简单外设篇】- KY-025 干簧管(磁控)模块
c语言·stm32·单片机·嵌入式硬件