Due to the vast functionality that exists in C's code, it can sometimes be useful to delegate processing to a C routine, instead of writing everything in Rust.
You can call all functions from the C standard library by using the libc
crate, which must be obtained through Cargo. To do this, simply add the following to your Rust code:
#![feature(libc)] extern crate libc;
To import C functions and types, you can sum them up like this:
use libc::{c_void, size_t, malloc, free};
Alternatively, you can use a *
wildcard, such as use libc::*;
, to make them all available.
To work with C (or another language) from Rust, you will have to use the FFI, which has its utilities in the std::ffi
module.
Here is a simple example to call C for printing out a Rust string with the puts
function in C:
// code from Chapter 9/code/calling_libc.rs: #![feature(libc)] extern crate libc; use libc::puts; use std::ffi::CString; fn main() { let sentence = "Merlin is the greatest magician!"; let to_print...