#android #ndk

ndk

Safe Rust bindings to the Android NDK

2 unstable releases

0.2.0 Sep 15, 2020
0.1.1 Jul 29, 2020
0.1.0 Apr 22, 2020

#3 in #ndk

Download history 3044/week @ 2020-06-06 2793/week @ 2020-06-13 2601/week @ 2020-06-20 3187/week @ 2020-06-27 2969/week @ 2020-07-04 3654/week @ 2020-07-11 3494/week @ 2020-07-18 3992/week @ 2020-07-25 3507/week @ 2020-08-01 2992/week @ 2020-08-08 2986/week @ 2020-08-15 3358/week @ 2020-08-22 3642/week @ 2020-08-29 3700/week @ 2020-09-05 2497/week @ 2020-09-12 2878/week @ 2020-09-19

14,170 downloads per month
Used in 163 crates (4 directly)

MIT/Apache

3MB
90K SLoC

Rust on Android

Rust MIT license APACHE2 license

Libraries and tools for Rust programming on Android targets:

Name Description Badges
ndk-sys Raw FFI bindings to the NDK crates.io crates.io
ndk Safe abstraction of the bindings crates.io crates.io
ndk-glue Startup code crates.io crates.io
ndk-build Everything for building apk's crates.io crates.io
cargo-apk Build tool crates.io crates.io

See ndk-examples for examples using the NDK and the README files of the crates for more details.

Hello world

Quick start for setting up a new project with support for Android. For communication with the Android framework in our native Rust application we require a NativeActivity. ndk-glue will do the necessary initialization when calling main but requires a few adjustments:

Cargo.toml

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

Wraps main function using attribute macro ndk::glue::main:

src/lib.rs

#[cfg_attr(target_os = "android", ndk_glue::main(backtrace = "on"))]
pub fn main() {
    println!("hello world");
}

src/main.rs

fn main() {
    $crate::main();
}

Install cargo apk for building, running and debugging your application:

cargo install cargo-apk

We can now directly execute our Hello World application on a real connected device or an emulator:

cargo apk run

Logging and stdout

Stdout is redirected to the android log api when using ndk-glue. Any logger that logs to stdout, like println!, should therefore work.

Use can filter the output in logcat

adb logcat RustStdoutStderr:D *:S

Android logger

Android logger can be setup using feature "logger" and attribute macro like so:

src/lib.rs

#[cfg_attr(target_os = "android", ndk_glue::main(logger(level = "debug", tag = "my-tag")))]
pub fn main() {
    log!("hello world");
}

Overriding crate paths

The macro ndk_glue::main tries to determine crate names from current Cargo.toml. In cases when it is not possible the default crate names will be used. You can override this names with specific paths like so:

#[ndk_glue::main(
  ndk_glue = "path::to::ndk_glue",
  logger(android_logger = "path::to::android_logger",
         log = "path::to::log")
)]
fn main() {}

JNI

TODO: talk more about jni and add some examples

  • jni, JNI bindings for Rust

Winit and glutin

TODO shameless plug

Flutter

TODO shameless plug

Dependencies

~0.9–1.7MB
~39K SLoC