Mojo Exporting to C
Mojo Calling C went from Mojo to C. This page goes the other way: C code calling functions you wrote in Mojo. There are two ways that happens. A C function can call back into Mojo while your Mojo program runs (a callback), or you can build your Mojo code into a shared library that a C program links against, just like a library written in C. Both work in Mojo 1.2, and both rest on one small piece of syntax: abi("C").
Every example was checked with Mojo 1.2 on Linux with gcc 13. The C side is plain C; you only need a C compiler for the second half of the page.
Speaking C’s language: abi("C")
Section titled “Speaking C’s language: abi("C")”Mojo and C don’t call functions in quite the same way. They can disagree on where arguments go and how results come back. That agreement is called the calling convention, part of the ABI (application binary interface). Adding abi("C") to a Mojo function compiles it with C’s convention, so C code can call it:
def add(a: Int32, b: Int32) abi("C") -> Int32: return a + b
def main(): var fp: def(Int32, Int32) thin abi("C") -> Int32 = add print(fp(1, 2)) print(add(3, 4))Output:
37abi("C") goes after the arguments and before ->. You can still call add from Mojo as usual. fp holds a pointer to the function, with the type def(Int32, Int32) thin abi("C") -> Int32. That’s the Mojo spelling of a C function pointer. thin means it’s a plain function with no captured variables, which is the only kind C understands. The reference page on function declarations describes abi and thin.
A normal Mojo function doesn’t fit that type:
def add(a: Int32, b: Int32) -> Int32: return a + b
def main(): var fp: def(Int32, Int32) thin abi("C") -> Int32 = add print(fp(1, 2))hello.mojo:5:56: error: cannot implicitly convert 'def add(a: Int32, b: Int32) thin -> Int32' value to 'def(Int32, Int32) abi("C") thin -> Int32' in 'var' initializer var fp: def(Int32, Int32) thin abi("C") -> Int32 = add ^~~mojo: error: failed to parse the provided Mojo source moduleabi("C") functions can’t raise
Section titled “abi("C") functions can’t raise”C has no exceptions, so a C-convention function isn’t allowed to raise an error:
from std.ffi import c_int
def parse(a: c_int) abi("C") raises -> c_int: if a < 0: raise Error("negative") return a
def main(): print(parse(5))hello.mojo:3:30: error: 'abi("C")' function may not be marked 'raises'; remove 'raises' or use 'abi("Mojo")'def parse(a: c_int) abi("C") raises -> c_int: ^mojo: error: failed to parse the provided Mojo source moduleDo what C functions do instead: catch the error inside the function and return a status code, like 0 for success and -1 for failure. You’ll see that pattern below.
Callbacks: C calling your Mojo function
Section titled “Callbacks: C calling your Mojo function”C’s qsort() sorts any array, but it doesn’t know how to compare your items. You give it a comparison function, and it calls that function every time it needs to compare two items. Here’s a descending sort with a comparison written in Mojo:
from std.ffi import external_call, c_int, c_size_tfrom std.sys import size_of
# int compare(const void *a, const void *b);def descending( a: OpaquePointer[mut=False, _], b: OpaquePointer[mut=False, _],) abi("C") -> c_int: var x = a.unsafe_bitcast[c_int]()[] var y = b.unsafe_bitcast[c_int]()[] if x > y: return c_int(-1) return c_int(x < y)
def main(): var numbers: List[c_int] = [5, 2, 9, 1, 5, 6] external_call["qsort", NoneType]( numbers.unsafe_ptr(), c_size_t(len(numbers)), c_size_t(size_of[c_int]()), descending, ) print(numbers)Output:
[9, 6, 5, 5, 2, 1]What’s going on:
qsortgets four things: a pointer to the list’s items, how many there are, how big each one is in bytes (size_of[c_int]()is 4), and the comparison function.- C calls
descendingwith twovoid*pointers, which Mojo callsOpaquePointer: pointers that don’t say what they point to.unsafe_bitcast[c_int]()tells Mojo to treat them as pointers toc_int, and[]reads the value. - The function returns a negative number when
ashould come first, a positive number whenbshould, and0when they’re equal. Returning-1whenx > yputs bigger numbers first.
A Mojo library for C programs
Section titled “A Mojo library for C programs”Now the bigger step: building Mojo code into a shared library (.so on Linux) that any C program can use. Mark each function C should see with @export("name") and abi("C"). Save this as mylib.mojo:
from std.ffi import c_int, c_double, c_size_tfrom std.runtime import initialize_runtime
@export("mylib_init")def init() abi("C"): initialize_runtime()
@export("mylib_add")def add(a: c_int, b: c_int) abi("C") -> c_int: return a + b
@export("mylib_sum")def sum_values( values: Pointer[c_double, ImmUntrackedOrigin], count: c_size_t) abi("C") -> c_double: var total: c_double = 0 for i in range(Int(count)): total += values[unsafe_offset=i] return total
@export("mylib_hello")def hello() abi("C"): print("Hello from Mojo!")@export("mylib_add")makes the function visible to other programs under the namemylib_add. The name must be a valid C name. Starting every name with your library’s name keeps it from clashing with other libraries.Pointer[c_double, ImmUntrackedOrigin]is how a Cconst double *arrives: a read-only pointer to memory Mojo doesn’t own.values[unsafe_offset=i]reads itemi. Nothing checks thatcountis right; that’s up to the C caller.mylib_initcallsinitialize_runtime(). More on that in a moment.
Build it with --emit shared-lib:
mojo build mylib.mojo --emit shared-lib -o libmylib.soThe C program declares the functions it expects (normally you’d put these lines in a header file, mylib.h) and calls them like any other C functions. Save it as main.c:
#include <stdio.h>#include <stddef.h>
/* The functions from libmylib.so, written in Mojo. */void mylib_init(void);int mylib_add(int a, int b);double mylib_sum(const double *values, size_t count);void mylib_hello(void);
int main(void) { mylib_init();
double prices[] = {1.5, 2.25, 4.0}; printf("2 + 3 = %d\n", mylib_add(2, 3)); printf("sum = %.2f\n", mylib_sum(prices, 3)); fflush(stdout);
mylib_hello(); return 0;}Compile it, link it against your library, and run it:
cc main.c -o main -L. -lmylib -Wl,-rpath,'$ORIGIN'./mainOutput:
2 + 3 = 5sum = 7.75Hello from Mojo!The C compiler flags, one by one: -L. says “look for libraries in this folder”, -lmylib links libmylib.so (the lib and .so are added for you), and -Wl,-rpath,'$ORIGIN' tells the finished program to look for the library next to itself when it starts.
The fflush(stdout) is there because C and Mojo each keep their own output buffer. In the terminal you won’t notice, but when we sent the output to a file without it, Hello from Mojo! came out first.
Starting the Mojo runtime
Section titled “Starting the Mojo runtime”When a Mojo program starts from its own main(), Mojo sets up its runtime first (for example, the thread pool that parallel code uses). When a C program owns main(), that never happens. The compilation guide says exported functions that use such features crash with a segmentation fault unless you call initialize_runtime() first.
The functions on this page don’t need it (we checked: they work without mylib_init), but it’s cheap and safe to call more than once. Two easy patterns:
- Export an init function, like
mylib_initabove, and tell users of your library to call it first. - Call
initialize_runtime()at the start of every exported function, so callers can’t forget.
Strings and errors across the border
Section titled “Strings and errors across the border”Here’s a function that takes a C string, may fail, and returns its result through a pointer, the way many C libraries do. Save it as textlib.mojo:
from std.ffi import c_char, c_int, c_long
@export("textlib_parse_int")def parse_int( text: Pointer[c_char, ImmUntrackedOrigin], result: Pointer[c_long, MutUntrackedOrigin],) abi("C") -> c_int: try: var s = String(unsafe_from_utf8_ptr=text) result[] = c_long(Int(s)) return 0 except: return -1String(unsafe_from_utf8_ptr=text) copies the C string into a Mojo String. Int(s) can raise, but the try catches it, so the function never raises and is allowed to be abi("C"). The answer goes out through result[], and the return value says whether it worked. A C program that uses it:
#include <stdio.h>
int textlib_parse_int(const char *text, long *result);
int main(void) { const char *inputs[] = {"42", "-7", "hello"}; for (int i = 0; i < 3; i++) { long value = 0; if (textlib_parse_int(inputs[i], &value) == 0) { printf("%s -> %ld\n", inputs[i], value); } else { printf("%s -> not a number\n", inputs[i]); } } return 0;}mojo build textlib.mojo --emit shared-lib -o libtextlib.socc main.c -o main -L. -ltextlib -Wl,-rpath,'$ORIGIN'./mainOutput:
42 -> 42-7 -> -7hello -> not a numberWhat to know before you ship it
Section titled “What to know before you ship it”- The library still needs Mojo. Like an executable from
mojo build,libmylib.soloads Mojo’s runtime libraries, and it finds them through a path to your project’s.venvthat’s stored inside the library. Copy it to a machine without that folder and it won’t load. @exportneeds anabi. Leave it out and Mojo warns:@export requires an explicit 'abi()' effect on the function. Always writeabi("C")for C callers.- Some setup is missing without a Mojo
main():sys.argv()doesn’t get the C program’s arguments, and crashes don’t print Mojo’s stack trace. - macOS uses
.dylibfiles and needs one extra step (install_name_tool). The compilation guide lists the commands; we only tested on Linux. - For Python callers, there’s a better way. Python could load this library with
ctypes, but Mojo Calling Mojo from Python builds a real Python module with much less fuss.
Practice
Section titled “Practice”1. Sort by the last digit
Section titled “1. Sort by the last digit”Use qsort with a Mojo comparison function to sort [23, 41, 15, 32, 7] by their last digit (smallest first). Print the result.
Hint: inside the comparison, work out x % 10 and y % 10 and compare those instead of x and y. Return -1, 1 or 0.
Show solution
from std.ffi import external_call, c_int, c_size_tfrom std.sys import size_of
def by_last_digit( a: OpaquePointer[mut=False, _], b: OpaquePointer[mut=False, _],) abi("C") -> c_int: var x = a.unsafe_bitcast[c_int]()[] % 10 var y = b.unsafe_bitcast[c_int]()[] % 10 if x < y: return c_int(-1) return c_int(x > y)
def main(): var numbers: List[c_int] = [23, 41, 15, 32, 7] external_call["qsort", NoneType]( numbers.unsafe_ptr(), c_size_t(len(numbers)), c_size_t(size_of[c_int]()), by_last_digit, ) print(numbers)Output:
[41, 32, 23, 15, 7]The last digits are 1, 2, 3, 5 and 7, so that’s the order qsort puts them in. No two numbers share a last digit here, which matters because qsort doesn’t promise to keep equal items in their original order.
2. Export a max function
Section titled “2. Export a max function”Add a function to mylib.mojo that C can call as mylib_max(int a, int b) and that returns the bigger number. Write the line the C program needs to declare it.
Hint: copy mylib_add, change the name in @export(...) and the body. The C declaration has the same shape as mylib_add’s.
Show solution
@export("mylib_max")def max_of(a: c_int, b: c_int) abi("C") -> c_int: if a > b: return a return bint mylib_max(int a, int b);After rebuilding the library with mojo build mylib.mojo --emit shared-lib -o libmylib.so, printf("%d\n", mylib_max(4, 9)); in main.c prints 9. The Mojo function’s own name (max_of) doesn’t matter to C; only the name in @export does.
abi("C")compiles a Mojo function with C’s calling convention, so C can call it.abi("C")functions can’t raise: catch errors inside and return a status code.- Callbacks like
qsort’s comparison are plainabi("C")functions that takeOpaquePointers. @export("name")plusmojo build --emit shared-libturns Mojo code into a library C programs link against.- Call
initialize_runtime()(for example from an init function) before using runtime features from a C host. - The library still needs Mojo’s runtime libraries where it runs.
Next up: Mojo Modules & Packages, splitting your own Mojo code into files and importing it.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- The @export decorator: exporting functions, renaming them and the
abirule. - Call a Mojo shared library from C or C++: the compilation guide’s section with the Linux and macOS steps and
initialize_runtime(). - initialize_runtime reference: what it sets up and when you need it.
- Using Mojo’s C FFI: the manual’s FFI page, including the
qsortcallback example. - Function declarations: the reference for
abi("C"),thinand function types.