IMPORTANT: To view this page as Markdown, append `.md` to the URL (e.g. /docs/manual/basics.md). For the complete Mojo documentation index, see llms.txt.
Skip to main content
Version: Nightly
For the complete Mojo documentation index, see llms.txt. Markdown versions of all pages are available by appending .md to any URL (e.g. /docs/manual/basics.md).

Passing data to C ABI functions

These examples call functions from the C standard library, so they run without any extra build steps. A function in your own library follows the same rules. C-compatible data types explains the types and the ownership rules the examples rely on.

Each example calls external_call["name", ReturnType](arguments). The parameters name the C function and its return type. Mojo infers the argument types from the values you pass, so pass values of the C types the function expects, such as c_int(17) for an int, not a bare 17, which Mojo treats as an Int, not a c_int. A comment above each call shows the C prototype it matches.

C-style out arguments​

A "C-style" out argument is a result written through an argument. This venerable pattern, older than C itself, lets procedures or functions return results, often in the form of a success flag and the data. In C, the argument is a pointer to the caller's variable.

C's frexp() splits a number into a mantissa, which it returns, and an exponent, which it writes through a pointer:

from std.ffi import external_call, c_double, c_int

def main():
# double frexp(double x, int *exp);
var exponent: c_int = 0
var mantissa = external_call["frexp", c_double](
c_double(12.0), Pointer(to=exponent)
)
print(mantissa, exponent) # 0.75 4

Point a C-style out argument at a local var or a mut argument. A pointer to an immutable function argument hands C memory that Mojo treats as read-only. The call compiles, and a write through that pointer is undefined behavior.

Structs​

C's div() returns a struct by value:

from std.ffi import external_call, c_int

@fieldwise_init
struct DivT(RegisterPassable):
var quot: c_int
var rem: c_int

def main():
var r = external_call["div", DivT](c_int(17), c_int(5))
print(r.quot, r.rem) # 3 2

A struct passed through a pointer works like any other C-style out argument. clock_gettime() fills in a timespec that your code owns:

from std.ffi import external_call, c_int, c_long

comptime CLOCK_REALTIME = c_int(0)

@fieldwise_init
struct Timespec:
var tv_sec: Int64 # time_t
var tv_nsec: c_long

def main():
var now = Timespec(tv_sec=0, tv_nsec=0)
# int clock_gettime(clockid_t clock, struct timespec *tp);
_ = external_call["clock_gettime", c_int](CLOCK_REALTIME, Pointer(to=now))
print(now.tv_sec, now.tv_nsec)

Opaque handles​

fopen() returns a FILE* handle. This example reads one line and closes the file:

from std.ffi import external_call, c_char, c_int, CStringSpan

comptime FILE = Optional[MutOpaquePointer[MutUntrackedOrigin]]

def main() raises:
# FILE *fopen(const char *path, const char *mode);
var file = external_call["fopen", FILE](
"/etc/hosts".as_c_string_span(), "r".as_c_string_span()
)
if not file:
return
var line = Array[c_char, 256](fill=0)
# char *fgets(char *buf, int size, FILE *stream);
_ = external_call["fgets", Optional[Pointer[c_char, MutUntrackedOrigin]]](
line.unsafe_ptr(), c_int(len(line)), file
)
var text = CStringSpan(unsafe_from_ptr=line.unsafe_ptr())
print(String(from_utf8=text.as_bytes()), end="")
# int fclose(FILE *stream);
_ = external_call["fclose", c_int](file)

The handle belongs to the C library. Close it once, with the library's own function, and don't use it afterward. Mojo doesn't track it, so Mojo can't close it for you.

The standard library also calls fclose(), and it declares the handle the same way FILE does here. A program can declare each C function only one way. When you call a C function that the standard library also uses, match the standard library's Mojo types. A different declaration fails to build with a conflicting-signature error. Matching doesn't work for free(), as C memory explains.

C memory​

Some C APIs need memory from C's allocator, for example when the library frees the memory itself later. malloc() returns null when it fails, so declare its result as Optional. The memory belongs to C, so its origin is untracked:

from std.ffi import external_call, c_size_t

def main():
comptime SIZE = 64
# void *malloc(size_t size);
var block = external_call[
"malloc", Optional[Pointer[UInt8, MutUntrackedOrigin]]
](c_size_t(SIZE))
if case .Some(ptr) = block:
var bytes = Span(unsafe_ptr=ptr, length=SIZE)
bytes[0] = 42
print(bytes[0]) # 42
# void free(void *ptr);
external_call["free", NoneType](ptr)

Mojo doesn't free this memory. Free it once with free(), unless you hand it to a C library that frees it. Wrap the pointer in a Span with the size you asked for, and read and write through the span.

The standard library declares free() differently. A program that calls free() through external_call fails to build if it also uses input() or subprocess.run().

A with block can free the memory for you. The struct allocates in its initializer, and __exit__() calls free() when the block ends, even when the block raises an error:

from std.ffi import external_call, c_size_t

struct CBuffer:
var ptr: Pointer[UInt8, MutUntrackedOrigin]
var size: Int

def __init__(out self, size: Int) raises:
var block = external_call[
"malloc", Optional[Pointer[UInt8, MutUntrackedOrigin]]
](c_size_t(size))
if case .Some(ptr) = block:
self.ptr = ptr
else:
raise Error("malloc failed")
self.size = size

def __enter__(self) -> Span[UInt8, MutUntrackedOrigin]:
return Span(unsafe_ptr=self.ptr, length=self.size)

def __exit__(self):
external_call["free", NoneType](self.ptr)

def main() raises:
with CBuffer(1024) as buf:
buf[0] = 42
print(buf[0]) # 42

The same pattern can close a FILE* handle with fclose(). Don't use buf after the block ends: the span still exists, but the memory behind it is gone.

Buffers​

Check whether the function counts elements or bytes. getentropy() fills a buffer with random bytes, and its length argument counts bytes:

from std.ffi import external_call, c_int, c_size_t

def main():
var key = Array[UInt8, 16](fill=0)
# int getentropy(void *buf, size_t len);
var status = external_call["getentropy", c_int](
key.unsafe_ptr(), c_size_t(len(key))
)
print(status, key[0], key[15]) # 0, then two random bytes

The buffer belongs to Mojo. C writes into it during the call and keeps nothing afterward.

Strings​

Programs often configure a C library through the environment before the library starts. That one task shows three different owners: Mojo, the environment, and memory from malloc():

from std.ffi import external_call, c_char, c_int, CStringSpan

def main() raises:
var setting = String("OMP_NUM_THREADS=4")
# char *strdup(const char *s);
var copy = external_call[
"strdup", Optional[Pointer[c_char, MutUntrackedOrigin]]
](setting.as_c_string_span())
if not copy:
return
# int putenv(char *string);
_ = external_call["putenv", c_int](copy)
# char *getenv(const char *name);
var value = external_call[
"getenv", Optional[Pointer[c_char, ImmUntrackedOrigin]]
]("OMP_NUM_THREADS".as_c_string_span())
if value:
var text = CStringSpan(unsafe_from_ptr=value.value())
print(String(from_utf8=text.as_bytes())) # 4

putenv() keeps the pointer you pass. A span of setting would point at freed memory as soon as Mojo destroys setting, so the example gives C its own copy. strdup() makes that copy in memory from malloc(). The environment keeps the copy for the life of the process, so don't free it.

getenv() returns a pointer into the environment, which C owns and can change later. Copy the value into a Mojo String right away, and never free it.

Sometimes a C function returns malloc() memory that it doesn't keep, such as a strdup() copy that you only read. Free that memory with free() when you're done.

Other C functions write a string into a buffer you own. gethostname() copies the machine's name into a Mojo Array:

from std.ffi import external_call, c_char, c_int, c_size_t, CStringSpan

def main() raises:
var name = Array[c_char, 256](fill=0)
# int gethostname(char *name, size_t len);
var status = external_call["gethostname", c_int](
name.unsafe_ptr(), c_size_t(len(name) - 1)
)
if status == 0:
var text = CStringSpan(unsafe_from_ptr=name.unsafe_ptr())
print(String(from_utf8=text.as_bytes()))

A name that doesn't fit is cut off or makes the call fail, depending on the platform. A cut-off copy may lack the terminating zero byte. The example fills the array with zeros and passes one byte less than its size, so the last byte always stays zero.

Some functions also return a pointer into your buffer, as getcwd() does. Declare that result with your buffer's origin, such as Optional[Pointer[c_char, origin_of(buf)]], so Mojo keeps the buffer alive while you use the result.

Callbacks​

C's bsearch() calls a comparison function as it searches a sorted array. This example checks a port number against a table of well-known ports:

from std.ffi import external_call, c_int, c_size_t
from std.sys import size_of

def compare_ports(
key: ImmOpaquePointer[ImmUntrackedOrigin],
item: ImmOpaquePointer[ImmUntrackedOrigin],
) abi("C") -> c_int:
var wanted = key.unsafe_bitcast[UInt16]()[]
var entry = item.unsafe_bitcast[UInt16]()[]
return c_int(-1) if wanted < entry else c_int(wanted > entry)

def main():
var well_known: List[UInt16] = [22, 25, 53, 80, 123, 143, 443, 993]
var port = UInt16(443)
# void *bsearch(const void *key, const void *base, size_t count,
# size_t size, int (*compare)(const void *, const void *));
var found = external_call[
"bsearch", Optional[Pointer[UInt16, ImmUntrackedOrigin]]
](
Pointer(to=port),
well_known.unsafe_ptr(),
c_size_t(len(well_known)),
c_size_t(size_of[UInt16]()),
compare_ports,
)
print(port, "is well known" if found else "isn't well known")

bsearch() returns null when it finds nothing, so the result is an Optional pointer. It also requires a sorted array. Searching an unsorted array is undefined behavior, and nothing reports an error.

bsearch() calls the comparison function only while bsearch() itself runs. Other C functions store a callback and call it later, such as a completion handler or a function registered with atexit(). Everything a stored callback reads, including its context, has to stay alive until its last call.

The comparison function compares its values and returns -1, 0, or 1. It doesn't return wanted - entry, a common shortcut in C. Subtraction can overflow for wide integer types and return the wrong sign, and the search then goes the wrong way without any error.

For a complete example that sorts with qsort(), see Lambdas and FFI interop.

Errors​

C reports errors through return values, null pointers, and C-style out arguments, never through exceptions. Many C library functions also set errno, an error code that each thread keeps separately. Read it with get_errno() from std.ffi right after the call fails, before another call can change it:

from std.ffi import external_call, get_errno

comptime FILE = Optional[MutOpaquePointer[MutUntrackedOrigin]]

def main():
# FILE *fopen(const char *path, const char *mode);
var file = external_call["fopen", FILE](
"/no/such/file".as_c_string_span(), "r".as_c_string_span()
)
if not file:
print("fopen failed:", get_errno()) # No such file or directory

Check the return value first. errno means something only after a call reports failure. A successful call can leave an old value in place.

To let the rest of your Mojo code handle C failures as errors, check the result in a small wrapper and raise:

from std.ffi import external_call, c_int, c_long, get_errno

comptime CLOCK_REALTIME = c_int(0)

@fieldwise_init
struct Timespec:
var tv_sec: Int64 # time_t
var tv_nsec: c_long

def clock_nanos(clock: c_int) raises -> Int64:
var now = Timespec(tv_sec=0, tv_nsec=0)
# int clock_gettime(clockid_t clock, struct timespec *tp);
if external_call["clock_gettime", c_int](clock, Pointer(to=now)) != 0:
raise Error("clock_gettime failed: ", get_errno())
return now.tv_sec * 1_000_000_000 + Int64(now.tv_nsec)

def main() raises:
print(clock_nanos(CLOCK_REALTIME))

The wrapper reads errno before it does anything else, so the message reports the failure that actually happened.

Check your declarations​

Neither external_call() nor get_function() checks a declaration against the C function it names. Make sure each declaration matches its C header: the argument count, each argument type, and the return type. Also make sure each pointer is valid and each cast describes the actual data. A mismatch produces wrong results or undefined behavior, such as a crash, not a Mojo error. Interop safety lists the mismatches that compile and run anyway.