Interop
- Kotlin course
- Expert
- Lesson 20/47
- 5 min
Learn C libraries with C interop.
What is C interop?
C interop lets Kotlin/Native code call C libraries. This is the way to reuse an existing C codebase.
In Gradle a C library is declared with a cinterops block; a .def file specifies header files and compile options. Kotlin generates a binding for each C function; you call these bindings like ordinary Kotlin functions. SQLite, libgit2 and OpenSSL are used this way. In this lesson we show the interop concept with a simple CLib model.
Mapping C types
C interop automatically maps C types to Kotlin types. The mapping is fixed; no manual tuning is needed.
Example: C int maps to Kotlin Int, char* to CPointer<ByteVar>, struct to a Kotlin class. Memory management happens on the Kotlin side; you allocate with nativeHeap.alloc<T>() and release with nativeHeap.free(ptr). This is the Kotlin counterpart of C's malloc/free. Wrong use causes a memory leak.
Practice Write CLib.cstrlen
Define object CLib. Inside it fun cstrlen(s: String): Int should return s.length. In main, write println(CLib.cstrlen("merhaba")).
Starter code
// add the CLib object
fun main() {
// print CLib.cstrlen("merhaba") result
}Sample solution
object CLib {
fun cstrlen(s: String): Int = s.length
}
fun main() {
println(CLib.cstrlen("merhaba"))
}Expected output
7
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the cstrlen call
fun main() {
val n = CLib.____("merhaba")
println(n)
}
fun main() {
val n = CLib.cstrlen("merhaba")
println(n)
}
Explanation: cstrlen is the Kotlin binding for the C strlen function.
2 Match C-Kotlin types
| Term | Meaning |
|---|---|
cinterops |
C library block |
.def file |
Headers and options |
nativeHeap |
Memory manager |
CPointer |
Pointer type |
3 Which file declares a C interop?
- A .json file
- A .def file Correct answer
- A .xml file
- A .properties file
Explanation: A .def file specifies headers and compile options.