O'Reilly logo

Mastering Rust by Vesa Kaihlavirta

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

Calling C code from Rust

Linking Rust code into C code requires the following two things at the minimum:

  • The foreign function declared inside an extern block
  • std::os::raw contains types that map directly to primitive C types and other functionalities that can be used from Rust

Let's look at a simple example to see how these things come together. Here's a piece of C code that measures the length of a C string. As you know, C strings are pointers to the first character of a contiguous block of memory whose end is signified by a zero byte:

/* count-string.c */ unsigned int count_string(char *str) {   unsigned int c;   for (c=0; *str != '\0'; c++, *str++);   return c; } 

The primitive types are in std::os::raw, with names close to their C counterparts. ...

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