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。

相关推荐
whoarethenext19 分钟前
加密认证库openssl初始附带c/c++的使用源码
c语言·网络·c++·openssl
User_芊芊君子23 分钟前
【C语言经典算法实战】:从“移动距离”问题看矩阵坐标计算
c语言·算法·矩阵
阿让啊12 小时前
单片机获取真实时间的实现方法
c语言·开发语言·arm开发·stm32·单片机·嵌入式硬件
FightingLod13 小时前
STM32版I²C相亲指南(软件硬件双修版)
c语言·stm32·单片机
用户0996918801815 小时前
Rust JSON 数据处理:take 与 clone 的权衡
rust
三体世界15 小时前
Linux 管道理解
linux·c语言·开发语言·c++·git·vscode·visual studio
wuxiguala16 小时前
【C/S通信仿真】
c语言·开发语言
2301_8170316516 小时前
C语言-- 深入理解指针(3)
c语言·开发语言
海绵宝宝的月光宝盒16 小时前
[STM32] 4-1 UART与串口通信
c语言·开发语言·笔记·stm32·单片机
bruce5411017 小时前
Rust学习之实现命令行小工具minigrep(二)
rust