FFI
Calling into C with extern C blocks and raw cstr / raw ptr views.
Minimal extern
Section titled “Minimal extern”extern "C": def abs(x: c_int) -> c_int
def main() -> i32: unsafe: return abs(-42)What’s worth noticing:
extern "C":is a block of bodyless C ABI declarations. The block is module-private: expose the wrapped function via a safeexport defif you want it reachable from other modules.- The call site needs an
unsafe:block. The body is otherwise fully checked. c_intis a nominal alias for the C-ABIinton the target.
Passing a NUL-terminated string
Section titled “Passing a NUL-terminated string”extern "C": def puts(buf: *const u8) -> c_int
def main() -> i32: unsafe: puts(raw cstr "hello from zmeu") return 0What’s worth noticing:
raw cstr "literal"produces a*const c_charview over the string literal with an implicit NUL terminator. There is no separateb"...\0"needed.raw cstralso accepts aview CStrfor already-borrowed C strings (e.g. coming out ofCString.as_cstr()).- For pointer-shaped byte buffers, use
raw ptr bytes(*const u8) orraw mut ptr buf(*mut u8).
What’s the unsafe block for
Section titled “What’s the unsafe block for”unsafe: permits three things in its body:
- Calls to
unsafe deffunctions. - Calls to raw extern declarations.
- Passing
raw ptr/raw cstr/raw mut ptrviews to those calls.
That’s it. The body is otherwise checked like normal code: there is no general escape hatch over the type or borrow rules. See Unsafe and FFI for the full picture.