Created
May 26, 2016 20:52
-
-
Save meoyawn/6d19fefe98a7c189c99870ec12a57349 to your computer and use it in GitHub Desktop.
Simple JNI with Kotlin and Rust
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package rust | |
external fun test(): String | |
fun main(args: Array<String>): Unit { | |
System.loadLibrary("hello") | |
println(test()) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[package] | |
name = "hello" | |
version = "0.1.0" | |
authors = ["adelnizamutdinov"] | |
[lib] | |
crate-type = ["dylib"] | |
[dependencies] | |
jni-sys = "0.1.0" | |
cesu8 = "1.1.0" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extern crate jni_sys; | |
extern crate cesu8; | |
use jni_sys::*; | |
#[derive(Debug)] | |
struct ExceptionThrown; | |
#[derive(Copy, Clone)] | |
struct SafeJNI(*mut jni_sys::JNIEnv); | |
impl SafeJNI { | |
fn string(&self, s: &str) -> Result<jni_sys::jstring, ExceptionThrown> { | |
let s = cvt(s); | |
let s = unsafe { ((**self.0).NewStringUTF)(self.0, s.as_ptr() as *const _) }; | |
if s.is_null() { | |
return Err(ExceptionThrown); | |
} | |
Ok(s) | |
} | |
} | |
fn cvt(s: &str) -> Vec<u8> { | |
let mut s = cesu8::to_java_cesu8(s).to_vec(); | |
s.push(0); | |
s | |
} | |
#[no_mangle] | |
pub extern "C" fn Java_rust_AppKt_test(env: *mut JNIEnv, class: jclass) -> jstring { | |
SafeJNI(env).string("this is rust mate").unwrap() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment