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).
Interop safety
Mojo checks types, mutability, and lifetimes, but it can't inspect what happens inside functions written in other languages. At the foreign function interface (FFI), Mojo trusts the interface you declare. A wrong declaration can compile successfully and still produce incorrect results or crash.
That makes you the type checker. Treat the library's headers and API docs as the contract. Three rules matter most:
- Match the library's types. Use the
std.ffialiases to match the target platform's C ABI. Incorrect types can produce wrong results without a compiler error. - Free memory where it was allocated. Use the allocating library's
deallocator, such as
free(). Keep Mojo memory alive for as long as foreign code needs it, even after the call returns. - Don't expect exceptions. Incorrect FFI declarations can cause undefined behavior, including results that appear correct. Passing tests don't prove a declaration is safe.
What Mojo checks for you
Mojo still checks the operations and lifetimes it can see. Operations
that bypass some of those checks use the unsafe_ prefix. For example:
unsafe_ptr()to hand foreign code a raw pointer.unsafe_bitcast()to reinterpret one.unsafe_offset=to index past the first element.String(unsafe_from_utf8_ptr=)to trust bytes foreign code gave you.
With each unsafe_ operation, you take responsibility for a guarantee
the compiler can't verify.
Mojo tracks pointer lifetimes through origins. For example,
line.as_c_string_span() ties the pointer's lifetime to line.
But Mojo can't track a pointer that foreign code stores for later use.
A callable returned by OwnedDLHandle.get_function() borrows the library
handle, keeping the library open while the callable is in use.
An origin stops you from moving the owner while a pointer or callable
depends on it, but not from reassigning it. Assigning a new value to
line or lib destroys the old value, and a span or callable from it
then refers to freed memory or a closed library. Don't reassign the
owner while you use anything that borrows from it.
For Python objects, checked downcasts raise on type mismatches, and Python
exceptions reach Mojo as catchable Error values.
Neither external_call() nor OwnedDLHandle validates a C function's
signature. The sections below distinguish errors Mojo catches from
mistakes you must prevent. Entries name the relevant API where needed.
Caught at build time
Mojo rejects some invalid FFI uses before the program runs. These checks are useful, but they don't verify a function against its C declaration.
- Conflicting C ABI signatures for one symbol (
external_call()): Declaringstrchrtwice in the same module with incompatible lowered C ABI signatures won't build. Different Mojo types that lower to the same signature don't trigger this check. The diagnostic points intostd.ffirather than at either of your call sites. This is easy to hit when a wrapper and an inline call disagree.get_function()casts a runtime pointer instead, so it has no module-level declaration to collide. - String arguments (
external_call()): Passing a MojoStringis rejected at compile time, and the error namesas_c_string_span()(null-terminated characters) as the fix. Of argument types,Stringis the only one the API checks. AStaticStringor other string slice compiles, so callas_c_string_span()on any Mojo string you pass to C.OwnedDLHandledoesn't repeat the check. - Return types must be
RegisterPassable:return_typeis bound toRegisterPassable, so the compiler rejects a return type that doesn't conform. raisesonabi("C")functions (@export): Anabi("C")function can't be markedraises, and the compiler rejects it. Foreign callers have no way to receive a Mojo error, so return failures as values. An@exportwithoutabi("C")only gets a warning, and a raising function builds, so always writeabi("C")on exports.
Availability checks
Loading a missing library with OwnedDLHandle, or looking up a missing
symbol with get_function[](), raises an error you can catch. This lets
you check for optional features and provide fallbacks.
OwnedDLHandle.call[]() and borrow() abort on a missing symbol instead.
For example, loading an unavailable library raises an error:
from std.ffi import OwnedDLHandle
from std.sys.info import platform_map
comptime LIBCURL = platform_map[
"libcurl", linux="libcurl.so.4", macos="libcurl.dylib"
]()
def main():
try:
var lib = OwnedDLHandle(LIBCURL)
# use the optional feature
except:
# fall back
Use check_symbol() to test whether a library exports a function or
global, especially for optional or platform-specific features. Linux's
libm exports exp10 and macOS's libm doesn't, so this example prints
100.0 on Linux and takes the fallback on macOS:
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)
if lib.check_symbol("exp10"):
var exp10 = lib.get_function[c_double]("exp10")
print(exp10(c_double(2.0))) # 100.0 on Linux
else:
print("exp10 not found in libm")
Failures the compiler can't catch
The compiler can't compare your FFI declarations with the foreign library's actual interfaces. The following mistakes may compile but produce incorrect results, corrupt memory, or crash. Some appear only on another platform.
Function signatures and calling conventions
- Return type width: Declaring a narrower return than C returns keeps
only the low bits. Declare
strchr'schar*return asc_intand thePointercomes back truncated. That's truncation rather than noise, so a wrong value can still look plausible. - Argument types: Mojo uses the widths and signedness you declare; it doesn't compare them with the C function's actual signature.
- Undeclared argument types (
OwnedDLHandle):get_function()takes the return type only, so nothing connects the arguments to the C function's real signature. Callingget_function[c_double]("sqrt")with ac_inthas undefined behavior rather than raising a type error. It may return a meaningless value instead of failing. - Raw
Stringarguments (OwnedDLHandle):external_call()rejects aStringat compile time, but a callable fromget_function()accepts one and reads whatever the struct's bytes happen to be. Always passas_c_string_span(). - Variadic callees without
num_fixed_args: Passnum_fixed_argsfor every C variadic function. Without it, each argument defaults to a fixed argument of a non-variadic callee, which gets the ABI wrong foropen()orsnprintf(). Apple's arm64 ABI passes variadic arguments differently from fixed ones, so the mistake can work on x86-64 Linux and break on Apple silicon. Functions fromOwnedDLHandletake nonum_fixed_args, so call variadic functions withexternal_call(). - Platform-varying C types:
c_longandc_ulongresolve per target rather than to one fixed width. Every platform Mojo supports is LP64, so writingInt64for a Clonghappens to work, but the alias says what you mean.c_chardoes differ: it's signed on x86-64 and macOS but unsigned on Linux arm64, so a comparison against a negative value changes meaning between targets.
Pointers and memory
- Pointers returned into a library (
OwnedDLHandle): When a C function returns aPointerinto its own library, the return type must borrow from the handle. For a C string, declare it asCStringSpan[lib_origin]wherecomptime lib_origin = ImmOrigin(origin_of(lib)). DeclaringImmStaticOrigincompiles, then reads freed memory once the handle closes the library. - Mixed allocators: Free memory with the allocator that created
it. Mojo's
unsafe_free()doesn't releasemalloc()memory, andfree()doesn't release Mojo allocations. Both mistakes compile, and can crash or corrupt the heap. - Pointers foreign code keeps after the call: An origin protects a pointer for as long as Mojo can see it. Mojo can't see foreign code storing your pointer for later, so a call returning doesn't mean the callee is finished with what you passed. Check the library's documentation for whether a function retains the pointer.
- Non-nul-terminated buffers: A bare
Pointer[c_char]into a buffer with no terminator sends a C string function reading off the end.CStringSpanis the guardrail for this, ensuring a null terminator is present.
Callbacks and exports
-
Callbacks without
abi("C"): A Mojo function passed to foreign code as a callback needsabi("C"). -
Capturing lambdas as callbacks: Use thin lambdas, not closures that capture values.
-
Exported signatures (
@export): Anabi("C")export accepts Mojo types such asStringandList, and symbol names C can't spell, such asnot-a-c-name. Foreign callers can't construct those types or name those symbols. Use only C-compatible types and valid C identifiers. -
Runtime initialization (
@export): Callinitialize_runtime()at the start of an exported function that uses the Mojo runtime's worker threads, such as code that runs work in parallel or callsparallelism_level(). A foreign host never runs Mojo's startup code, so those threads don't exist until you initialize the runtime, and code that needs them crashes. Exported functions that don't use worker threads don't need it.If you export a separate initialization function, every host, whether it's written in C, C++, Rust, etc, has to call it first, and a host that forgets crashes the same way.
initialize_runtime()is idempotent, so calling it multiple times is safe:from std.runtime import initialize_runtimeinitialize_runtime() # call first in affected exported functionsFor more details, see.
Python
Python-specific interoperability
- Python version support. Mojo supports CPython 3.10 and later, but not free-threaded Python builds.
- Mojo errors become generic Python exceptions. A Mojo
Errorraised from a function registered withdef_function()reaches Python asException. Useraise_python_exception()with anExceptionTypeto raise a specific type, such asValueErrororTypeError.
Python-specific memory and pointers
- NumPy views:
from_numpy_array()gives Mojo a view of the array's buffer, not a copy. Resizing or reallocating the array while you use the view leaves the view pointing at freed memory. - Downcast pointers:
downcast_value_ptr[T]()returns a pointer with a wildcard origin, so Mojo doesn't track aliasing through it. Don't mutate an object through two downcast pointers at the same time.unchecked_downcast_value_ptr[T]()also skips the type check.
Python-specific conversions
- Narrow integer conversions: Integer
py=initializers can wrap silently.UInt8(py=300)produces44,Int8(py=200)produces-56, andInt32(py=2**40)produces0. Some out-of-range values raise instead, such asUInt8(py=-1)andInt64(py=2**63), so don't rely on a conversion to either wrap or raise. - Permissive conversions:
String(py=)callsstr(), so any object converts andNonebecomes"None".Int(py=)callsint(), so3.9becomes3and"12"becomes12.Bool(py=)uses truthiness. Check the Python type first when the input could be the wrong kind.