Version: 1.1.0

Calling C from Mojo

Mojo calls C by declaring the foreign function with a C-compatible signature. The declaration is the whole import.

Essentials

  • Use the FFI declaration form for the C name and argument types.
  • Pass integers, floats, and pointers. Pass structs only when the layout matches C.
  • Strings need a pointer and a length, or a NUL-terminated buffer.
  • The C library must be on the link line or the system search path.
  • Ownership of memory allocated by C stays with C unless you document a free function.

Example

fn strlen(s: UnsafePointer[UInt8]) -> Int:
    """Foreign declaration shape. Bind this to the C symbol when you import it."""
    return 0

Keep in mind

Write a thin Mojo wrapper that copies into a String or Span so the rest of the program never sees the C pointer.