7.3 与 Java 互操作
01-与 Java 互操作 — Comprehensive Rust
1分钟内可阅读完
译文 · 基于 Comprehensive Rust
原文链接: https://google.github.io/comprehensive-rust/android/interoperability/java.html
7.3 与 Java 互操作
Java 可以通过
Java Native Interface (JNI)
加载共享对象。jni crate 允许你创建兼容的库。
首先,创建一个要导出给 Java 的 Rust 函数:
interoperability/java/src/lib.rs:
// Copyright 2022 Google LLC
// SPDX-License-Identifier: Apache-2.0
//! Rust <-> Java FFI demo.
use jni::JNIEnv;
use jni::objects::{JClass, JString};
use jni::sys::jstring;
/// HelloWorld::hello method implementation.
// SAFETY: There is no other global function of this name.
#[unsafe(no_mangle)]
pub extern "system" fn Java_HelloWorld_hello(
mut env: JNIEnv,
_class: JClass,
name: JString,
) -> jstring {
let input: String = env.get_string(&name).unwrap().into();
let greeting = format!("Hello, {input}!");
let output = env.new_string(greeting).unwrap();
output.into_raw()
}
interoperability/java/Android.bp:
| |
然后从 Java 调用该函数:
interoperability/java/HelloWorld.java:
| |
interoperability/java/Android.bp:
| |
最后,可以构建、同步并运行该二进制:
| |
unsafe(no_mangle)属性指示 Rust 按原样发出Java_HelloWorld_hello符号。这一点很重要,以便 Java 能把该符号识别为HelloWorld类上的hello方法。
- 默认情况下,Rust 会 mangling(重命名)符号,以便一个二进制可以链接同一 Rust crate 的两个版本。