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。

相关推荐
DongLi011 天前
rustlings 学习笔记 -- exercises/06_move_semantics
rust
ssshooter1 天前
Tauri 踩坑 appLink 修改后闪退
前端·ios·rust
布列瑟农的星空1 天前
前端都能看懂的rust入门教程(二)——函数和闭包
前端·后端·rust
RuoZoe2 天前
重塑WPF辉煌?基于DirectX 12的现代.NET UI框架Jalium
c语言
蚂蚁背大象2 天前
Rust 所有权系统是为了解决什么问题
后端·rust
布列瑟农的星空2 天前
前端都能看懂的rust入门教程(五)—— 所有权
rust
Java水解3 天前
Rust嵌入式开发实战——从ARM裸机编程到RTOS应用
后端·rust
Pomelo_刘金3 天前
Rust:所有权系统
rust
Ranger09293 天前
鸿蒙开发新范式:Gpui
rust·harmonyos
祈安_5 天前
C语言内存函数
c语言·后端