O'Reilly logo

Rust Essentials by Ivo Balbaert

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Interfacing with C

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required