Mojo package
ffi
Foreign function interface (FFI) for calling C code and loading libraries.
This module provides tools for interfacing Mojo with C libraries and other foreign code. It includes:
- C type aliases:
c_int,c_char,c_long,c_size_t, etc. for portable type definitions that match C's type sizes on each platform. - Dynamic library loading:
OwnedDLHandlefor loading shared libraries at runtime and calling their functions. - External function calls:
external_call()for calling C functions by name with compile-time resolution. - String interop:
CStringSlicefor working with null-terminated C strings.
Example:
from ffi import c_int, external_call
fn get_random() -> c_int:
return external_call["rand", c_int]()For loading dynamic libraries:
from ffi import OwnedDLHandle
fn main() raises:
var lib = OwnedDLHandle("libm.so")
var sqrt = lib.get_function[fn(Float64) -> Float64]("sqrt")
print(sqrt(4.0)) # 2.0comptime values
c_char
comptime c_char = Int8
C char type.
c_double
comptime c_double = Float64
C double type.
c_float
comptime c_float = Float32
C float type.
c_int
comptime c_int = Int32
C int type.
The C int type is typically a signed 32-bit integer on commonly used targets
today.
c_long
comptime c_long = Scalar[_c_long_dtype()]
C long type.
The C long type is typically a signed 64-bit integer on macOS and Linux, and a
32-bit integer on Windows.
c_long_long
comptime c_long_long = Scalar[_c_long_long_dtype()]
C long long type.
The C long long type is typically a signed 64-bit integer on commonly used
targets today.
c_pid_t
comptime c_pid_t = Int
C pid_t type.
c_short
comptime c_short = Int16
C short type.
c_size_t
comptime c_size_t = UInt
C size_t type.
c_ssize_t
comptime c_ssize_t = Int
C ssize_t type.
c_uchar
comptime c_uchar = UInt8
C unsigned char type.
c_uint
comptime c_uint = UInt32
C unsigned int type.
c_ulong
comptime c_ulong = Scalar[_c_long_dtype[True]()]
C unsigned long type.
The C unsigned long type is typically a 64-bit integer on commonly used
targets today.
c_ulong_long
comptime c_ulong_long = Scalar[_c_long_long_dtype[True]()]
C unsigned long long type.
The C unsigned long long type is typically a 64-bit integer on commonly used
targets today.
c_ushort
comptime c_ushort = UInt16
C unsigned short type.
DEFAULT_RTLD
comptime DEFAULT_RTLD = (2 | RTLD.GLOBAL)
Default runtime linker flags for dynamic library loading.
MAX_PATH
comptime MAX_PATH = _get_max_path()
Maximum path length for the current platform.
Modules
Structs
-
OwnedDLHandle: Represents an owned handle to a dynamically linked library with RAII semantics. -
RTLD: Enumeration of the RTLD flags used during dynamic library loading.
Functions
-
external_call: Calls an external function.
Was this page helpful?
Thank you! We'll create more content like this.
Thank you for helping us improve!