Native library
- Kotlin course
- Expert
- Lesson 23/47
- 5 min
Learn to write native libraries with Kotlin/Native.
Native library output
Kotlin/Native produces not only executables but also native libraries. These libraries can be called from other languages.
In Gradle you write binaries { framework { ... } } or binaries { sharedLib() } inside a target block. On iOS a framework is produced; this framework is added to an Xcode project and called from Swift. On Linux/Windows a sharedLib (.so, .dll) is produced; it can be called from C or Python. This is how Kotlin code joins an existing platform ecosystem.
A NativeLib example
In this lesson we model library loading with a NativeLib class. In a real setup the Gradle binaries block produces this automatically.
Example: class NativeLib(val name: String) { fun load(): String = "loaded: $name" }. The call NativeLib("sqlite").load() returns "loaded: sqlite". A real library would call C functions at this point; here we report a successful load with a string. This simple model is enough to understand the library lifecycle.
Practice Write NativeLib
Define class NativeLib(val name: String). Method fun load(): String should return "loaded: $name". In main, build val lib = NativeLib("sqlite") and write println(lib.load()).
Starter code
// add the NativeLib class
fun main() {
// load the sqlite library and print
}Sample solution
class NativeLib(val name: String) {
fun load(): String = "loaded: $name"
}
fun main() {
val lib = NativeLib("sqlite")
println(lib.load())
}Expected output
loaded: sqlite
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the load method
class NativeLib(val name: String) {
fun ____(): String = "loaded: $name"
}
class NativeLib(val name: String) {
fun load(): String = "loaded: $name"
}
Explanation: load() loads the library and returns its name.
2 Which output is produced on an iOS target?
- A framework Correct answer
- A .dll file
- A .so file
- A .jar file
Explanation: The iOS target produces a framework; it is added to Xcode.
3 Match library parts
| Term | Meaning |
|---|---|
framework |
iOS output |
sharedLib |
Linux/Windows output |
binaries |
Gradle block |
Xcode |
Apple IDE |