Skip to content

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

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:

42

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

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:

1235

Forget 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 failed
def 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 manager

This 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/10

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

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^4

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

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 set
NOT_SET_ANYWHERE is not set

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

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_double
from 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.0000000000000004
5.0
True False
  • platform_map[...]() picks the library’s file name for the system you build on: libm.so.6 on Linux, libm.dylib on macOS.
  • OwnedDLHandle(LIBM) opens the library and closes it again when lib is no longer used.
  • get_function[c_double]("cbrt") finds a function by name and gives you something you can call. As with external_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.

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):

Terminal window
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:

Terminal window
mojo main.mojo

Output:

5
7.5
5

The 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 directory

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

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 M

C works with characters as numbers, so toupper gets 109 (m) and returns 77, which is M.

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_double
from 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.0

pow 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.ffi has everything: C type names like c_int, c_double and c_size_t, external_call and OwnedDLHandle.
  • 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 with String(unsafe_from_utf8_ptr=...).
  • Use num_fixed_args for C functions with ..., Pointer(to=x) for results C writes back, and Optional[Pointer[...]] for returns that can be null.
  • OwnedDLHandle("lib.so") loads a library while the program runs; get_function finds 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

1. What goes inside the square brackets of external_call[...]?
2. How do you pass a Mojo String to a C function that takes const char*?
3. A C function returns a pointer that may be null. How should you declare the return type?
4. You call C's sqrt with a c_int instead of a c_double. What happens?

  • 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 and CStringSpan.
  • mojo build: the build command’s options, including -Xlinker.
  • GCC link options: what -shared, -L and -l mean.