Mojo Calling C
A huge amount of useful code is written in C: the C standard library, math libraries, databases like SQLite, compression, hardware drivers. Mojo can call C functions directly, with no wrapper code and no extra layer in between. This page starts with functions from the C standard library (libc), then shows how to load a shared library and how to call a small C library you compile yourself.
Everything here comes from the std.ffi module. FFI stands for foreign function interface: the way one language calls functions written in another. Every example was checked with Mojo 1.2 on Linux with gcc 13.
C types in Mojo
Section titled “C types in Mojo”C’s number types don’t have fixed sizes everywhere: an int is usually 32 bits, a long is 64 bits on Linux and macOS but 32 on Windows. So std.ffi gives you names that always match the C type on the platform you build for:
| C type | std.ffi name |
Mojo type it is on Linux and macOS |
|---|---|---|
int |
c_int |
Int32 |
long |
c_long |
Int64 |
double |
c_double |
Float64 |
float |
c_float |
Float32 |
char |
c_char |
Int8 |
size_t |
c_size_t |
UInt |
Use these names whenever you talk to C. The Mojo manual’s C FFI page has the full table.
Calling a libc function
Section titled “Calling a libc function”C’s abs() takes an int and returns its absolute value. Its declaration in C is int abs(int n);. Here’s how you call it:
from std.ffi import external_call, c_int
def main(): # int abs(int n); var n = external_call["abs", c_int](c_int(-42)) print(n)Output:
42external_call["abs", c_int](...) reads as: call the C function named abs, which returns a c_int, with these arguments. Inside the square brackets go the name and the return type; inside the round brackets go the arguments. You don’t declare the argument types: Mojo takes them from the values you pass. That’s why the argument is written c_int(-42) and not just -42. It makes sure C gets exactly the 32-bit int it expects.
libc is always there, so Mojo finds abs without you naming a library.
Passing strings
Section titled “Passing strings”C strings are bytes ending in a zero byte (char*). Mojo strings are different, so you convert with as_c_string_span(). Here’s C’s atoi(), which reads a number from text (int atoi(const char *text);):
from std.ffi import external_call, c_int
def main(): var text: String = "1234" var n = external_call["atoi", c_int](text.as_c_string_span()) print(n + 1)Output:
1235Forget as_c_string_span() and Mojo stops you at compile time, with a message that names the fix:
from std.ffi import external_call, c_int
def main(): var text: String = "1234" var n = external_call["atoi", c_int](text) print(n)hello.mojo:3:5: error: function instantiation faileddef main(): ^hello.mojo:5:41: note: call expansion failed var n = external_call["atoi", c_int](text) ^Mojo/stdlib/std/ffi/__init__.mojo:1204:9: note: constraint failed: Passing a `String` to `external_call` is never correct. Instead, first call `as_c_string_span()` to pass a C-FFI compatible `CStringSpan` type (synonymous with C's `const char*`). Example `external_call["foo", NoneType]("some string".as_c_string_span())mojo: error: failed to run the pass managerThis is one of the very few mistakes the compiler catches for you here.
To go the other way, from a C string to a Mojo String, use String(unsafe_from_utf8_ptr=...). You’ll see it in the next two examples.
Functions with a variable number of arguments
Section titled “Functions with a variable number of arguments”Some C functions, like printf and snprintf, take any number of arguments after the fixed ones (the ... in C). For those, tell Mojo how many arguments are fixed with num_fixed_args:
from std.ffi import external_call, c_char, c_int, c_size_t
def main(): # int snprintf(char *buf, size_t size, const char *format, ...); var buf = Array[c_char, 64](uninitialized=True) var written = external_call["snprintf", c_int, num_fixed_args=3]( buf.unsafe_ptr(), c_size_t(64), "score: %d/%d".as_c_string_span(), c_int(7), c_int(10), ) print(t"wrote {written}: {String(unsafe_from_utf8_ptr=buf.unsafe_ptr())}")Output:
wrote 11: score: 7/10Array[c_char, 64] is a fixed block of 64 bytes owned by Mojo, and buf.unsafe_ptr() hands C a pointer to it. snprintf writes the text into it, and String(unsafe_from_utf8_ptr=...) copies the C string back into a Mojo String. Without num_fixed_args, the call may happen to work on one kind of computer and break on another, because some systems pass the extra arguments differently.
Getting results back through a pointer
Section titled “Getting results back through a pointer”Many C functions return extra results by writing to a pointer you give them. C’s frexp() splits a number into a fraction and a power of two: it returns the fraction and writes the exponent through int *exp:
from std.ffi import external_call, c_double, c_int
def main(): # double frexp(double x, int *exp); var exponent: c_int = 0 var fraction = external_call["frexp", c_double]( c_double(12.0), Pointer(to=exponent) ) print(t"12.0 = {fraction} * 2^{exponent}")Output:
12.0 = 0.75 * 2^4Pointer(to=exponent) is a pointer to the Mojo variable, and C fills it in. The variable must be a var you own, so C is allowed to change it. Mojo Pointers explains Pointer itself.
When C returns “nothing”
Section titled “When C returns “nothing””C uses a null pointer to say “nothing here” or “it failed”. A Mojo Pointer can’t be null, so for C functions that might return null, wrap the return type in Optional. getenv() returns the value of an environment variable, or null when it isn’t set:
from std.ffi import external_call, c_char
def main(): var names: List[String] = ["HOME", "NOT_SET_ANYWHERE"] for ref name in names: var found = external_call[ "getenv", Optional[Pointer[c_char, MutUntrackedOrigin]] ](name.as_c_string_span()) if found: print(name, "is set") else: print(name, "is not set")Output:
HOME is setNOT_SET_ANYWHERE is not setMutUntrackedOrigin says the memory belongs to C, not to any Mojo variable. If a value is set, String(unsafe_from_utf8_ptr=found.value()) would copy it into a Mojo String. Declaring a plain Pointer instead of Optional would also compile, but then a null comes back looking like a real pointer, and using it crashes the program. The for ref name matters too: as_c_string_span() may need to add the zero byte, so it needs a string it can change. Mojo Optional covers Optional.
Loading a shared library
Section titled “Loading a shared library”external_call is for functions that are already part of your program, like libc. For other libraries, load them while the program runs with OwnedDLHandle. Here’s the C math library, libm:
from std.ffi import OwnedDLHandle, c_doublefrom std.sys.info import platform_map
comptime LIBM = platform_map["libm", linux="libm.so.6", macos="libm.dylib"]()
def main() raises: var lib = OwnedDLHandle(LIBM) var cbrt = lib.get_function[c_double]("cbrt") print(cbrt(c_double(27.0))) var hypot = lib.get_function[c_double]("hypot") print(hypot(c_double(3.0), c_double(4.0))) print(lib.check_symbol("exp10"), lib.check_symbol("no_such_function"))Output:
3.00000000000000045.0True Falseplatform_map[...]()picks the library’s file name for the system you build on:libm.so.6on Linux,libm.dylibon macOS.OwnedDLHandle(LIBM)opens the library and closes it again whenlibis no longer used.get_function[c_double]("cbrt")finds a function by name and gives you something you can call. As withexternal_call, you only give the return type.check_symbol("name")tells you whether a function exists, before you try to use it.
cbrt(27.0) printing 3.0000000000000004 isn’t a Mojo bug: that’s the closest a double gets, and C gives the same answer.
Calling your own C code
Section titled “Calling your own C code”Now a C file of your own. Save this as mytools.c:
#include <stddef.h>
int add(int a, int b) { return a + b;}
double average(const double *values, size_t count) { if (count == 0) { return 0.0; } double total = 0.0; for (size_t i = 0; i < count; i++) { total += values[i]; } return total / count;}
int count_vowels(const char *text) { int count = 0; for (const char *p = text; *p != '\0'; p++) { switch (*p) { case 'a': case 'e': case 'i': case 'o': case 'u': case 'A': case 'E': case 'I': case 'O': case 'U': count++; } } return count;}Compile it into a shared library with gcc (on macOS, use clang and name it libmytools.dylib):
gcc -shared -fPIC -o libmytools.so mytools.c-shared makes a library instead of a program, and -fPIC is a setting shared libraries need on Linux. Now load it from Mojo:
from std.ffi import OwnedDLHandle, c_int, c_double, c_size_t
def main(): try: var lib = OwnedDLHandle("./libmytools.so")
var add = lib.get_function[c_int]("add") print(add(c_int(2), c_int(3)))
var scores: List[c_double] = [7.5, 9.0, 6.0] var average = lib.get_function[c_double]("average") print(average(scores.unsafe_ptr(), c_size_t(len(scores))))
var word: String = "Mojo interop" var count_vowels = lib.get_function[c_int]("count_vowels") print(count_vowels(word.as_c_string_span())) except e: print("Couldn't use the library:", e)Run it in the folder with libmytools.so:
mojo main.mojoOutput:
57.55The list is passed the way C likes arrays: a pointer to the first item (scores.unsafe_ptr()) plus the number of items. A Mojo List keeps its items side by side in memory, just like a C array, so nothing is copied. Get the pointer right before the call: adding items to a list can move its memory.
Run the program from another folder and "./libmytools.so" isn’t found. The try turns that into a clear message:
Couldn't use the library: dlopen failed: ./libmytools.so: cannot open shared object file: No such file or directoryWrong types give wrong answers
Section titled “Wrong types give wrong answers”Here’s what “you are the type checker” means in practice. C’s sqrt takes a double. Pass a c_int instead, and nothing complains:
from std.ffi import OwnedDLHandle, c_double, c_intfrom std.sys.info import platform_map
comptime LIBM = platform_map["libm", linux="libm.so.6", macos="libm.dylib"]()
def main() raises: var lib = OwnedDLHandle(LIBM) var sqrt = lib.get_function[c_double]("sqrt") print(sqrt(c_double(16.0))) print(sqrt(c_int(16)))On our machine this printed 4.0 and then 2.0. The second call is simply wrong: C looked for a double where Mojo never put one and used whatever happened to be there. Yours may print a different wrong number. The program doesn’t crash, which is exactly what makes these mistakes hard to find.
Practice
Section titled “Practice”1. Shout with toupper
Section titled “1. Shout with toupper”C’s toupper() (int toupper(int c);) turns one lowercase letter into uppercase. Use it to print the letter M from the letter m.
Hint: ord("m") gives the letter’s number and chr(...) turns a number back into a letter. Pass c_int(ord("m")), and convert the result with chr(Int(result)).
Show solution
from std.ffi import external_call, c_int
def main(): var result = external_call["toupper", c_int](c_int(ord("m"))) print(result, chr(Int(result)))Output:
77 MC works with characters as numbers, so toupper gets 109 (m) and returns 77, which is M.
2. Powers from libm
Section titled “2. Powers from libm”Load libm with OwnedDLHandle and call pow (double pow(double x, double y);) to print 2 to the power of 10.
Hint: copy the platform_map line from the libm example, then lib.get_function[c_double]("pow"). Both arguments must be c_double.
Show solution
from std.ffi import OwnedDLHandle, c_doublefrom std.sys.info import platform_map
comptime LIBM = platform_map["libm", linux="libm.so.6", macos="libm.dylib"]()
def main() raises: var lib = OwnedDLHandle(LIBM) var pow = lib.get_function[c_double]("pow") print(pow(c_double(2.0), c_double(10.0)))Output:
1024.0pow returns a double, so the result prints as 1024.0. Writing c_double(2.0) rather than 2 makes sure C receives the type it declared.
std.ffihas everything: C type names likec_int,c_doubleandc_size_t,external_callandOwnedDLHandle.external_call["name", ReturnType](args...)calls a C function that’s already in your program, like libc.- Strings go to C with
as_c_string_span()and come back withString(unsafe_from_utf8_ptr=...). - Use
num_fixed_argsfor C functions with...,Pointer(to=x)for results C writes back, andOptional[Pointer[...]]for returns that can be null. OwnedDLHandle("lib.so")loads a library while the program runs;get_functionfinds functions in it.- Nothing checks your C declarations: wrong types give wrong answers, not errors.
Next up: Mojo Exporting to C, letting C code call functions you wrote in Mojo.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Using Mojo’s C FFI: the manual’s full guide, with structs, memory ownership and a list of what can go wrong.
- std.ffi module: reference for
external_call,OwnedDLHandle, the C type names andCStringSpan. - mojo build: the build command’s options, including
-Xlinker. - GCC link options: what
-shared,-Land-lmean.