Skip to content

LanguageIdiomaภาษา

UniFFI: Kotlin Bindings for Rust Without Writing JNI by Hand

UniFFI: Kotlin Bindings for Rust Without Writing JNI by HandUniFFI: bindings de Kotlin para Rust sin escribir JNI a manoUniFFI: Kotlin Binding สำหรับ Rust โดยไม่ต้องเขียน JNI เอง

Rust & NativeRust y nativoRust และเนทีฟ

ByPorโดย David Cruz Anaya, Mobile & Applied AI EngineerIngeniero sénior de móvil e IA aplicada (Android, Kotlin Multiplatform, IA de producto)วิศวกรมือถือและ AI ประยุกต์ระดับอาวุโส (Android, Kotlin Multiplatform, AI ของผลิตภัณฑ์)

Updated 7 August 2026Actualizado el 7 de agosto de 2026อัปเดตเมื่อ 7 สิงหาคม 202610 min read10 min de lecturaอ่าน 10 นาที
AndroidRustNDKUniFFIKotlinFFI
Share:Compartir:แชร์:

Rust + NDK on Android, Part 3 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: Calling Rust from Kotlin: JNI Basics for Android Developers. Next: Project Structure: Gradle + Cargo in One Build, ABI Splits, Debug/Release Flavors.

You don’t have to write another Java_dev_davthecoder_rustseries_... symbol by hand to call Rust from Kotlin. UniFFI, Mozilla’s binding generator, reads annotations on your Rust code and generates the entire Kotlin side of the bridge: data classes for your structs, enum classes for your enums, a sealed exception hierarchy for your error types. Functions come out as plain camelCase Kotlin that throws a typed exception wherever the Rust returns a Result. You write the Rust and run one generator, and the border paperwork from Part 2 is gone.

In Part 2 I made you write that paperwork on purpose, because you can’t debug a bridge you’ve never seen. This part solves the same problem the comfortable way: we annotate a small expense parser crate with UniFFI’s proc macros, generate the Kotlin bindings, wire generation into the Gradle build, and then compare the two approaches without romance. This assumes the toolchain from Part 1. Everything below is pinned to uniffi 0.29.

Key Takeaways

  • UniFFI generates the whole Kotlin side of a Rust API: records become data classes, enums become enum classes, error enums become sealed exception hierarchies, and Result returns become thrown exceptions.
  • No UDL file is required anymore. #[uniffi::export], three derives and uniffi::setup_scaffolding!() describe functions, records, enums and errors directly in the Rust source (UniFFI proc macro docs).
  • The generated Kotlin calls Rust through JNA, version 5.12.0 or newer, and every argument is serialized across the boundary, so hot per-frame call paths remain hand-written JNI territory (UniFFI Kotlin docs).
  • From here the series uses raw JNI where the point is to see the machinery, and recommends UniFFI for production apps with a wide API surface.

What UniFFI generates and why it exists

The three functions in Part 2 cost roughly sixty lines of glue: a mangled symbol per function, two conversions per string, and a manual repack of every return value. That tax is flat per function, and the glue is exactly where JNI crashes live. Now scale it to a real product: forty functions, a dozen types, and an iOS app that wants the same core through Swift. Hand-written JNI grows linearly in the worst currency there is: unsafe boilerplate a reviewer must re-verify on every change.

UniFFI is Mozilla’s answer to that bill. It was built to ship Rust components inside Firefox for Android and iOS, and several apps in the production table of the hub post cross the same bridge: Element X drives its whole Matrix engine through UniFFI-generated Kotlin and Swift, and Wire and Bitwarden ship their crypto cores the same way.

Two halves get generated. On the Rust side, the macros expand into scaffolding: C ABI functions that receive serialized arguments, call your real functions, and serialize the results back. On the Kotlin side, a generator called uniffi-bindgen writes one Kotlin file containing your types plus all the deserialization code, and it loads your .so through JNA the first time you touch the API. Between the halves sits a small serialization protocol: primitives cross directly, everything else is packed into a byte buffer on one side and unpacked on the other. It’s plain code generation all the way down, which is what makes the costs predictable.

The Rust side: one macro and three derives

The crate lives at rust/uniffi-demo and stands alone for now; Part 4 moves the series crates into one Cargo workspace and adjusts the paths. Here is the complete rust/uniffi-demo/Cargo.toml:

[package]
name = "uniffi-demo"
version = "0.1.0"
edition = "2021"

[lib]
name = "uniffi_demo"
crate-type = ["cdylib", "lib"]

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

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

cdylib produces the .so for Android, and lib lets tests and the binary target link against the crate. The odd part is that [[bin]] section: the crate ships its own copy of the binding generator, and the whole of rust/uniffi-demo/uniffi-bindgen.rs is this:

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

The reason is version discipline: the generated Kotlin and the uniffi runtime compiled into your .so must come from the same release, and building the generator from the same Cargo.lock makes drift impossible.

Now the API itself, the complete rust/uniffi-demo/src/lib.rs. It parses expense lines like "Lidl;12.99;groceries" into a typed record:

uniffi::setup_scaffolding!();

#[derive(uniffi::Record)]
pub struct Expense {
    pub merchant: String,
    pub cents: i64,
    pub category: Category,
}

#[derive(uniffi::Enum)]
pub enum Category {
    Groceries,
    Transport,
    Other,
}

#[derive(Debug, uniffi::Error)]
pub enum ParseError {
    Empty,
    BadAmount { raw: String },
}

impl std::fmt::Display for ParseError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ParseError::Empty => write!(f, "input line was empty"),
            ParseError::BadAmount { raw } => write!(f, "could not parse amount: {raw}"),
        }
    }
}

impl std::error::Error for ParseError {}

#[uniffi::export]
pub fn parse_expense(line: String) -> Result<Expense, ParseError> {
    let line = line.trim();
    if line.is_empty() {
        return Err(ParseError::Empty);
    }
    let mut parts = line.split(';');
    let merchant = parts.next().unwrap_or("").trim().to_string();
    let raw_amount = parts.next().unwrap_or("").trim();
    let cents = parse_cents(raw_amount).ok_or(ParseError::BadAmount {
        raw: raw_amount.to_string(),
    })?;
    let category = match parts.next().map(|p| p.trim().to_ascii_lowercase()).as_deref() {
        Some("groceries") => Category::Groceries,
        Some("transport") => Category::Transport,
        _ => Category::Other,
    };
    Ok(Expense { merchant, cents, category })
}

#[uniffi::export]
pub fn total_cents(expenses: Vec<Expense>) -> i64 {
    expenses.iter().map(|e| e.cents).sum()
}

fn parse_cents(raw: &str) -> Option<i64> {
    let (whole, frac) = match raw.split_once('.') {
        Some((whole, frac)) => (whole, frac),
        None => (raw, ""),
    };
    if whole.is_empty() || whole.starts_with('-') {
        return None;
    }
    let whole: i64 = whole.parse().ok()?;
    let frac: i64 = match frac.len() {
        0 => 0,
        1 => frac.parse::<i64>().ok()? * 10,
        2 => frac.parse().ok()?,
        _ => return None,
    };
    Some(whole * 100 + frac)
}

Four annotations carry the entire interface. uniffi::setup_scaffolding!() at the top replaces the UDL file and build.rs step that older tutorials revolve around; when your whole API is described by macros, it’s the only setup you need (UniFFI proc macro docs). #[derive(uniffi::Record)] marks a plain data holder that crosses the boundary by value, and #[derive(uniffi::Enum)] does the same for the enum inside it.

The error type earns the most attention. UniFFI requires error enums to implement std::error::Error (UniFFI error docs), which is why the two small impl blocks are there: Display provides the exception message Kotlin will see, and the variant fields, like raw, cross the boundary as typed properties. Returning Result<Expense, ParseError> is the complete error story on the Rust side. You never touch a JNIEnv and you never throw an exception by hand, so there is nothing to get wrong at 2am. What happens when Rust panics instead of returning an Err is a different story, and it gets its own post, Error Handling and Panics: Keeping Rust Crashes Out of Your Android App.

There is no symbol naming rule anywhere in this file. Rename the Kotlin package tomorrow and not one line of Rust changes.

The generated Kotlin and how it reads

One small config file controls the Kotlin output. This is rust/uniffi-demo/uniffi.toml:

[bindings.kotlin]
package_name = "dev.davthecoder.rustseries.uniffi"

Build the .so files exactly as in Part 1, then point the generator at the compiled library. This is called library mode: the generator reads metadata the macros embedded in the binary, so it never parses your source:

cd rust/uniffi-demo
cargo ndk -t arm64-v8a -t armeabi-v7a -t x86_64 -t x86 \
  -o ../../app/src/main/jniLibs build --release
cargo run --bin uniffi-bindgen -- generate \
  --library target/aarch64-linux-android/release/libuniffi_demo.so \
  --language kotlin \
  --out-dir ../../app/build/generated/uniffi

Out comes a single file, uniffi_demo.kt, in the package you configured. It’s a few hundred lines of serialization code you never edit, and its public surface maps one to one onto the Rust: a data class Expense, an enum class Category with GROCERIES, TRANSPORT and OTHER, and a sealed ParseException hierarchy, since UniFFI renames a Rust FooError to a Kotlin FooException. The two functions arrive as parseExpense, marked @Throws(ParseException::class), and totalCents. There’s no System.loadLibrary call for you to write either: the generated file loads libuniffi_demo.so itself.

Here’s the consuming side, app/src/main/java/dev/davthecoder/rustseries/ExpenseDemo.kt:

package dev.davthecoder.rustseries

import dev.davthecoder.rustseries.uniffi.Category
import dev.davthecoder.rustseries.uniffi.Expense
import dev.davthecoder.rustseries.uniffi.ParseException
import dev.davthecoder.rustseries.uniffi.parseExpense
import dev.davthecoder.rustseries.uniffi.totalCents

object ExpenseDemo {

    fun run(): String {
        val groceries: Expense = parseExpense("Lidl;12.99;groceries")
        val transport: Expense = parseExpense("BVG;3.80;transport")

        check(groceries.category == Category.GROCERIES)
        check(totalCents(listOf(groceries, transport)) == 1679L)

        return try {
            parseExpense("Lidl;twelve;groceries")
            "unreachable"
        } catch (e: ParseException.BadAmount) {
            "rejected amount: ${e.raw}"
        } catch (e: ParseException) {
            "parse failed: ${e.message}"
        }
    }
}

That catch block is the part hand-written JNI never gives you for free. ParseException.BadAmount is a real type with a real raw property, so the compiler checks your error handling, and when over the sealed hierarchy is exhaustive. In Part 2 the equivalent was a returned sentinel value and a prayer.

Wiring UniFFI into an Android Gradle build

The bindings need JNA at runtime, version 5.12.0 or newer per the UniFFI Kotlin docs. Add it to the dependencies block of app/build.gradle.kts:

dependencies {
    implementation("net.java.dev.jna:jna:5.12.0@aar")
}

Then wire two Exec tasks into the same file: one builds the .so files with cargo-ndk, the next generates the bindings from the arm64 library, and both hang off preBuild so a plain ./gradlew assembleDebug does everything. Generating into build/generated and registering that directory as a source root keeps generated code out of src/ and out of git:

val rustCrateDir = rootProject.file("rust/uniffi-demo")
val uniffiOutDir = layout.buildDirectory.dir("generated/uniffi")

val cargoNdkBuild = tasks.register<Exec>("cargoNdkBuild") {
    workingDir(rustCrateDir)
    commandLine(
        "cargo", "ndk",
        "-t", "arm64-v8a", "-t", "armeabi-v7a", "-t", "x86_64", "-t", "x86",
        "-o", project.file("src/main/jniLibs").absolutePath,
        "build", "--release",
    )
}

val generateUniffiBindings = tasks.register<Exec>("generateUniffiBindings") {
    dependsOn(cargoNdkBuild)
    workingDir(rustCrateDir)
    commandLine(
        "cargo", "run", "--bin", "uniffi-bindgen", "--",
        "generate",
        "--library", "target/aarch64-linux-android/release/libuniffi_demo.so",
        "--language", "kotlin",
        "--out-dir", uniffiOutDir.get().asFile.absolutePath,
    )
}

tasks.named("preBuild") {
    dependsOn(generateUniffiBindings)
}

android {
    sourceSets {
        getByName("main") {
            java.srcDir(uniffiOutDir)
        }
    }
}

This is the blunt version. It shells out to cargo on every build and knows nothing about build types or flavors; cargo’s own caching keeps the no-change case quick, but Gradle can’t skip the tasks because they declare no inputs or outputs. Making Gradle and Cargo behave like one incremental build, with debug and release profiles mapped properly and ABI splits for Play, is the whole of Part 4, Project Structure: Gradle + Cargo in One Build, ABI Splits, Debug/Release Flavors.

UniFFI vs hand-written JNI: where each wins

You’ve now shipped the same shape of API both ways.

Hand-written JNI (Part 2) UniFFI (this post)
Cost per function Manual symbol, conversions, checks One annotation
Rich types Manual marshalling both directions Records, enums, errors generated
Error handling Sentinels or hand-thrown exceptions Typed sealed exceptions
Call overhead Direct call, primitives cross free Serialization plus JNA dispatch
Zero-copy options Direct ByteBuffers, array pinning None, the protocol copies
Extra dependencies None beyond your .so JNA plus generated runtime
Other platforms Rewrite per language Swift and Python from the same crate

Every UniFFI call packs its arguments into a buffer, crosses through JNA, and unpacks on the far side, and the return value makes the same trip in reverse. For a login call, a parser, or a sync engine you will never feel it. For a function called per frame with a bitmap-sized payload, you will. I’m not going to invent numbers here; the series puts real measurements on the boundary in Fast Image Processing on Android with Rust: Bitmaps, Filters, and the JNI Fast Path. Until then the working rule is simple: coarse calls belong to UniFFI, hot loops belong to JNI you control. Zero-copy follows the same logic: raw JNI offers direct ByteBuffer access and array pinning, covered in Passing Data Between Kotlin and Rust: Strings, Arrays, ByteBuffers, and Zero-Copy, while UniFFI’s protocol copies by design.

UniFFI adds the JNA native library to every ABI you ship plus the generated runtime code, where hand JNI adds nothing beyond your own .so. And the generated bindings are welded to the uniffi version in your Cargo.lock: bump the crate and you must regenerate, which the Gradle wiring above does for you on every build anyway.

For a real product with a wide API, that ledger still tilts hard toward UniFFI. You give up a copy cost you mostly can’t measure and get back compiler-checked errors, far less unsafe glue, and Swift bindings from the same annotations. So here is the convention for the rest of this series. Teaching posts stay on raw JNI, because the machinery is the lesson. Posts about squeezing the boundary also stay on JNI, because control is the point. For a production app with more than a handful of exported functions, use UniFFI.

Frequently Asked Questions

Do I need a UDL file to use UniFFI on Android?

No. Older tutorials are built around a .udl interface file and a build.rs scaffolding step, but the proc macro interface covers functions, records, enums, errors and objects, and uniffi::setup_scaffolding!() replaces the build script entirely (UniFFI proc macro docs). UDL remains supported, and a few features still appear there first, but a new Android project doesn’t need it.

Does UniFFI use JNI under the hood?

Indirectly. The generated Kotlin reaches your Rust through JNA, which itself rides on JNI to call native code (UniFFI Kotlin docs). You write none of that layer, but it exists, and it’s the reason a UniFFI call costs more than the direct hand-written JNI call from Part 2.

Can UniFFI generate suspend functions for Kotlin coroutines?

Yes. An async fn behind #[uniffi::export] becomes a Kotlin suspend function, with a kotlinx-coroutines dependency on the Kotlin side. Runtimes, threading and calling back into Kotlin from Rust are a topic of their own, covered in Threading and Async: Tokio, Kotlin Coroutines, and Calling Back Into Kotlin from Rust.

The wiring above works, but it rebuilds too eagerly and knows nothing about flavors. Part 4, Project Structure: Gradle + Cargo in One Build, ABI Splits, Debug/Release Flavors, turns it into a build you can live with every day. And if you landed here from a search result rather than from Part 1, the hub post has the map of the whole series.

Sources

Rust + NDK on Android, Part 3 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: Calling Rust from Kotlin: JNI Basics for Android Developers. Next: Project Structure: Gradle + Cargo in One Build, ABI Splits, Debug/Release Flavors.

No tienes que escribir a mano otro símbolo Java_dev_davthecoder_rustseries_... para llamar a Rust desde Kotlin. UniFFI, el generador de bindings de Mozilla, lee las anotaciones de tu código Rust y genera todo el lado Kotlin del puente: data classes para tus structs, enum classes para tus enums y una jerarquía de excepciones sellada para tus tipos de error. Las funciones salen como Kotlin camelCase normal, que lanza una excepción tipada allá donde Rust devuelve un Result. Escribes el Rust, ejecutas un generador, y el papeleo de la frontera de la parte 2 desaparece.

En la parte 2 te hice escribir ese papeleo a propósito, porque no puedes depurar un puente que no has visto nunca. Esta parte resuelve el mismo problema por la vía cómoda: anotamos un crate pequeño de parseo de gastos con las proc macros de UniFFI, generamos los bindings de Kotlin, enganchamos la generación al build de Gradle y luego comparamos los dos enfoques sin romanticismos. Esto da por hecha la cadena de herramientas de la parte 1. Todo lo que sigue está fijado a uniffi 0.29.

Ideas clave

  • UniFFI genera todo el lado Kotlin de una API de Rust: los records se vuelven data classes, los enums se vuelven enum classes, los enums de error se vuelven jerarquías de excepciones selladas y los Result se vuelven excepciones lanzadas.
  • Ya no hace falta un fichero UDL. #[uniffi::export], tres derives y uniffi::setup_scaffolding!() describen funciones, records, enums y errores directamente en el fuente de Rust (documentación de proc macros de UniFFI).
  • El Kotlin generado llama a Rust a través de JNA, versión 5.12.0 o posterior, y cada argumento se serializa al cruzar la frontera, así que las rutas de llamada calientes por fotograma siguen siendo territorio del JNI escrito a mano (documentación de Kotlin de UniFFI).
  • A partir de aquí, la serie usa JNI crudo cuando el objetivo es ver la maquinaria, y recomienda UniFFI para aplicaciones de producción con una superficie de API amplia.

Qué genera UniFFI y por qué existe

Las tres funciones de la parte 2 costaron unas sesenta líneas de pegamento: un símbolo con el nombre machacado por función, dos conversiones por cadena y un reempaquetado manual de cada valor de retorno. Ese impuesto es fijo por función, y el pegamento es justo donde viven los crashes de JNI. Ahora escálalo a un producto de verdad: cuarenta funciones, una docena de tipos y una aplicación de iOS que quiere el mismo núcleo a través de Swift. El JNI escrito a mano crece de forma lineal en la peor moneda que existe: código repetitivo unsafe que quien revisa tiene que volver a verificar en cada cambio.

UniFFI es la respuesta de Mozilla a esa factura. Se construyó para publicar componentes de Rust dentro de Firefox para Android e iOS, y varias aplicaciones de la tabla de producción del artículo central cruzan el mismo puente: Element X mueve todo su motor de Matrix a través de Kotlin y Swift generados por UniFFI, y Wire y Bitwarden publican sus núcleos criptográficos del mismo modo.

Se generan dos mitades. En el lado Rust, las macros se expanden en andamiaje: funciones de ABI de C que reciben argumentos serializados, llaman a tus funciones reales y serializan los resultados de vuelta. En el lado Kotlin, un generador llamado uniffi-bindgen escribe un fichero Kotlin con tus tipos más todo el código de deserialización, y carga tu .so a través de JNA la primera vez que tocas la API. Entre las dos mitades hay un protocolo de serialización pequeño: los primitivos cruzan directamente, y todo lo demás se empaqueta en un búfer de bytes en un lado y se desempaqueta en el otro. Es generación de código de principio a fin, y por eso los costes son predecibles.

El lado Rust: una macro y tres derives

El crate vive en rust/uniffi-demo y, de momento, va por libre; la parte 4 mete los crates de la serie en un único workspace de Cargo y ajusta las rutas. Este es el rust/uniffi-demo/Cargo.toml completo:

[package]
name = "uniffi-demo"
version = "0.1.0"
edition = "2021"

[lib]
name = "uniffi_demo"
crate-type = ["cdylib", "lib"]

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

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

cdylib produce el .so para Android, y lib permite que los tests y el binario enlacen contra el crate. La parte rara es esa sección [[bin]]: el crate lleva su propia copia del generador de bindings, y todo rust/uniffi-demo/uniffi-bindgen.rs es esto:

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

La razón es la disciplina de versiones: el Kotlin generado y el runtime de uniffi compilado dentro de tu .so tienen que salir de la misma versión, y construir el generador desde el mismo Cargo.lock hace imposible que se desfasen.

Ahora la API en sí, el rust/uniffi-demo/src/lib.rs completo. Parsea líneas de gasto como "Lidl;12.99;groceries" y las convierte en un record tipado:

uniffi::setup_scaffolding!();

#[derive(uniffi::Record)]
pub struct Expense {
    pub merchant: String,
    pub cents: i64,
    pub category: Category,
}

#[derive(uniffi::Enum)]
pub enum Category {
    Groceries,
    Transport,
    Other,
}

#[derive(Debug, uniffi::Error)]
pub enum ParseError {
    Empty,
    BadAmount { raw: String },
}

impl std::fmt::Display for ParseError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ParseError::Empty => write!(f, "input line was empty"),
            ParseError::BadAmount { raw } => write!(f, "could not parse amount: {raw}"),
        }
    }
}

impl std::error::Error for ParseError {}

#[uniffi::export]
pub fn parse_expense(line: String) -> Result<Expense, ParseError> {
    let line = line.trim();
    if line.is_empty() {
        return Err(ParseError::Empty);
    }
    let mut parts = line.split(';');
    let merchant = parts.next().unwrap_or("").trim().to_string();
    let raw_amount = parts.next().unwrap_or("").trim();
    let cents = parse_cents(raw_amount).ok_or(ParseError::BadAmount {
        raw: raw_amount.to_string(),
    })?;
    let category = match parts.next().map(|p| p.trim().to_ascii_lowercase()).as_deref() {
        Some("groceries") => Category::Groceries,
        Some("transport") => Category::Transport,
        _ => Category::Other,
    };
    Ok(Expense { merchant, cents, category })
}

#[uniffi::export]
pub fn total_cents(expenses: Vec<Expense>) -> i64 {
    expenses.iter().map(|e| e.cents).sum()
}

fn parse_cents(raw: &str) -> Option<i64> {
    let (whole, frac) = match raw.split_once('.') {
        Some((whole, frac)) => (whole, frac),
        None => (raw, ""),
    };
    if whole.is_empty() || whole.starts_with('-') {
        return None;
    }
    let whole: i64 = whole.parse().ok()?;
    let frac: i64 = match frac.len() {
        0 => 0,
        1 => frac.parse::<i64>().ok()? * 10,
        2 => frac.parse().ok()?,
        _ => return None,
    };
    Some(whole * 100 + frac)
}

Cuatro anotaciones cargan con toda la interfaz. uniffi::setup_scaffolding!() arriba del todo sustituye el fichero UDL y el paso de build.rs alrededor de los que giran los tutoriales antiguos; cuando toda tu API la describen macros, es la única preparación que necesitas (documentación de proc macros de UniFFI). #[derive(uniffi::Record)] marca un contenedor de datos plano que cruza la frontera por valor, y #[derive(uniffi::Enum)] hace lo mismo con el enum que lleva dentro.

El tipo de error es el que más atención se merece. UniFFI exige que los enums de error implementen std::error::Error (documentación de errores de UniFFI), y por eso están esos dos impl pequeños: Display aporta el mensaje de la excepción que verá Kotlin, y los campos de la variante, como raw, cruzan la frontera como propiedades tipadas. Devolver Result<Expense, ParseError> es toda la historia de errores en el lado Rust. Nunca tocas un JNIEnv y nunca lanzas una excepción a mano, así que no hay nada que puedas hacer mal a las dos de la madrugada. Qué pasa cuando Rust entra en pánico en lugar de devolver un Err es otra historia, y tiene su propio artículo: Gestión de errores y pánicos: cómo mantener los cierres de Rust fuera de tu aplicación Android.

En este fichero no hay ninguna regla para nombrar símbolos. Cambia mañana el paquete de Kotlin y no se mueve ni una línea de Rust.

El Kotlin generado y cómo se lee

Un fichero de configuración pequeño controla la salida de Kotlin. Este es rust/uniffi-demo/uniffi.toml:

[bindings.kotlin]
package_name = "dev.davthecoder.rustseries.uniffi"

Construye los .so exactamente como en la parte 1 y luego apunta el generador a la biblioteca compilada. Esto se llama modo library: el generador lee los metadatos que las macros incrustaron en el binario, así que nunca parsea tu fuente:

cd rust/uniffi-demo
cargo ndk -t arm64-v8a -t armeabi-v7a -t x86_64 -t x86 \
  -o ../../app/src/main/jniLibs build --release
cargo run --bin uniffi-bindgen -- generate \
  --library target/aarch64-linux-android/release/libuniffi_demo.so \
  --language kotlin \
  --out-dir ../../app/build/generated/uniffi

Sale un único fichero, uniffi_demo.kt, en el paquete que configuraste. Son unos cientos de líneas de código de serialización que no editas nunca, y su superficie pública se corresponde una a una con la de Rust: una data class Expense, una enum class Category con GROCERIES, TRANSPORT y OTHER, y una jerarquía sellada ParseException, porque UniFFI renombra un FooError de Rust a un FooException de Kotlin. Las dos funciones llegan como parseExpense, marcada con @Throws(ParseException::class), y totalCents. Tampoco tienes que escribir tú ninguna llamada a System.loadLibrary: el fichero generado carga libuniffi_demo.so él solo.

Este es el lado que lo consume, app/src/main/java/dev/davthecoder/rustseries/ExpenseDemo.kt:

package dev.davthecoder.rustseries

import dev.davthecoder.rustseries.uniffi.Category
import dev.davthecoder.rustseries.uniffi.Expense
import dev.davthecoder.rustseries.uniffi.ParseException
import dev.davthecoder.rustseries.uniffi.parseExpense
import dev.davthecoder.rustseries.uniffi.totalCents

object ExpenseDemo {

    fun run(): String {
        val groceries: Expense = parseExpense("Lidl;12.99;groceries")
        val transport: Expense = parseExpense("BVG;3.80;transport")

        check(groceries.category == Category.GROCERIES)
        check(totalCents(listOf(groceries, transport)) == 1679L)

        return try {
            parseExpense("Lidl;twelve;groceries")
            "unreachable"
        } catch (e: ParseException.BadAmount) {
            "rejected amount: ${e.raw}"
        } catch (e: ParseException) {
            "parse failed: ${e.message}"
        }
    }
}

Ese bloque catch es la parte que el JNI escrito a mano no te regala nunca. ParseException.BadAmount es un tipo de verdad, con una propiedad raw de verdad, así que el compilador comprueba tu gestión de errores, y un when sobre la jerarquía sellada es exhaustivo. En la parte 2 el equivalente era un valor centinela devuelto y un rezo.

Enganchar UniFFI a un build de Gradle en Android

Los bindings necesitan JNA en tiempo de ejecución, versión 5.12.0 o posterior según la documentación de Kotlin de UniFFI. Añádelo al bloque de dependencias de app/build.gradle.kts:

dependencies {
    implementation("net.java.dev.jna:jna:5.12.0@aar")
}

Luego engancha dos tareas Exec en el mismo fichero: una construye los .so con cargo-ndk, la siguiente genera los bindings a partir de la biblioteca arm64, y las dos cuelgan de preBuild para que un simple ./gradlew assembleDebug lo haga todo. Generar dentro de build/generated y registrar ese directorio como raíz de fuentes mantiene el código generado fuera de src/ y fuera de git:

val rustCrateDir = rootProject.file("rust/uniffi-demo")
val uniffiOutDir = layout.buildDirectory.dir("generated/uniffi")

val cargoNdkBuild = tasks.register<Exec>("cargoNdkBuild") {
    workingDir(rustCrateDir)
    commandLine(
        "cargo", "ndk",
        "-t", "arm64-v8a", "-t", "armeabi-v7a", "-t", "x86_64", "-t", "x86",
        "-o", project.file("src/main/jniLibs").absolutePath,
        "build", "--release",
    )
}

val generateUniffiBindings = tasks.register<Exec>("generateUniffiBindings") {
    dependsOn(cargoNdkBuild)
    workingDir(rustCrateDir)
    commandLine(
        "cargo", "run", "--bin", "uniffi-bindgen", "--",
        "generate",
        "--library", "target/aarch64-linux-android/release/libuniffi_demo.so",
        "--language", "kotlin",
        "--out-dir", uniffiOutDir.get().asFile.absolutePath,
    )
}

tasks.named("preBuild") {
    dependsOn(generateUniffiBindings)
}

android {
    sourceSets {
        getByName("main") {
            java.srcDir(uniffiOutDir)
        }
    }
}

Esta es la versión directa, sin florituras. Llama a cargo en cada build y no sabe nada de tipos de build ni de flavors; la caché del propio cargo mantiene rápido el caso en el que no hay cambios, pero Gradle no puede saltarse las tareas porque no declaran entradas ni salidas. Hacer que Gradle y Cargo se comporten como un único build incremental, con los perfiles de debug y release bien mapeados y los cortes de ABI para Play, es toda la parte 4, Estructura del proyecto: Gradle y Cargo en un solo build, cortes de ABI y flavors de debug y release.

UniFFI frente a JNI escrito a mano: dónde gana cada uno

Ya has publicado la misma forma de API por los dos caminos.

JNI escrito a mano (parte 2) UniFFI (este artículo)
Coste por función Símbolo, conversiones y comprobaciones manuales Una anotación
Tipos ricos Marshalling manual en las dos direcciones Records, enums y errores generados
Gestión de errores Centinelas o excepciones lanzadas a mano Excepciones selladas y tipadas
Sobrecoste de la llamada Llamada directa; los primitivos cruzan gratis Serialización más el despacho de JNA
Opciones de copia cero ByteBuffers directos y fijación de arrays Ninguna: el protocolo copia
Dependencias extra Ninguna, aparte de tu .so JNA más el runtime generado
Otras plataformas Reescribir por lenguaje Swift y Python desde el mismo crate

Cada llamada de UniFFI empaqueta sus argumentos en un búfer, cruza a través de JNA y los desempaqueta al otro lado, y el valor de retorno hace el mismo viaje a la inversa. En una llamada de login, un parser o un motor de sincronización no lo vas a notar nunca. En una función a la que llamas por fotograma con una carga del tamaño de un bitmap, sí. No voy a inventar cifras aquí; la serie pone mediciones reales sobre la frontera en Procesado rápido de imágenes en Android con Rust: bitmaps, filtros y la vía rápida de JNI. Hasta entonces, la regla de trabajo es simple: las llamadas de grano grueso son de UniFFI, y los bucles calientes son de un JNI que controlas tú. La copia cero sigue la misma lógica: el JNI crudo ofrece acceso directo a ByteBuffer y fijación de arrays, que se cubre en Pasar datos entre Kotlin y Rust: cadenas, arrays, ByteBuffers y copia cero, mientras que el protocolo de UniFFI copia por diseño.

UniFFI añade la biblioteca nativa de JNA a cada ABI que publicas, más el código de runtime generado, mientras que el JNI a mano no añade nada más allá de tu propio .so. Y los bindings generados están soldados a la versión de uniffi de tu Cargo.lock: sube el crate y tienes que regenerar, cosa que el enganche de Gradle de arriba hace por ti en cada build de todas formas.

Para un producto de verdad con una API amplia, ese balance sigue inclinándose con fuerza hacia UniFFI. Entregas un coste de copia que casi nunca puedes medir y recuperas errores comprobados por el compilador, mucho menos pegamento unsafe y bindings de Swift a partir de las mismas anotaciones. Así que esta es la convención para el resto de la serie. Los artículos que enseñan se quedan en JNI crudo, porque la maquinaria es la lección. Los artículos sobre exprimir la frontera también se quedan en JNI, porque el control es el objetivo. Para una aplicación de producción con más de un puñado de funciones exportadas, usa UniFFI.

Preguntas frecuentes

¿Necesito un fichero UDL para usar UniFFI en Android?

No. Los tutoriales antiguos se construyen alrededor de un fichero de interfaz .udl y un paso de andamiaje en build.rs, pero la interfaz de proc macros cubre funciones, records, enums, errores y objetos, y uniffi::setup_scaffolding!() sustituye por completo al script de build (documentación de proc macros de UniFFI). UDL sigue estando soportado, y algunas funciones siguen apareciendo ahí primero, pero un proyecto de Android nuevo no lo necesita.

¿UniFFI usa JNI por debajo?

De forma indirecta. El Kotlin generado llega a tu Rust a través de JNA, que a su vez se apoya en JNI para llamar a código nativo (documentación de Kotlin de UniFFI). Tú no escribes nada de esa capa, pero existe, y es la razón por la que una llamada de UniFFI cuesta más que la llamada JNI directa escrita a mano de la parte 2.

¿UniFFI puede generar funciones suspend para las corrutinas de Kotlin?

Sí. Una async fn detrás de #[uniffi::export] se convierte en una función suspend de Kotlin, con una dependencia de kotlinx-coroutines en el lado Kotlin. Los runtimes, los hilos y llamar de vuelta a Kotlin desde Rust son un tema aparte, cubierto en Hilos y asincronía: Tokio, corrutinas de Kotlin y cómo llamar de vuelta a Kotlin desde Rust.

El enganche de arriba funciona, pero reconstruye con demasiadas ganas y no sabe nada de flavors. La parte 4, Estructura del proyecto: Gradle y Cargo en un solo build, cortes de ABI y flavors de debug y release, lo convierte en un build con el que puedes convivir cada día. Y si has llegado aquí desde un resultado de búsqueda y no desde la parte 1, el artículo central tiene el mapa de toda la serie.

Fuentes

Rust + NDK on Android, Part 3 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: Calling Rust from Kotlin: JNI Basics for Android Developers. Next: Project Structure: Gradle + Cargo in One Build, ABI Splits, Debug/Release Flavors.

คุณไม่ต้องเขียนสัญลักษณ์ Java_dev_davthecoder_rustseries_... ด้วยมืออีกเพื่อเรียก Rust จาก Kotlin UniFFI ตัวสร้าง binding ของ Mozilla อ่านแอโนเทชันบนโค้ด Rust ของคุณ แล้วสร้างฝั่ง Kotlin ของสะพานทั้งก้อน data class สำหรับ struct, enum class สำหรับ enum, ลำดับชั้น exception แบบ sealed สำหรับชนิด error ของคุณ ฟังก์ชันออกมาเป็น Kotlin แบบ camelCase ธรรมดาที่โยน exception แบบมี type ทุกที่ที่ Rust คืน Result คุณเขียน Rust แล้วรันตัวสร้างหนึ่งครั้ง และเอกสารชายแดนจาก ตอนที่ 2 ก็หายไป

ในตอนที่ 2 ผมให้คุณเขียนเอกสารนั้นโดยตั้งใจ เพราะคุณดีบักสะพานที่คุณไม่เคยเห็นไม่ได้ ตอนนี้แก้ปัญหาเดียวกันแบบสบาย เราใส่แอโนเทชัน crate ตัวแยกบรรทัดค่าใช้จ่ายเล็กๆ ด้วย proc macro ของ UniFFI สร้าง Kotlin binding ผูกการสร้างเข้าบิลด์ Gradle แล้วเทียบสองแนวทางแบบตรงๆ ไม่แต่งเติม บทความนี้สมมติ toolchain จาก ตอนที่ 1 ทุกอย่างด้านล่างปักที่ uniffi 0.29

ประเด็นหลัก

  • UniFFI สร้างฝั่ง Kotlin ทั้งก้อนของ API ของ Rust record กลายเป็น data class, enum กลายเป็น enum class, error enum กลายเป็นลำดับชั้น exception แบบ sealed และการคืน Result กลายเป็น exception ที่ถูกโยน
  • ไม่ต้องมีไฟล์ UDL อีกต่อไป #[uniffi::export], derive สามตัว และ uniffi::setup_scaffolding!() อธิบายฟังก์ชัน record enum และ error ได้ตรงในซอร์ส Rust (เอกสาร proc macro ของ UniFFI)
  • Kotlin ที่สร้างขึ้นเรียก Rust ผ่าน JNA เวอร์ชัน 5.12.0 ขึ้นไป และทุกอาร์กิวเมนต์ถูก serialize ข้ามชายแดน ดังนั้นเส้นเรียกที่ร้อนแบบต่อเฟรมยังเป็นเขตของ JNI ที่เขียนมือ (เอกสาร Kotlin ของ UniFFI)
  • จากตรงนี้ซีรีส์ใช้ JNI ดิบในที่ที่ประเด็นคือการเห็นเครื่องจักร และแนะนำ UniFFI สำหรับแอปโปรดักชันที่มีผิว API กว้าง

UniFFI สร้างอะไร และทำไมมันถึงมีอยู่

สามฟังก์ชันในตอนที่ 2 ใช้กาวราวหกสิบบรรทัด สัญลักษณ์ที่ชื่อบิดเบี้ยวต่อฟังก์ชัน การแปลงสองครั้งต่อสตริง และการแพ็กค่าที่คืนด้วยมือทุกค่า ภาษีนั้นแบนต่อฟังก์ชัน และกาวคือที่ที่ crash ของ JNI อยู่ พอขยายเป็นผลิตภัณฑ์จริง สี่สิบฟังก์ชัน ชนิดเป็นโหล และแอป iOS ที่ต้องการคอร์เดียวกันผ่าน Swift JNI ที่เขียนมือโตเชิงเส้นในสกุลเงินที่แย่ที่สุด คือ boilerplate ที่ไม่ปลอดภัยซึ่งผู้รีวิวต้องตรวจซ้ำทุกครั้งที่เปลี่ยน

UniFFI คือคำตอบของ Mozilla ต่อบิลนั้น มันถูกสร้างเพื่อชิปคอมโพเนนต์ Rust ใน Firefox สำหรับ Android และ iOS และหลายแอปในตารางโปรดักชันของ โพสต์ฮับ ข้ามสะพานเดียวกัน Element X ขับเอนจิน Matrix ทั้งก้อนผ่าน Kotlin และ Swift ที่ UniFFI สร้าง และ Wire กับ Bitwarden ชิปคอร์คริปโตของพวกเขาแบบเดียวกัน

มีสองซีกที่ถูกสร้าง ฝั่ง Rust แมโครขยายเป็นนั่งร้าน ฟังก์ชัน C ABI ที่รับอาร์กิวเมนต์ที่ถูก serialize เรียกฟังก์ชันจริงของคุณ แล้ว serialize ผลกลับ ฝั่ง Kotlin ตัวสร้างชื่อ uniffi-bindgen เขียนไฟล์ Kotlin หนึ่งไฟล์ที่มีชนิดของคุณบวกโค้ด deserialize ทั้งหมด และมันโหลด .so ของคุณผ่าน JNA ครั้งแรกที่คุณแตะ API ระหว่างสองซีกมีโปรโตคอล serialization เล็กๆ primitive ข้ามตรง อย่างอื่นถูกแพ็กลงบัฟเฟอร์ไบต์ฝั่งหนึ่งแล้วแกะอีกฝั่ง มันเป็นการสร้างโค้ดธรรมดาตลอดทาง ซึ่งทำให้ต้นทุนคาดได้

ฝั่ง Rust แมโครหนึ่งตัวและ derive สามตัว

crate อยู่ที่ rust/uniffi-demo และยืนเดี่ยวไปก่อน ตอนที่ 4 ย้าย crate ของซีรีส์เข้า workspace ของ Cargo เดียวแล้วปรับพาธ นี่คือ rust/uniffi-demo/Cargo.toml ทั้งไฟล์

[package]
name = "uniffi-demo"
version = "0.1.0"
edition = "2021"

[lib]
name = "uniffi_demo"
crate-type = ["cdylib", "lib"]

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

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

cdylib สร้าง .so สำหรับ Android และ lib ให้เทสกับเป้าหมายไบนารีลิงก์เข้า crate ได้ ส่วนที่แปลกคือส่วน [[bin]] crate นี้ชิปสำเนาของตัวสร้าง binding ของตัวเอง และทั้งไฟล์ rust/uniffi-demo/uniffi-bindgen.rs คืออันนี้

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

เหตุผลคือวินัยเรื่องเวอร์ชัน Kotlin ที่สร้างขึ้นกับรันไทม์ uniffi ที่ถูกคอมไพล์เข้า .so ของคุณต้องมาจากรีลีสเดียวกัน และการสร้างตัวสร้างจาก Cargo.lock เดียวกันทำให้การเหลื่อมเป็นไปไม่ได้

ต่อไปคือ API เอง คือ rust/uniffi-demo/src/lib.rs ทั้งไฟล์ มันแยกบรรทัดค่าใช้จ่ายแบบ "Lidl;12.99;groceries" เป็น record ที่มี type

uniffi::setup_scaffolding!();

#[derive(uniffi::Record)]
pub struct Expense {
    pub merchant: String,
    pub cents: i64,
    pub category: Category,
}

#[derive(uniffi::Enum)]
pub enum Category {
    Groceries,
    Transport,
    Other,
}

#[derive(Debug, uniffi::Error)]
pub enum ParseError {
    Empty,
    BadAmount { raw: String },
}

impl std::fmt::Display for ParseError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ParseError::Empty => write!(f, "input line was empty"),
            ParseError::BadAmount { raw } => write!(f, "could not parse amount: {raw}"),
        }
    }
}

impl std::error::Error for ParseError {}

#[uniffi::export]
pub fn parse_expense(line: String) -> Result<Expense, ParseError> {
    let line = line.trim();
    if line.is_empty() {
        return Err(ParseError::Empty);
    }
    let mut parts = line.split(';');
    let merchant = parts.next().unwrap_or("").trim().to_string();
    let raw_amount = parts.next().unwrap_or("").trim();
    let cents = parse_cents(raw_amount).ok_or(ParseError::BadAmount {
        raw: raw_amount.to_string(),
    })?;
    let category = match parts.next().map(|p| p.trim().to_ascii_lowercase()).as_deref() {
        Some("groceries") => Category::Groceries,
        Some("transport") => Category::Transport,
        _ => Category::Other,
    };
    Ok(Expense { merchant, cents, category })
}

#[uniffi::export]
pub fn total_cents(expenses: Vec<Expense>) -> i64 {
    expenses.iter().map(|e| e.cents).sum()
}

fn parse_cents(raw: &str) -> Option<i64> {
    let (whole, frac) = match raw.split_once('.') {
        Some((whole, frac)) => (whole, frac),
        None => (raw, ""),
    };
    if whole.is_empty() || whole.starts_with('-') {
        return None;
    }
    let whole: i64 = whole.parse().ok()?;
    let frac: i64 = match frac.len() {
        0 => 0,
        1 => frac.parse::<i64>().ok()? * 10,
        2 => frac.parse().ok()?,
        _ => return None,
    };
    Some(whole * 100 + frac)
}

แอโนเทชันสี่ตัวแบกอินเทอร์เฟซทั้งก้อน uniffi::setup_scaffolding!() ที่ด้านบนแทนไฟล์ UDL และขั้น build.rs ที่บทเรียนเก่าหมุนรอบ เมื่อ API ทั้งก้อนถูกอธิบายด้วยแมโคร นี่คือการตั้งค่าเดียวที่คุณต้องมี (เอกสาร proc macro ของ UniFFI) #[derive(uniffi::Record)] ทำเครื่องหมายที่เก็บข้อมูลธรรมดาที่ข้ามชายแดนแบบส่งค่า และ #[derive(uniffi::Enum)] ทำแบบเดียวกันกับ enum ที่อยู่ข้างใน

ชนิด error ได้ความสนใจมากที่สุด UniFFI กำหนดให้ error enum implement std::error::Error (เอกสาร error ของ UniFFI) ซึ่งเป็นเหตุผลที่มีบล็อก impl เล็กสองบล็อก Display ให้ข้อความ exception ที่ Kotlin จะเห็น และฟิลด์ของ variant เช่น raw ข้ามชายแดนเป็นพร็อพเพอร์ตี้ที่มี type การคืน Result<Expense, ParseError> คือเรื่อง error ทั้งก้อนฝั่ง Rust คุณไม่แตะ JNIEnv และไม่โยน exception ด้วยมือ ดังนั้นไม่มีอะไรให้พลาดตอนตีสอง สิ่งที่เกิดเมื่อ Rust panic แทนการคืน Err เป็นคนละเรื่อง และมีโพสต์ของมันเอง คือ การจัดการ error และ panic: ไม่ให้ crash ของ Rust หลุดเข้าแอป Android ของคุณ

ไม่มีกฎการตั้งชื่อสัญลักษณ์ที่ไหนในไฟล์นี้ เปลี่ยนแพ็กเกจ Kotlin พรุ่งนี้ แล้วไม่มีบรรทัด Rust สักบรรทัดที่เปลี่ยน

Kotlin ที่สร้างขึ้น และมันอ่านอย่างไร

ไฟล์คอนฟิกเล็กหนึ่งไฟล์ควบคุมเอาต์พุต Kotlin นี่คือ rust/uniffi-demo/uniffi.toml

[bindings.kotlin]
package_name = "dev.davthecoder.rustseries.uniffi"

บิลด์ไฟล์ .so ให้เหมือนตอนที่ 1 แล้วชี้ตัวสร้างไปที่ไลบรารีที่คอมไพล์แล้ว สิ่งนี้เรียกว่า library mode ตัวสร้างอ่านเมทาดาทาที่แมโครฝังในไบนารี ดังนั้นมันไม่เคยแยกซอร์สของคุณ

cd rust/uniffi-demo
cargo ndk -t arm64-v8a -t armeabi-v7a -t x86_64 -t x86 \
  -o ../../app/src/main/jniLibs build --release
cargo run --bin uniffi-bindgen -- generate \
  --library target/aarch64-linux-android/release/libuniffi_demo.so \
  --language kotlin \
  --out-dir ../../app/build/generated/uniffi

ออกมาเป็นไฟล์เดียว uniffi_demo.kt ในแพ็กเกจที่คุณตั้ง มันเป็นโค้ด serialization ไม่กี่ร้อยบรรทัดที่คุณไม่เคยแก้ และผิวสาธารณะของมันแมปหนึ่งต่อหนึ่งกับ Rust คือ data class Expense, enum class Category ที่มี GROCERIES, TRANSPORT และ OTHER และลำดับชั้น ParseException แบบ sealed เพราะ UniFFI เปลี่ยนชื่อ FooError ของ Rust เป็น FooException ของ Kotlin สองฟังก์ชันมาเป็น parseExpense ที่ติด @Throws(ParseException::class) และ totalCents ไม่มี System.loadLibrary ให้คุณเขียนเช่นกัน ไฟล์ที่สร้างขึ้นโหลด libuniffi_demo.so เอง

นี่คือฝั่งที่ใช้ คือ app/src/main/java/dev/davthecoder/rustseries/ExpenseDemo.kt

package dev.davthecoder.rustseries

import dev.davthecoder.rustseries.uniffi.Category
import dev.davthecoder.rustseries.uniffi.Expense
import dev.davthecoder.rustseries.uniffi.ParseException
import dev.davthecoder.rustseries.uniffi.parseExpense
import dev.davthecoder.rustseries.uniffi.totalCents

object ExpenseDemo {

    fun run(): String {
        val groceries: Expense = parseExpense("Lidl;12.99;groceries")
        val transport: Expense = parseExpense("BVG;3.80;transport")

        check(groceries.category == Category.GROCERIES)
        check(totalCents(listOf(groceries, transport)) == 1679L)

        return try {
            parseExpense("Lidl;twelve;groceries")
            "unreachable"
        } catch (e: ParseException.BadAmount) {
            "rejected amount: ${e.raw}"
        } catch (e: ParseException) {
            "parse failed: ${e.message}"
        }
    }
}

บล็อก catch นั้นคือส่วนที่ JNI ที่เขียนมือไม่เคยให้ฟรี ParseException.BadAmount เป็น type จริงที่มีพร็อพเพอร์ตี้ raw จริง ดังนั้นคอมไพเลอร์ตรวจการจัดการ error ของคุณ และ when บนลำดับชั้น sealed ครบทุกแขนง ในตอนที่ 2 สิ่งที่เทียบเท่าคือค่า sentinel ที่คืนมา กับการภาวนา

ผูก UniFFI เข้าบิลด์ Gradle ของ Android

binding ต้องการ JNA ตอนรัน เวอร์ชัน 5.12.0 ขึ้นไปตาม เอกสาร Kotlin ของ UniFFI เพิ่มมันในบล็อก dependencies ของ app/build.gradle.kts

dependencies {
    implementation("net.java.dev.jna:jna:5.12.0@aar")
}

แล้วผูกทาสก์ Exec สองตัวเข้าไฟล์เดียวกัน ตัวหนึ่งบิลด์ไฟล์ .so ด้วย cargo-ndk ตัวถัดไปสร้าง binding จากไลบรารี arm64 และทั้งคู่แขวนกับ preBuild เพื่อให้ ./gradlew assembleDebug ธรรมดาทำทุกอย่าง การสร้างลง build/generated แล้วลงทะเบียนไดเรกทอรีนั้นเป็นรากซอร์ส ทำให้โค้ดที่สร้างอยู่พ้น src/ และพ้น git

val rustCrateDir = rootProject.file("rust/uniffi-demo")
val uniffiOutDir = layout.buildDirectory.dir("generated/uniffi")

val cargoNdkBuild = tasks.register<Exec>("cargoNdkBuild") {
    workingDir(rustCrateDir)
    commandLine(
        "cargo", "ndk",
        "-t", "arm64-v8a", "-t", "armeabi-v7a", "-t", "x86_64", "-t", "x86",
        "-o", project.file("src/main/jniLibs").absolutePath,
        "build", "--release",
    )
}

val generateUniffiBindings = tasks.register<Exec>("generateUniffiBindings") {
    dependsOn(cargoNdkBuild)
    workingDir(rustCrateDir)
    commandLine(
        "cargo", "run", "--bin", "uniffi-bindgen", "--",
        "generate",
        "--library", "target/aarch64-linux-android/release/libuniffi_demo.so",
        "--language", "kotlin",
        "--out-dir", uniffiOutDir.get().asFile.absolutePath,
    )
}

tasks.named("preBuild") {
    dependsOn(generateUniffiBindings)
}

android {
    sourceSets {
        getByName("main") {
            java.srcDir(uniffiOutDir)
        }
    }
}

นี่คือเวอร์ชันตรงๆ มันเรียก cargo ทุกบิลด์ และไม่รู้อะไรเรื่อง build type หรือ flavor การแคชของ cargo เองทำให้กรณีที่ไม่มีการเปลี่ยนยังเร็ว แต่ Gradle ข้ามทาสก์ไม่ได้เพราะพวกมันไม่ประกาศ input หรือ output การทำให้ Gradle กับ Cargo ทำตัวเหมือนบิลด์แบบเพิ่มทีละส่วนเดียว โดยแมปโปรไฟล์ debug กับ release ให้ถูก และแยก ABI สำหรับ Play คือทั้งตอนที่ 4 เรื่อง โครงสร้างโปรเจกต์: Gradle + Cargo ในบิลด์เดียว, การแยก ABI, flavor ของ debug/release

UniFFI กับ JNI ที่เขียนมือ แต่ละแบบชนะตรงไหน

ตอนนี้คุณชิป API รูปเดียวกันทั้งสองทางแล้ว

JNI ที่เขียนมือ (ตอนที่ 2) UniFFI (โพสต์นี้)
ต้นทุนต่อฟังก์ชัน สัญลักษณ์ การแปลง และการตรวจด้วยมือ แอโนเทชันหนึ่งอัน
ชนิดที่ซับซ้อน การจัดเรียงด้วยมือทั้งสองทาง record, enum, error ถูกสร้างให้
การจัดการ error ค่า sentinel หรือ exception ที่โยนมือ exception แบบ sealed ที่มี type
overhead ของการเรียก เรียกตรง primitive ข้ามฟรี serialization บวกการส่งผ่าน JNA
ทางเลือก zero-copy ByteBuffer ตรง การปักอาเรย์ ไม่มี โปรโตคอลก๊อป
dependency เพิ่ม ไม่มีนอกจาก .so ของคุณ JNA บวกรันไทม์ที่สร้างขึ้น
แพลตฟอร์มอื่น เขียนใหม่ต่อภาษา Swift และ Python จาก crate เดียวกัน

ทุกการเรียก UniFFI แพ็กอาร์กิวเมนต์ลงบัฟเฟอร์ ข้ามผ่าน JNA แล้วแกะฝั่งไกล และค่าที่คืนเดินทางเดียวกันย้อนกลับ สำหรับการเรียกล็อกอิน ตัวแยก หรือเอนจินซิงก์ คุณจะไม่รู้สึก สำหรับฟังก์ชันที่ถูกเรียกต่อเฟรมพร้อมเพย์โหลดขนาดบิตแมป คุณจะรู้สึก ผมจะไม่แต่งตัวเลขตรงนี้ ซีรีส์วางการวัดจริงบนชายแดนใน ประมวลผลภาพเร็วบน Android ด้วย Rust: บิตแมป ฟิลเตอร์ และเส้นทางเร็วของ JNI จนกว่าจะถึงตอนนั้น กฎที่ใช้ได้เรียบง่าย การเรียกหยาบเป็นของ UniFFI ลูปร้อนเป็นของ JNI ที่คุณควบคุม zero-copy เดินตามลอจิกเดียวกัน JNI ดิบให้การเข้าถึง ByteBuffer ตรงและการปักอาเรย์ ซึ่งครอบคลุมใน การส่งข้อมูลระหว่าง Kotlin กับ Rust: สตริง อาเรย์ ByteBuffer และ zero-copy ขณะที่โปรโตคอลของ UniFFI ก๊อปโดยการออกแบบ

UniFFI เพิ่มไลบรารีเนทีฟของ JNA ให้ทุก ABI ที่คุณชิป บวกโค้ดรันไทม์ที่สร้างขึ้น ขณะที่ JNI มือไม่เพิ่มอะไรนอกจาก .so ของคุณเอง และ binding ที่สร้างขึ้นถูกเชื่อมกับเวอร์ชัน uniffi ใน Cargo.lock ของคุณ เลื่อน crate แล้วคุณต้องสร้างใหม่ ซึ่งการผูก Gradle ด้านบนทำให้ทุกบิลด์อยู่แล้ว

สำหรับผลิตภัณฑ์จริงที่มี API กว้าง บัญชีนั้นยังเอียงแรงไปทาง UniFFI คุณยอมต้นทุนการก๊อปที่ส่วนใหญ่วัดไม่ได้ แล้วได้ error ที่คอมไพเลอร์ตรวจ กาวที่ไม่ปลอดภัยน้อยลงมาก และ binding ของ Swift จากแอโนเทชันเดียวกัน ดังนั้นนี่คือข้อตกลงสำหรับที่เหลือของซีรีส์ โพสต์สอนอยู่บน JNI ดิบ เพราะเครื่องจักรคือบทเรียน โพสต์เรื่องการบีบชายแดนก็อยู่บน JNI เพราะการควบคุมคือประเด็น สำหรับแอปโปรดักชันที่มีฟังก์ชันส่งออกมากกว่าหยิบมือ ใช้ UniFFI

คำถามที่พบบ่อย

ต้องมีไฟล์ UDL เพื่อใช้ UniFFI บน Android หรือไม่

ไม่ บทเรียนเก่าสร้างรอบไฟล์อินเทอร์เฟซ .udl และขั้นนั่งร้าน build.rs แต่อินเทอร์เฟซ proc macro ครอบคลุมฟังก์ชัน record enum error และอ็อบเจกต์ และ uniffi::setup_scaffolding!() แทนสคริปต์บิลด์ทั้งก้อน (เอกสาร proc macro ของ UniFFI) UDL ยังรองรับ และบางฟีเจอร์ยังโผล่ที่นั่นก่อน แต่โปรเจกต์ Android ใหม่ไม่ต้องการมัน

UniFFI ใช้ JNI ข้างใต้หรือไม่

ทางอ้อม Kotlin ที่สร้างขึ้นถึง Rust ของคุณผ่าน JNA ซึ่งตัวมันขี่บน JNI เพื่อเรียกโค้ดเนทีฟ (เอกสาร Kotlin ของ UniFFI) คุณไม่เขียนเลเยอร์นั้น แต่ชั้นนั้นมีอยู่ และนั่นคือเหตุผลที่การเรียก UniFFI แพงกว่าการเรียก JNI ที่เขียนมือตรงๆ จากตอนที่ 2

UniFFI สร้างฟังก์ชัน suspend สำหรับ Kotlin coroutine ได้หรือไม่

ได้ async fn ที่อยู่หลัง #[uniffi::export] กลายเป็นฟังก์ชัน suspend ของ Kotlin พร้อม dependency kotlinx-coroutines ฝั่ง Kotlin รันไทม์ เธรด และการเรียกกลับเข้า Kotlin จาก Rust เป็นหัวข้อของมันเอง ครอบคลุมใน เธรดและ async: Tokio, Kotlin Coroutines และการเรียกกลับเข้า Kotlin จาก Rust

การผูกด้านบนใช้ได้ แต่มันบิลด์ใหม่กระตือรือร้นเกินไป และไม่รู้อะไรเรื่อง flavor ตอนที่ 4 เรื่อง โครงสร้างโปรเจกต์: Gradle + Cargo ในบิลด์เดียว, การแยก ABI, flavor ของ debug/release เปลี่ยนมันเป็นบิลด์ที่คุณอยู่ด้วยได้ทุกวัน และถ้าคุณมาที่นี่จากผลการค้นหา ไม่ใช่จากตอนที่ 1 โพสต์ฮับ มีแผนที่ของทั้งซีรีส์

แหล่งข้อมูล

Share:Compartir:แชร์:

CommentsComentariosความคิดเห็น

Loading comments…Cargando comentarios…กำลังโหลดความคิดเห็น…