feat: add basic rust JNI demo

This commit is contained in:
Matthieu Bessat 2024-01-01 17:45:08 +01:00
parent 954d100742
commit 8d1472b5a7
6 changed files with 61 additions and 0 deletions

1
.gitignore vendored
View file

@ -8,3 +8,4 @@
.externalNativeBuild .externalNativeBuild
.cxx .cxx
local.properties local.properties
jniLibs

View file

@ -0,0 +1,8 @@
package net.mbess.popequer
object Native {
init {
System.loadLibrary("rustsandbox")
}
external fun add(a: Int, b: Int): Int
}

View file

@ -8,10 +8,14 @@ import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.* import androidx.compose.material3.*
import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalContext
import net.mbess.popequer.AppContext import net.mbess.popequer.AppContext
import net.mbess.popequer.Native
class MainActivity : ComponentActivity() { class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
Native.add(143, 54).let {
println("From foreign rust result: $it")
}
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
val appContext = AppContext(this) val appContext = AppContext(this)

20
rust-sandbox/.gitignore vendored Normal file
View file

@ -0,0 +1,20 @@
# Created by https://www.toptal.com/developers/gitignore/api/rust
# Edit at https://www.toptal.com/developers/gitignore?templates=rust
### Rust ###
# Generated by Cargo
# will have compiled files and executables
debug/
target/
# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries
# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html
Cargo.lock
# These are backup files generated by rustfmt
**/*.rs.bk
# MSVC Windows builds of rustc generate these, which store debugging information
*.pdb
# End of https://www.toptal.com/developers/gitignore/api/rust

13
rust-sandbox/Cargo.toml Normal file
View file

@ -0,0 +1,13 @@
[package]
name = "rust-sandbox"
version = "0.1.0"
edition = "2021"
[lib]
name = "rustsandbox"
crate-type = ["cdylib"]
[dependencies]
jni = "0.21.1"
[target.'cfg(target_os = "android")'.dependencies]

15
rust-sandbox/src/lib.rs Normal file
View file

@ -0,0 +1,15 @@
use jni::{
objects::{JClass, JObject},
JNIEnv,
};
#[no_mangle]
pub extern "system" fn Java_net_mbess_popequer_Native_add(
_env: JNIEnv,
_class: JClass,
a: i32,
b: i32
) -> i32 {
a + b
}