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。

相关推荐
AlexMercer101235 分钟前
【操作系统】操作系统期末考试 简答题 焚决
c语言·经验分享·笔记·操作系统
学嵌入式的六子1 小时前
如何使用VScode开发STM32【喂饭级教程】-全过程讲解
c语言·ide·vscode·stm32·单片机·嵌入式硬件
墨辰JC1 小时前
C语言可变参数讲解:stdarg.h应用
c语言·开发语言·蓝桥杯·内存·蓝桥杯嵌入式
C语言小火车1 小时前
C++右值引用与转移语义详解
c语言·开发语言
程芯带你刷C语言简单算法题2 小时前
Day43~实现一个算法求一个数字的树根
c语言·开发语言·算法·c
buyicn2 小时前
C语言中各种变量的内存分布
c语言
leo__5204 小时前
基于C语言的FOC算法核心模块实现
c语言·算法·机器学习
LegendNoTitle4 小时前
Windows和Linux下Rust-init、Cargo下载慢的解决
开发语言·windows·rust
培林将军4 小时前
C语言指针
c语言·开发语言·算法
古城小栈5 小时前
rust 借用,三巨头之一
开发语言·rust