Skip to content

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.

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:

3
7

abi("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 module

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 module

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

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_t
from 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:

  • qsort gets 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 descending with two void* pointers, which Mojo calls OpaquePointer: pointers that don’t say what they point to. unsafe_bitcast[c_int]() tells Mojo to treat them as pointers to c_int, and [] reads the value.
  • The function returns a negative number when a should come first, a positive number when b should, and 0 when they’re equal. Returning -1 when x > y puts bigger numbers first.

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_t
from 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 name mylib_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 C const double * arrives: a read-only pointer to memory Mojo doesn’t own. values[unsafe_offset=i] reads item i. Nothing checks that count is right; that’s up to the C caller.
  • mylib_init calls initialize_runtime(). More on that in a moment.

Build it with --emit shared-lib:

Terminal window
mojo build mylib.mojo --emit shared-lib -o libmylib.so

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

Terminal window
cc main.c -o main -L. -lmylib -Wl,-rpath,'$ORIGIN'
./main

Output:

2 + 3 = 5
sum = 7.75
Hello 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.

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_init above, 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.

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 -1

String(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;
}
Terminal window
mojo build textlib.mojo --emit shared-lib -o libtextlib.so
cc main.c -o main -L. -ltextlib -Wl,-rpath,'$ORIGIN'
./main

Output:

42 -> 42
-7 -> -7
hello -> not a number
  • The library still needs Mojo. Like an executable from mojo build, libmylib.so loads Mojo’s runtime libraries, and it finds them through a path to your project’s .venv that’s stored inside the library. Copy it to a machine without that folder and it won’t load.
  • @export needs an abi. Leave it out and Mojo warns: @export requires an explicit 'abi()' effect on the function. Always write abi("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 .dylib files 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.

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

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 b
int 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 plain abi("C") functions that take OpaquePointers.
  • @export("name") plus mojo build --emit shared-lib turns 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

1. Why can't an abi("C") function be marked raises?
2. Which command turns mylib.mojo into a library a C program can link against?
3. In @export("mylib_add") def add(...) abi("C"), which name does the C program use?
4. A C program using your library starts with "cannot open shared object file". What's a likely fix?