当前位置:网站首页>Rust FFI programming - libc crate
Rust FFI programming - libc crate
2022-06-28 06:40:00 【51CTO】
Previous warning : If the Unix Environment system programming without basic knowledge , This article will be in the clouds .
We're doing it Rust When developing and compiling , Often in dependency list , notice libc This crate The figure of . We don't usually rely directly on this crate, But dependence ( The dependence of ……) You might use this crate. in general , It is Rust One of the most basic and bottom layers in ecology crate 了 .
libc What is it?
libc It is the original system library of each platform FFI binding . Its code address is at :https://github.com/rust-lang/libc. You can see , This is a Rust A library officially maintained .
libc Provided with Rust The most basic system on each supported platform C All necessary facilities for dealing with the warehouse . It exports the type of underlying platform 、 Functions and constants .
All content is placed directly in libc Under this namespace , No more modules . therefore , You can use libc::foo
Access any exported content in this library in this form .
It can work with std In combination with , It can also be in no_std Environmental use .
libc Import of
In the project Cargo.toml
Add the following configuration , You can import libc 了 .
libc Content classification of
libc The underlying layer will be exported C These things from the library :
- C type , such as typedefs, Primitive types , enumeration , Structure, etc
- C Constant , For example, use
#define
Those constants defined by the instruction - C Static variables
- C function ( Export by function signature defined in their header file )
- C macro , stay Rust Will be implemented as
#[inline]
function
in addition ,libc All exported in C struct It's all done Copy
and Clone
trait.
ok , be familiar with C Classmate , It should have been known ,C The interface of , It's just that . Now? libc It's all led out .
What is the result of the export ? Open it directly https://docs.rs/libc/0.2.69/libc/index.html see , There will be a long web page in front of you . Yes
- Structs Corresponding C Symbols in
- Enums Corresponding C Enumeration in
- Constants Corresponding C Constant in
- Functions Corresponding C Function interface in
- Type Definitions Corresponding C Medium typedef Defined symbols
These symbols , Probably 99% No one can guarantee that they used it 20% above , Even many students who focus on upper level development have never seen these names .
This is a great set of things , It is the essence of the system that has been accumulated over the years in the history of computer engineering. . The essence of this system is called. Unix Environment programming . This system 《UNIX Environment advanced programming ( The first 3 edition )》 There is an authoritative explanation in this book .
The essence of this set of things lies in its essence. , It's not just a simple list of symbols , It contains a set of exquisite mechanism to drive . Yes , It's a set of mechanisms . This mechanism is composed of several different parts , There is a very clear distinction between these parts (Unix Of KISS principle ), But in terms of design concept , It's the same smell again . therefore , This set of things , We call it engineering 、 technology 、 philosophy 、 Even art .
This set of things is modern IT Industry , The cornerstone of the Internet .
libc The boundaries of
be familiar with linux The students of system development all know ,linux The system itself has a libc library , It is the basic library of almost all applications . Basically linux Next C All code written in language must be linked to this library to run .
and Rust Of libc crate, Not exactly equivalent to C Of libc Encapsulation of Libraries . The differences are as follows :
- Linux ( And others unix-like platform ) Next , Exported is libc, libm, librt, libdl, libutil and libpthread Symbols of these libraries .
- OSX Next , Exported is libsystem_c, libsystem_m, libsystem_pthread, libsystem_malloc and libdyld Symbols of these libraries .
- Windows Next , Exported is VS CRT(VS C RunTime VS C Runtime library ) Symbols in . But these symbols , Symbols compared to the first two platforms , Much less in quantity . therefore , You can say that directly ,Rust libc crate stay Windows Limited functionality on the platform . stay Windows On the platform , It is recommended to use
winapi
This crate Development .
give an example : Use libc Create child process
That's amazing , Let's meet libc What does Lushan look like . below , Let's use an example —— Create a subprocess —— To show libc Usage of , As well as Rust Different thread operations in standard library .
Rust There is no facility to create child processes in the standard library , But you can create a child thread . As a comparative demonstration , Let's create a new thread :
The above code will be output :
Let's see libc How to create a subprocess :
fn main() {
unsafe {
let pid = libc::fork();
if pid > 0 {
println!("Hello, I am parent thread: {}", libc::getpid());
}
else if pid == 0 {
println!("Hello, I am child thread: {}", libc::getpid());
println!("My parent thread: {}", libc::getppid());
}
else {
println!("Fork creation failed!");
}
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
This code will have output similar to the following :
Specific process id Numbers , Every run can change .
A simple comparison of two programs , You can find :
- libc All function calls for , all must In the
unsafe
In block . Because all its calls are unsafe Of ; - std Thread operation encapsulation of , To use , image .libc Process operations for , And C Language system programming is the same , It's just another set of ideas and programming style ;
- std The thread operation of is simple , But there is also a lack of finer particle size control . and libc Operations that can be performed on a process ( And subsequent function expansion of subprocesses , Signal management in parent process, etc ), Complete control , More flexible , Powerful ;
- std Process cannot be implemented by itself fork The function of .
Example address of the above code : https://github.com/daogangtang/learn-rust/tree/master/07libctest
Which things are Rust std Can't do it libc What can be done ?
Almost everything about underlying programming ( Of course, this sentence is not rigorous ).
Just a few examples :dup2
Do you have a standard library ?openpty
Do you have a standard library ?ioctl
Do you have a standard library ?
ioctl No, , That's with the bottom floor say byebye La ( And then isolated from serious embedded development ). Of course , You can say , Then I'll take it Rust Write your own operating system . Right? , Do you use Rust Write operating system , It doesn't work std ah .
It should be said , Use libc, class Unix All system programming on the platform , Previously, only by C Work done , It can be used now Rust Here we go . On this level ,C What can be done ,Rust Can do it .
adopt libc This floor ,Rust Breaking into the field of system programming .
Probably , Some students have to explain again , It's just a library , It's no big deal .Python There are also packages for operating system base Libraries ,Python The same can be done for system development . This is not enough to prove Rust Is a system programming language ,Rust There is no difference at this point .
In fact, it only needs one sentence to answer this question : Because of me Rust The package of is zero cost ( Zero cost ) Of .
Yes, It's that simple . Zero cost abstraction gives Rust Ability of system programming .
libc And std::os::*::raw The relationship between ?
Careful students will find out , In the standard library os Under module , There's something about libc Duplication .
page https://doc.rust-lang.org/std/os/raw/index.html Contains c_char, c_double, c_float, c_int, c_long, c_longlong, c_schar, c_short, c_uchar, c_uint, c_ulong, c_ulonglong, c_ushort
.
and libc in , For these , And redefined a ( such as :https://docs.rs/libc/0.2.69/libc/type.c_char.html). Why? ?
std::os::raw These definitions in , Can be used with some simple C Code to interact , For example, there is no system call C Code . This is the time , No need to introduce it again libc The library .
Once a system call is generated or Unix Environment programming , Then we have to introduce libc Library to operate .
std Here are some more std::os::*::raw Module , These modules are now Deprecated 了 ( such as :https://doc.rust-lang.org/std/os/unix/raw/index.html). Clearly noted in the document :
in other words , These things , Go to libc Middle search , use libc To implement these functions .
summary
We should be glad ,Rust Humanized and convenient programming mode provided by standard library .
meanwhile , We should be glad again ,Rust And C Close consanguinity of , Let us Rustaceans Easy to use with little performance loss C The way and thinking of the lowest level system programming .
This little fortune ( possibility ), Not everyone can have it .
I want to master Rust And feel happy .
边栏推荐
- Trie string statistics
- fpm工具安装
- 推荐10个好用到爆的Jupyter Notebook插件,让你效率飞起
- CRC32概述以及实现和使用
- MySQL(一)——安装
- AttributeError: 'callable_iterator' object has no attribute 'next'
- 报错--解决core-js/modules/es.error.cause.js报错
- 4~20ma input /0~5v output i/v conversion circuit
- EasyUI reset multi condition query
- 微信小程序分页功能,下拉刷新功能,直接干货拿来就用
猜你喜欢
随机推荐
ThreadLocal
4~20mA输入/0~5V输出的I/V转换电路
FPGA - 7系列 FPGA SelectIO -08- 高级逻辑资源之OSERDESE2
MySQL (I) - Installation
Yygh-7-user management
Eyebeam advanced settings
freeswitch使用mod_shout模块播放mp3
CAD secondary development +nettopologysuite+pgis reference multi version DLL
Differences between overloads, rewrites, abstract classes and interfaces
链表(一)——移除链表元素
Linked list (II) - Design linked list
Integer promotion and size side byte order
Alibaba cloud SMS service (Complete Guide), SMS sending function implementation.
FPGA - 7系列 FPGA SelectIO -09- 高级逻辑资源之IO_FIFO
声网 VQA:将实时互动中未知的视频画质用户主观体验变可知
ImportError: cannot import name 'ensure_dir_exists'的可解决办法
Build your jmeter+jenkins+ant
MySQL common functions
OpenGL API learning (2008) client server client server
pytorch RNN 学习笔记