20. The native boundary: C interop
Mini calls C directly: no wrapper layer, no generated glue. The API is the one of Kotlin/Native's kotlinx.cinterop, so code written for it mostly works unchanged.
Not in the browser
The in-browser compiler produces WebAssembly with no C libraries and no system calls beyond standard output, so a program that calls into C cannot run here. The listings in this chapter are plain code. To run them, install Mini. The Check cell at the end works in the browser, because the memory checker needs no C at all.
By the end: identify the symbol, representation and lifetime contract at a C boundary. This chapter needs a native installation for execution; the browser cannot link your host libraries. Ownership checks can still be demonstrated in a Check cell.
Declaring and calling C functions
An external fun with @CName("symbol") is a direct call of the C function:
@file:CInclude("time.h")
import kotlin.native.CName
import kotlinx.cinterop.*
@CName("strlen")
external fun strlen(s: CPointer<ByteVar>): Long
fun main() {
memScoped {
println(strlen("héllo".cstr.ptr)) // 6: the length of the UTF-8 bytes
}
}@file:CInclude("header.h") becomes a real #include in the generated C, @file:CLink("m") adds -lm to the link line and --c-src helper.c compiles your own C file into the program. Only exported symbols can be called, not macros or static inline functions.
Types map one to one:
| Kotlin | C |
|---|---|
Byte, Short, Int, Long | int8_t, int16_t, int32_t, int64_t |
Float, Double | float, double |
Boolean, Unit | bool, void |
CPointer<T>, COpaquePointer | T *, void * |
CPointer<CFunction<(Int) -> Int>> | int (*)(int) |
Strings, classes and structs by value have no C representation. Unsigned types do not exist yet.
Memory and callbacks
Pointers are plain machine addresses, never reference counted. memScoped { ... } frees everything allocated inside when it ends, and staticCFunction { ... } turns a non-capturing lambda into a C function pointer. This is the complete sample the documentation CI builds and runs natively: it calls strlen, sorts an array with qsort and a Kotlin comparator, and fills a struct tm with gmtime_r:
@file:Suppress("WRONG_MODIFIER_TARGET")
@file:CInclude("time.h")
import kotlin.native.CName
import kotlinx.cinterop.*
@CName("strlen")
external fun strlen(s: CPointer<ByteVar>): Long
@CName("qsort")
external fun qsort(base: COpaquePointer?, n: Long, size: Long, cmp: CPointer<CFunction<(COpaquePointer?, COpaquePointer?) -> Int>>)
@CStruct("tm")
external class Tm : CStructVar {
var tm_sec: Int
var tm_min: Int
var tm_hour: Int
var tm_mday: Int
var tm_mon: Int
var tm_year: Int
var tm_wday: Int
var tm_yday: Int
var tm_isdst: Int
var tm_gmtoff: Long
var tm_zone: CPointer<ByteVar>?
}
@CName("gmtime_r")
external fun gmtime_r(t: CPointer<LongVar>, out: CPointer<Tm>): CPointer<Tm>?
val ascending = staticCFunction { a: COpaquePointer?, b: COpaquePointer? ->
a!!.reinterpret<IntVar>().pointed.value - b!!.reinterpret<IntVar>().pointed.value
}
fun main() {
memScoped {
println(strlen("héllo".cstr.ptr))
val numbers = allocArray<IntVar>(5)
val values = intArrayOf(42, 7, 19, 3, 88)
for (i in 0 until 5) numbers[i] = values[i]
qsort(numbers, 5L, 4L, ascending)
for (i in 0 until 5) print("" + numbers[i] + " ")
println()
val seconds = alloc<LongVar>()
seconds.value = 86400L * 365L
val tm = alloc<Tm>()
gmtime_r(seconds.ptr, tm.ptr)
println("" + (tm.tm_year + 1900) + "-" + (tm.tm_mon + 1) + "-" + tm.tm_mday)
}
}Its output:
6
3 7 19 42 88
1971-1-1Structs are declared as external class with @CStruct("tm") and laid out with the C rules. The C interop guide has the full list.
The memory checker knows about C memory
In a Strict file the pointer rules are the same as for every other owned value. memScoped is a scoped allocator like Arena: a pointer into it must not leave the block. This one you can check right here:
@file:MemoryMode(Mode.Strict)
import kotlinx.cinterop.*
import mini.memory.*
fun dangling(): CPointer<IntVar> {
val p = memScoped {
val x = alloc<IntVar>()
x.value = 1
x.ptr // the memory is freed when memScoped ends
}
return p
}
fun main() {
println(dangling().pointed.value)
}M0105. And a pointer returned by C is externally managed unless you say otherwise: @Owned(free = "free") on the external fun makes the caller the owner, with the same leak, double free and use-after-free checks as for Heap.
Limits
64-bit targets only. No unsigned types, no structs by value, no bit fields. Exporting Kotlin functions to C and a binding generator from headers are planned. The roadmap is the honest list.
Checkpoint
Does a C pointer keep its allocation alive? Can a Kotlin String simply be passed as char *? Who should free a pointer returned by a C library?
Reasoning
A pointer is an address, not a reference-counted owner. Convert strings through the documented C representation and respect the conversion buffer's lifetime. The C API defines whether a returned pointer is borrowed or owned and which release function matches it.