Chapter 23. Foreign Functions
Cyberspace. Unthinkable complexity. Lines of light ranged in the non-space of the mind, clusters and constellations of data. Like city lights, receding . . .
William Gibson, Neuromancer
Tragically, not every program in the world is written in Rust. There are many critical libraries and interfaces implemented in other languages that we would like to be able to use in our Rust programs. Rustâs foreign function interface (FFI) lets Rust code call functions written in C, and in some cases C++. Since most operating systems offer C interfaces, Rustâs foreign function interface allows immediate access to all sorts of low-level facilities.
In this chapter, weâll write a program that links with libgit2
, a C library for working with the Git version control system. First, weâll show what itâs like to use C functions directly from Rust, using the unsafe features demonstrated in the previous chapter. Then, weâll show how to construct a safe interface to libgit2
, taking inspiration from the open source git2-rs
crate, which does exactly that.
Weâll assume that youâre familiar with C and the mechanics of compiling and linking C programs. Working with C++ is similar. Weâll also assume that youâre somewhat familiar with the Git version control system.
There do exist Rust crates for communicating with many other languages, including Python, JavaScript, Lua, and Java. We donât have room to cover them here, but ultimately, all these interfaces ...
Get Programming Rust, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.