Skip to content

Keel

EnglishEestiEspañolไทย

Tekstide kirjutamisel ja parandamisel kasutasin tehisaru abi, seega võib esineda kirja- ja muid vigu. Kui leiate mõne, andke palun teada: [email protected]

Rust in Kotlin Multiplatform: One Native Core for Android and iOS, and When to Skip Rust Entirely

Rust in Kotlin Multiplatform: One Native Core for Android and iOS, and When to Skip Rust Entirely

Kotlin Multiplatform

Autor: David Cruz Anaya, mobiili ja rakendusliku tehisaru insener

Uuendatud 30. oktoober 202612 min lugemist

Android · Rust · NDK · Kotlin Multiplatform · UniFFI · iOS

Rust + NDK on Android, Part 15 of 15. This series teaches Android developers how to ship Rust in production apps, no prior Rust required. Hub: Rust on Android: How to Use It, How to Debug It, and Why It's Worth It. Previous: CI/CD for Rust + Android: GitHub Actions, Cross-Compilation Caching, Reproducible Builds. This part closes the series.

Rust in Kotlin Multiplatform comes down to one crate producing two artifacts, plus one decision about the bridge. The crate compiles to a cdylib for Android through cargo-ndk, exactly as it has since the start of this series, and to static libraries wrapped in an XCFramework for iOS. The bridge is either UniFFI generating Kotlin and Swift from one annotated interface, or a small C API under expect/actual, with JNI on the Android side and cinterop on the iOS side. The Rust itself does not change. Only the packaging does.

Because this is the closing part, it also covers the question that should come before any of that plumbing: whether your app needs Rust at all. The second half is the checklist of cases where I would tell you to skip it. This assumes the toolchain from Part 1 and the UniFFI workflow from Part 3.

Key Takeaways

  • One crate, two artifacts: cargo-ndk produces the Android .so, and xcodebuild -create-xcframework packages the iOS static libraries. All three Apple iOS targets are Tier 2 in rustc (Platform Support).
  • UniFFI generates Kotlin and Swift from the same annotated Rust. Element X ships its entire Matrix engine, the open source matrix-rust-sdk, to both platforms this way.
  • Kotlin/Native imports C and Objective-C headers, not Swift, so shared Kotlin that must call Rust on iOS goes through a C API under expect/actual (Kotlin docs).
  • Rust earns a place in a KMP app only below a profiled native need. Kotlin stays the default, the same gate as the hub post.

Where Rust fits in a Kotlin Multiplatform architecture

KMP and Rust answer different questions, and confusing the two produces the wrong architecture. Kotlin Multiplatform shares the code you would otherwise write twice: view models, repositories, networking, persistence, business rules. Rust shares the code that has to be native on both platforms anyway: the image pipeline from Part 5, the audio DSP from Part 10, the parsing core from Part 11, the crypto from Part 12.

In the layering I use in my KMP clean architecture blueprint, Rust sits one floor below commonMain. Common code owns an interface, the platform source sets own the bridge to the crate, and everything above the interface stays testable with fakes on the JVM. No use case or view model knows the implementation changed languages.

Block builds Bitkey, its bitcoin wallet, with Kotlin Multiplatform for the shared app logic and Rust for the core underneath (Block Engineering). Element X drives both its Android and iOS apps from the Rust matrix-rust-sdk through UniFFI-generated Kotlin and Swift. The shape you are about to build is the same one they ship.

One crate, two platforms

The crate for this part lives at rust/kmp-core and is deliberately tiny, because the plumbing is the lesson. Here is rust/kmp-core/Cargo.toml:

[package]
name = "kmp-core"
version = "0.1.0"
edition = "2021"

[lib]
name = "kmp_core"
crate-type = ["cdylib", "staticlib"]

[dependencies]
uniffi = { version = "0.29", features = ["cli"] }

[[bin]]
name = "uniffi-bindgen"
path = "uniffi-bindgen.rs"

Two crate types because the platforms load code differently. Android dlopens a shared object, so it gets the cdylib. Apple’s toolchain prefers to link native code into the final binary itself, so iOS gets the staticlib. The uniffi-bindgen binary is the standard UniFFI pattern for generating bindings from your own crate (UniFFI tutorial), and rust/kmp-core/uniffi-bindgen.rs is three lines:

fn main() {
    uniffi::uniffi_bindgen_main()
}

The library at rust/kmp-core/src/lib.rs exposes the same logic twice, once through UniFFI for the generated-bindings route and once as a plain C function for the cinterop route:

uniffi::setup_scaffolding!();

#[derive(uniffi::Record)]
pub struct ReceiptSummary {
    pub items: u32,
    pub total_cents: i64,
}

#[uniffi::export]
pub fn summarize_receipts(amounts_cents: Vec<i64>) -> ReceiptSummary {
    ReceiptSummary {
        items: amounts_cents.len() as u32,
        total_cents: amounts_cents.iter().sum(),
    }
}

/// C entry point for the Kotlin/Native cinterop route on iOS.
#[no_mangle]
pub extern "C" fn kmp_core_sum_cents(amounts: *const i64, len: usize) -> i64 {
    if amounts.is_null() || len == 0 {
        return 0;
    }
    let amounts = unsafe { std::slice::from_raw_parts(amounts, len) };
    amounts.iter().sum()
}

The Android build is the command you have typed fourteen times by now, aimed at the shared module instead of an app module:

cargo ndk -t arm64-v8a -t armeabi-v7a -t x86_64 \
  -o shared/src/androidMain/jniLibs build --release -p kmp-core

One line inside the existing android block of shared/build.gradle.kts teaches AGP where those libraries live:

sourceSets["main"].jniLibs.srcDir("src/androidMain/jniLibs")

Building the XCFramework for iOS

Rust treats the Apple iOS targets as Tier 2, same as the Android ones (Platform Support): aarch64-apple-ios for devices, aarch64-apple-ios-sim and x86_64-apple-ios for simulators. You cannot merge all three with lipo, because the device and Apple Silicon simulator slices share an architecture and a fat binary cannot hold both. That collision is exactly why Apple introduced the XCFramework format (Apple Developer). The older cargo-lipo tool predates it; today you want xcodebuild -create-xcframework.

The whole build is one script at scripts/build-ios-core.sh, run from the repository root on a Mac:

#!/usr/bin/env bash
set -euo pipefail

TARGETS=(aarch64-apple-ios aarch64-apple-ios-sim x86_64-apple-ios)
for target in "${TARGETS[@]}"; do
  rustup target add "$target"
  cargo build -p kmp-core --release --target "$target"
done

# lipo only merges the two simulator slices; the device slice stays alone.
mkdir -p target/ios-sim-universal
lipo -create \
  target/aarch64-apple-ios-sim/release/libkmp_core.a \
  target/x86_64-apple-ios/release/libkmp_core.a \
  -output target/ios-sim-universal/libkmp_core.a

rm -rf target/KmpCore.xcframework
xcodebuild -create-xcframework \
  -library target/aarch64-apple-ios/release/libkmp_core.a \
  -headers rust/kmp-core/include \
  -library target/ios-sim-universal/libkmp_core.a \
  -headers rust/kmp-core/include \
  -output target/KmpCore.xcframework

Drop the resulting KmpCore.xcframework into the Xcode project and Xcode picks the right slice per destination. In CI this script slots into the macOS runner job from Part 14 unchanged.

Route one: UniFFI generates Kotlin and Swift from one interface

The same annotated Rust produces both bindings. One config file at rust/kmp-core/uniffi.toml names the output for each language (Kotlin config, Swift config):

[bindings.kotlin]
package_name = "dev.davthecoder.rustseries.rust"
cdylib_name = "kmp_core"

[bindings.swift]
module_name = "KmpCore"

Generation reads the compiled library’s metadata, so build for the host first, then run bindgen twice:

cargo build -p kmp-core --release

cargo run -p kmp-core --bin uniffi-bindgen -- generate \
  --library target/release/libkmp_core.dylib \
  --language kotlin \
  --out-dir shared/src/androidMain/kotlin

cargo run -p kmp-core --bin uniffi-bindgen -- generate \
  --library target/release/libkmp_core.dylib \
  --language swift \
  --out-dir ios/Generated

The Kotlin lands in androidMain, needs the JNA dependency from Part 3, and works immediately. Common code then defines the API it wants in shared/src/commonMain/kotlin/dev/davthecoder/rustseries/ReceiptCore.kt using expect/actual (Kotlin docs):

package dev.davthecoder.rustseries

data class Receipts(val items: Int, val totalCents: Long)

expect fun summarizeReceipts(amountsCents: List<Long>): Receipts

The Android actual at shared/src/androidMain/kotlin/dev/davthecoder/rustseries/ReceiptCore.android.kt is one import away from done:

package dev.davthecoder.rustseries

import dev.davthecoder.rustseries.rust.summarizeReceipts as rustSummarizeReceipts

actual fun summarizeReceipts(amountsCents: List<Long>): Receipts {
    val summary = rustSummarizeReceipts(amountsCents)
    return Receipts(
        items = summary.items.toInt(),
        totalCents = summary.totalCents,
    )
}

On iOS there is a wrinkle you should understand before committing to this route. UniFFI’s Swift output is a Swift module, and Kotlin/Native cannot import Swift, only C and Objective-C (Kotlin docs). So the generated Swift is for your SwiftUI layer, not for iosMain. If the Rust calls live at the app edge, that is perfect: define an interface in commonMain, implement it in Swift on top of the generated bindings, and inject it into shared code at startup. Element X works at this altitude. But if commonMain logic itself must call Rust on iOS, you need a C surface, which is route two.

Packaging the generated Swift so it actually builds

The Swift bindgen run above produced three files, not one: KmpCore.swift, the API your app code calls, plus KmpCoreFFI.h and KmpCoreFFI.modulemap, which declare the C symbols that Swift file binds against (UniFFI Swift docs). The build script from earlier packages only the hand-written kmp_core.h, so as written, KmpCore.swift has no KmpCoreFFI module to import and the SwiftUI layer fails to compile. Run the bindgen before the script, then add two copies to scripts/build-ios-core.sh just above the xcodebuild -create-xcframework call:

cp ios/Generated/KmpCoreFFI.h rust/kmp-core/include/
cp ios/Generated/KmpCoreFFI.modulemap rust/kmp-core/include/module.modulemap

The rename in the second copy matters: Xcode only picks up a modulemap inside a framework’s Headers directory when it is named module.modulemap. KmpCore.swift does not go into the framework at all. Add it to your app target as a plain source file.

Route two: expect/actual over JNI and cinterop

For the cinterop route, you write the C header yourself, which is also the discipline that keeps the surface small. This is rust/kmp-core/include/kmp_core.h, the same directory the XCFramework script already packages:

#pragma once

#include <stdint.h>
#include <stddef.h>

int64_t kmp_core_sum_cents(const int64_t *amounts, size_t len);

Kotlin/Native learns about it through a definition file at shared/src/nativeInterop/cinterop/kmpcore.def:

headers = kmp_core.h
package = dev.davthecoder.rustseries.cinterop

The wiring goes inside the kotlin block of shared/build.gradle.kts: each iOS target gets the cinterop for stub generation and a linker path to its matching Rust slice:

listOf(
    iosArm64() to "aarch64-apple-ios",
    iosSimulatorArm64() to "aarch64-apple-ios-sim",
    iosX64() to "x86_64-apple-ios",
).forEach { (iosTarget, rustTriple) ->
    iosTarget.compilations.getByName("main").cinterops.create("kmpcore") {
        definitionFile.set(project.file("src/nativeInterop/cinterop/kmpcore.def"))
        includeDirs(rootDir.resolve("rust/kmp-core/include"))
    }
    iosTarget.binaries.framework {
        baseName = "Shared"
        isStatic = true
        linkerOpts(
            "-L${rootDir.resolve("target/$rustTriple/release")}",
            "-lkmp_core",
        )
    }
}

Now iosMain can call the Rust function directly. The actual lives at shared/src/iosMain/kotlin/dev/davthecoder/rustseries/ReceiptCore.ios.kt:

package dev.davthecoder.rustseries

import dev.davthecoder.rustseries.cinterop.kmp_core_sum_cents
import kotlinx.cinterop.ExperimentalForeignApi
import kotlinx.cinterop.convert
import kotlinx.cinterop.toCValues

@OptIn(ExperimentalForeignApi::class)
actual fun summarizeReceipts(amountsCents: List<Long>): Receipts {
    val total = kmp_core_sum_cents(
        amountsCents.toLongArray().toCValues(),
        amountsCents.size.convert(),
    )
    return Receipts(items = amountsCents.size, totalCents = total)
}

The item count never crosses, because it never needed Rust. Hand-written C APIs push you toward flat buffers and primitive returns, the same instincts Part 6 built for JNI. That is fine for a handful of entry points. The moment your API grows records, errors, and callbacks on both platforms, maintaining a C header plus two hand bridges costs more than UniFFI’s generated code.

When to skip Rust entirely

After fourteen parts of machinery, here are the situations where I would tell you not to use any of it.

  • Your app is a thin client over an API. CRUD screens, forms, a backend that does the real work. There is no compute for Rust to accelerate. KMP alone shares everything worth sharing, and KMP already reaches platforms as far out as tvOS without a line of native code.
  • Nobody on the team has shipped Rust. Google’s own retraining data says about a third of C++ developers feel productive in Rust within two months and about half within four (The Register, 2024). That is a real cost even for teams already writing native code. Starting from Kotlin only, it is larger, and it buys nothing without a native bottleneck to spend it on.
  • Kotlin already has the library. kotlinx.serialization, Ktor, SQLDelight, and the coroutine ecosystem cover most app infrastructure well. Part 11 was explicit that serde only wins past a measured payload threshold. Rewriting working Kotlin in Rust for purity is negative engineering. Most of what makes a mobile product, auth, billing, sync, storage, lives in the shared Kotlin layer.
  • You ship one platform. The shared-core argument is the strongest reason to accept FFI complexity. Android-only, a plain Kotlin app, or Kotlin plus a small JNI crate where profiling demands it, beats a KMP and Rust sandwich you built for an iOS app that does not exist yet.
  • You cannot own an FFI boundary for years. The disciplines from Part 7, Part 8, and Part 9 are a permanent tax on every change that crosses the border. If the team cannot budget for that maintenance, the boundary will rot into the crash reports it was supposed to prevent.

The rule from the hub post has not moved in fifteen parts: Kotlin stays the default, and native code enters only after profiling proves the JVM is the wall. Rust changed which language wins once you pass that gate. It did not move the gate.

The series, start to finish

Here is the full spine, in reading order:

  1. The Complete Rust Toolchain Setup for Android: rustup, cargo-ndk, and Your First .so in an APK
  2. Calling Rust from Kotlin: JNI Basics for Android Developers
  3. UniFFI: Kotlin Bindings for Rust Without Writing JNI by Hand
  4. Project Structure: Gradle + Cargo in One Build, ABI Splits, Debug/Release Flavors
  5. Fast Image Processing on Android with Rust: Bitmaps, Filters, and the JNI Fast Path
  6. Passing Data Between Kotlin and Rust: Strings, Arrays, ByteBuffers, and Zero-Copy
  7. Memory Management Across JNI: Ownership, Box::into_raw, Global Refs, and Leaks
  8. Error Handling and Panics: Keeping Rust Crashes Out of Your Android App
  9. Threading and Async: Tokio, Kotlin Coroutines, and Calling Back Into Kotlin from Rust
  10. Low-Latency Audio DSP with Rust: AAudio and Oboe from a Rust Core
  11. Heavy Parsing with Serde: Offloading JSON and CSV Crunching to Rust
  12. Cryptography with Rust on Android: ring and RustCrypto Instead of Rolling Your Own
  13. Binary Size and the 16KB Page Requirement: Optimizing Rust .so Files for Release
  14. CI/CD for Rust + Android: GitHub Actions, Cross-Compilation Caching, Reproducible Builds
  15. Rust in Kotlin Multiplatform: One Native Core for Android and iOS, and When to Skip Rust Entirely, this post.

Frequently Asked Questions

Do I need a Mac to build the iOS side of a Rust KMP core?

Yes. Cross-compiling the Rust itself to Apple targets needs the Apple SDKs, and packaging the XCFramework requires xcodebuild, which only runs on macOS. In practice that means a macOS job in your CI matrix, the same runner split as Part 14.

Fifteen parts later

This series opened with an empty crate and a single cargo ndk command. It closes with that same crate compiled for a second operating system, still without Google’s blessing and still without leaving Kotlin.

The upcoming book covers a shared Rust core for Android, iOS, and other platforms. The book page is the place for that. The hub post has the map of all fifteen parts.

Sources

Jaga: