Struct jni::AttachGuard
source · [−]pub struct AttachGuard<'a> { /* private fields */ }
Expand description
A RAII implementation of scoped guard which detaches the current thread
when dropped. The attached JNIEnv
can be accessed through this guard
via its Deref
implementation.
Methods from Deref<Target = JNIEnv<'a>>
sourcepub fn get_version(&self) -> Result<JNIVersion>
pub fn get_version(&self) -> Result<JNIVersion>
Get the java version that we’re being executed from.
sourcepub fn define_class<S>(
&self,
name: S,
loader: JObject<'a>,
buf: &[u8]
) -> Result<JClass<'a>>where
S: Into<JNIString>,
pub fn define_class<S>(
&self,
name: S,
loader: JObject<'a>,
buf: &[u8]
) -> Result<JClass<'a>>where
S: Into<JNIString>,
Load a class from a buffer of raw class data. The name of the class must match the name encoded within the class file data.
sourcepub fn define_unnamed_class<S>(
&self,
loader: JObject<'a>,
buf: &[u8]
) -> Result<JClass<'a>>where
S: Into<JNIString>,
pub fn define_unnamed_class<S>(
&self,
loader: JObject<'a>,
buf: &[u8]
) -> Result<JClass<'a>>where
S: Into<JNIString>,
Load a class from a buffer of raw class data. The name of the class is inferred from the buffer.
sourcepub fn get_superclass<'c, T>(&self, class: T) -> Result<JClass<'a>>where
T: Desc<'a, JClass<'c>>,
pub fn get_superclass<'c, T>(&self, class: T) -> Result<JClass<'a>>where
T: Desc<'a, JClass<'c>>,
Returns the superclass for a particular class OR JObject::null()
for java.lang.Object
or
an interface. As with find_class
, takes a descriptor.
sourcepub fn is_assignable_from<'t, 'u, T, U>(
&self,
class1: T,
class2: U
) -> Result<bool>where
T: Desc<'a, JClass<'t>>,
U: Desc<'a, JClass<'u>>,
pub fn is_assignable_from<'t, 'u, T, U>(
&self,
class1: T,
class2: U
) -> Result<bool>where
T: Desc<'a, JClass<'t>>,
U: Desc<'a, JClass<'u>>,
Tests whether class1 is assignable from class2.
sourcepub fn is_instance_of<'c, O, T>(&self, object: O, class: T) -> Result<bool>where
O: Into<JObject<'a>>,
T: Desc<'a, JClass<'c>>,
pub fn is_instance_of<'c, O, T>(&self, object: O, class: T) -> Result<bool>where
O: Into<JObject<'a>>,
T: Desc<'a, JClass<'c>>,
Returns true if the object reference can be cast to the given type.
NB: Unlike the operator instanceof
, function IsInstanceOf
returns true
for all classes if object
is null
.
See JNI documentation for details.
sourcepub fn is_same_object<'b, 'c, O, T>(&self, ref1: O, ref2: T) -> Result<bool>where
O: Into<JObject<'b>>,
T: Into<JObject<'c>>,
pub fn is_same_object<'b, 'c, O, T>(&self, ref1: O, ref2: T) -> Result<bool>where
O: Into<JObject<'b>>,
T: Into<JObject<'c>>,
Returns true if ref1 and ref2 refer to the same Java object, or are both NULL
. Otherwise,
returns false.
sourcepub fn throw<'e, E>(&self, obj: E) -> Result<()>where
E: Desc<'a, JThrowable<'e>>,
pub fn throw<'e, E>(&self, obj: E) -> Result<()>where
E: Desc<'a, JThrowable<'e>>,
Raise an exception from an existing object. This will continue being
thrown in java unless exception_clear
is called.
Examples
let _ = env.throw(("java/lang/Exception", "something bad happened"));
Defaulting to “java/lang/Exception”:
let _ = env.throw("something bad happened");
sourcepub fn throw_new<'c, S, T>(&self, class: T, msg: S) -> Result<()>where
S: Into<JNIString>,
T: Desc<'a, JClass<'c>>,
pub fn throw_new<'c, S, T>(&self, class: T, msg: S) -> Result<()>where
S: Into<JNIString>,
T: Desc<'a, JClass<'c>>,
Create and throw a new exception from a class descriptor and an error message.
Example
let _ = env.throw_new("java/lang/Exception", "something bad happened");
sourcepub fn exception_occurred(&self) -> Result<JThrowable<'a>>
pub fn exception_occurred(&self) -> Result<JThrowable<'a>>
Check whether or not an exception is currently in the process of being
thrown. An exception is in this state from the time it gets thrown and
not caught in a java function until exception_clear
is called.
sourcepub fn exception_describe(&self) -> Result<()>
pub fn exception_describe(&self) -> Result<()>
Print exception information to the console.
sourcepub fn exception_clear(&self) -> Result<()>
pub fn exception_clear(&self) -> Result<()>
Clear an exception in the process of being thrown. If this is never called, the exception will continue being thrown when control is returned to java.
sourcepub fn fatal_error<S: Into<JNIString>>(&self, msg: S) -> !
pub fn fatal_error<S: Into<JNIString>>(&self, msg: S) -> !
Abort the JVM with an error message.
sourcepub fn exception_check(&self) -> Result<bool>
pub fn exception_check(&self) -> Result<bool>
Check to see if an exception is being thrown. This only differs from
exception_occurred
in that it doesn’t return the actual thrown
exception.
sourcepub unsafe fn new_direct_byte_buffer(
&self,
data: *mut u8,
len: usize
) -> Result<JByteBuffer<'a>>
pub unsafe fn new_direct_byte_buffer(
&self,
data: *mut u8,
len: usize
) -> Result<JByteBuffer<'a>>
Create a new instance of a direct java.nio.ByteBuffer
Example
let buf = vec![0; 1024 * 1024];
let (addr, len) = { // (use buf.into_raw_parts() on nightly)
let buf = buf.leak();
(buf.as_mut_ptr(), buf.len())
};
let direct_buffer = unsafe { env.new_direct_byte_buffer(addr, len) };
Safety
Expects a valid (non-null) pointer and length
Caller must ensure the lifetime of data
extends to all uses of the returned
ByteBuffer
. The JVM may maintain references to the ByteBuffer
beyond the lifetime
of this JNIEnv
.
sourcepub fn get_direct_buffer_address(&self, buf: JByteBuffer<'_>) -> Result<*mut u8>
pub fn get_direct_buffer_address(&self, buf: JByteBuffer<'_>) -> Result<*mut u8>
Returns the starting address of the memory of the direct java.nio.ByteBuffer.
sourcepub fn get_direct_buffer_capacity(&self, buf: JByteBuffer<'_>) -> Result<usize>
pub fn get_direct_buffer_capacity(&self, buf: JByteBuffer<'_>) -> Result<usize>
Returns the capacity (length) of the direct java.nio.ByteBuffer.
Terminology
“capacity” here means the length that was passed to Self::new_direct_byte_buffer()
which does not reflect the (potentially) larger size of the underlying allocation (unlike the Vec
API).
The terminology is simply kept from the original JNI API (GetDirectBufferCapacity
).
sourcepub fn new_global_ref<O>(&self, obj: O) -> Result<GlobalRef>where
O: Into<JObject<'a>>,
pub fn new_global_ref<O>(&self, obj: O) -> Result<GlobalRef>where
O: Into<JObject<'a>>,
Turns an object into a global ref. This has the benefit of removing the lifetime bounds since it’s guaranteed to not get GC’d by java. It releases the GC pin upon being dropped.
sourcepub fn new_local_ref<'b, O>(&self, obj: O) -> Result<JObject<'a>>where
O: Into<JObject<'b>>,
pub fn new_local_ref<'b, O>(&self, obj: O) -> Result<JObject<'a>>where
O: Into<JObject<'b>>,
Create a new local reference to an object.
Specifically, this calls the JNI function NewLocalRef
, which creates a reference in the
current local reference frame, regardless of whether the original reference belongs to the
same local reference frame, a different one, or is a global reference. In Rust
terms, this method accepts a JNI reference with any valid lifetime and produces a clone of
that reference with the lifetime of this JNIEnv
. The returned reference can outlive the
original.
This method is useful when you have a strong global reference and you can’t prevent it from being dropped before you’re finished with it. In that case, you can use this method to create a new local reference that’s guaranteed to remain valid for the duration of the current local reference frame, regardless of what later happens to the original global reference.
Lifetimes
'a
is the lifetime of this JNIEnv
. This method creates a new local reference with
lifetime 'a
.
'b
is the lifetime of the original reference. It can be any valid lifetime, even one that
'a
outlives or vice versa.
Think of 'a
as meaning 'new
and 'b
as meaning 'original
. (It is unfortunately not
possible to actually give these names to the two lifetimes because 'a
is a parameter to
the JNIEnv
type, not a parameter to this method.)
Example
In the following example, the ExampleError::extract_throwable
method uses
JNIEnv::new_local_ref
to create a new local reference that outlives the original global
reference:
/// An error that may be caused by either a Java exception or something going wrong in Rust
/// code.
enum ExampleError {
/// This variant represents a Java exception.
///
/// The enclosed `GlobalRef` points to a Java object of class `java.lang.Throwable`
/// (or one of its many subclasses).
Exception(GlobalRef),
/// This variant represents an error in Rust code, not a Java exception.
Other(SomeOtherErrorType),
}
impl ExampleError {
/// Consumes this `ExampleError` and produces a `JThrowable`, suitable for throwing
/// back to Java code.
///
/// If this is an `ExampleError::Exception`, then this extracts the enclosed Java
/// exception object. Otherwise, a new exception object is created to represent this
/// error.
fn extract_throwable(self, env: JNIEnv) -> jni::errors::Result<JThrowable> {
let throwable: JObject = match self {
ExampleError::Exception(exception) => {
// The error was caused by a Java exception.
// Here, `exception` is a `GlobalRef` pointing to a Java `Throwable`. It
// will be dropped at the end of this `match` arm. We'll use
// `new_local_ref` to create a local reference that will outlive the
// `GlobalRef`.
env.new_local_ref(exception.as_obj())?
}
ExampleError::Other(error) => {
// The error was caused by something that happened in Rust code. Create a
// new `java.lang.Error` to represent it.
env.new_object(
"java/lang/Error",
"(Ljava/lang/String;)V",
&[
env.new_string(error.to_string())?.into(),
],
)?
}
};
Ok(JThrowable::from(throwable))
}
}
sourcepub fn auto_local<'b, O>(&'b self, obj: O) -> AutoLocal<'a, 'b>where
O: Into<JObject<'a>>,
pub fn auto_local<'b, O>(&'b self, obj: O) -> AutoLocal<'a, 'b>where
O: Into<JObject<'a>>,
Creates a new auto-deleted local reference.
See also with_local_frame
method that
can be more convenient when you create a bounded number of local references
but cannot rely on automatic de-allocation (e.g., in case of recursion, deep call stacks,
permanently-attached native threads, etc.).
sourcepub fn delete_local_ref(&self, obj: JObject<'_>) -> Result<()>
pub fn delete_local_ref(&self, obj: JObject<'_>) -> Result<()>
Deletes the local reference.
Local references are valid for the duration of a native method call. They are freed automatically after the native method returns. Each local reference costs some amount of Java Virtual Machine resource. Programmers need to make sure that native methods do not excessively allocate local references. Although local references are automatically freed after the native method returns to Java, excessive allocation of local references may cause the VM to run out of memory during the execution of a native method.
In most cases it is better to use AutoLocal
(see auto_local
method)
or with_local_frame
instead of direct delete_local_ref
calls.
sourcepub fn push_local_frame(&self, capacity: i32) -> Result<()>
pub fn push_local_frame(&self, capacity: i32) -> Result<()>
Creates a new local reference frame, in which at least a given number of local references can be created.
Returns Err
on failure, with a pending OutOfMemoryError
.
Prefer to use with_local_frame
instead of
direct push_local_frame
/pop_local_frame
calls.
See also auto_local
method
and AutoLocal
type — that approach can be more convenient in loops.
sourcepub fn pop_local_frame(&self, result: JObject<'a>) -> Result<JObject<'a>>
pub fn pop_local_frame(&self, result: JObject<'a>) -> Result<JObject<'a>>
Pops off the current local reference frame, frees all the local
references allocated on the current stack frame, except the result
,
which is returned from this function and remains valid.
The resulting JObject
will be NULL
iff result
is NULL
.
sourcepub fn with_local_frame<F>(&self, capacity: i32, f: F) -> Result<JObject<'a>>where
F: FnOnce() -> Result<JObject<'a>>,
pub fn with_local_frame<F>(&self, capacity: i32, f: F) -> Result<JObject<'a>>where
F: FnOnce() -> Result<JObject<'a>>,
Executes the given function in a new local reference frame, in which at least a given number of references can be created. Once this method returns, all references allocated in the frame are freed, except the one that the function returns, which remains valid.
If no new frames can be allocated, returns Err
with a pending OutOfMemoryError
.
See also auto_local
method
and AutoLocal
type - that approach can be more convenient in loops.
sourcepub fn alloc_object<'c, T>(&self, class: T) -> Result<JObject<'a>>where
T: Desc<'a, JClass<'c>>,
pub fn alloc_object<'c, T>(&self, class: T) -> Result<JObject<'a>>where
T: Desc<'a, JClass<'c>>,
Allocates a new object from a class descriptor without running a constructor.
sourcepub fn get_method_id<'c, T, U, V>(
&self,
class: T,
name: U,
sig: V
) -> Result<JMethodID>where
T: Desc<'a, JClass<'c>>,
U: Into<JNIString>,
V: Into<JNIString>,
pub fn get_method_id<'c, T, U, V>(
&self,
class: T,
name: U,
sig: V
) -> Result<JMethodID>where
T: Desc<'a, JClass<'c>>,
U: Into<JNIString>,
V: Into<JNIString>,
Look up a method by class descriptor, name, and signature.
Example
let method_id: JMethodID =
env.get_method_id("java/lang/String", "substring", "(II)Ljava/lang/String;");
sourcepub fn get_static_method_id<'c, T, U, V>(
&self,
class: T,
name: U,
sig: V
) -> Result<JStaticMethodID>where
T: Desc<'a, JClass<'c>>,
U: Into<JNIString>,
V: Into<JNIString>,
pub fn get_static_method_id<'c, T, U, V>(
&self,
class: T,
name: U,
sig: V
) -> Result<JStaticMethodID>where
T: Desc<'a, JClass<'c>>,
U: Into<JNIString>,
V: Into<JNIString>,
Look up a static method by class descriptor, name, and signature.
Example
let method_id: JMethodID =
env.get_static_method_id("java/lang/String", "valueOf", "(I)Ljava/lang/String;");
sourcepub fn get_field_id<'c, T, U, V>(
&self,
class: T,
name: U,
sig: V
) -> Result<JFieldID>where
T: Desc<'a, JClass<'c>>,
U: Into<JNIString>,
V: Into<JNIString>,
pub fn get_field_id<'c, T, U, V>(
&self,
class: T,
name: U,
sig: V
) -> Result<JFieldID>where
T: Desc<'a, JClass<'c>>,
U: Into<JNIString>,
V: Into<JNIString>,
Look up the field ID for a class/name/type combination.
Example
let field_id = env.get_field_id("com/my/Class", "intField", "I");
sourcepub fn get_static_field_id<'c, T, U, V>(
&self,
class: T,
name: U,
sig: V
) -> Result<JStaticFieldID>where
T: Desc<'a, JClass<'c>>,
U: Into<JNIString>,
V: Into<JNIString>,
pub fn get_static_field_id<'c, T, U, V>(
&self,
class: T,
name: U,
sig: V
) -> Result<JStaticFieldID>where
T: Desc<'a, JClass<'c>>,
U: Into<JNIString>,
V: Into<JNIString>,
Look up the static field ID for a class/name/type combination.
Example
let field_id = env.get_static_field_id("com/my/Class", "intField", "I");
sourcepub fn get_object_class<'b, O>(&self, obj: O) -> Result<JClass<'a>>where
O: Into<JObject<'b>>,
pub fn get_object_class<'b, O>(&self, obj: O) -> Result<JClass<'a>>where
O: Into<JObject<'b>>,
Get the class for an object.
sourcepub fn call_static_method_unchecked<'c, T, U>(
&self,
class: T,
method_id: U,
ret: ReturnType,
args: &[jvalue]
) -> Result<JValue<'a>>where
T: Desc<'a, JClass<'c>>,
U: Desc<'a, JStaticMethodID>,
pub fn call_static_method_unchecked<'c, T, U>(
&self,
class: T,
method_id: U,
ret: ReturnType,
args: &[jvalue]
) -> Result<JValue<'a>>where
T: Desc<'a, JClass<'c>>,
U: Desc<'a, JStaticMethodID>,
Call a static method in an unsafe manner. This does nothing to check whether the method is valid to call on the class, whether the return type is correct, or whether the number of args is valid for the method.
Under the hood, this simply calls the CallStatic<Type>MethodA
method
with the provided arguments.
sourcepub fn call_method_unchecked<O, T>(
&self,
obj: O,
method_id: T,
ret: ReturnType,
args: &[jvalue]
) -> Result<JValue<'a>>where
O: Into<JObject<'a>>,
T: Desc<'a, JMethodID>,
pub fn call_method_unchecked<O, T>(
&self,
obj: O,
method_id: T,
ret: ReturnType,
args: &[jvalue]
) -> Result<JValue<'a>>where
O: Into<JObject<'a>>,
T: Desc<'a, JMethodID>,
Call an object method in an unsafe manner. This does nothing to check whether the method is valid to call on the object, whether the return type is correct, or whether the number of args is valid for the method.
Under the hood, this simply calls the Call<Type>MethodA
method with
the provided arguments.
sourcepub fn call_method<O, S, T>(
&self,
obj: O,
name: S,
sig: T,
args: &[JValue<'_>]
) -> Result<JValue<'a>>where
O: Into<JObject<'a>>,
S: Into<JNIString>,
T: Into<JNIString> + AsRef<str>,
pub fn call_method<O, S, T>(
&self,
obj: O,
name: S,
sig: T,
args: &[JValue<'_>]
) -> Result<JValue<'a>>where
O: Into<JObject<'a>>,
S: Into<JNIString>,
T: Into<JNIString> + AsRef<str>,
Calls an object method safely. This comes with a number of lookups/checks. It
- Parses the type signature to find the number of arguments and return type
- Looks up the JClass for the given object.
- Looks up the JMethodID for the class/name/signature combination
- Ensures that the number of args matches the signature
- Calls
call_method_unchecked
with the verified safe arguments.
Note: this may cause a java exception if the arguments are the wrong type, in addition to if the method itself throws.
sourcepub fn call_static_method<'c, T, U, V>(
&self,
class: T,
name: U,
sig: V,
args: &[JValue<'_>]
) -> Result<JValue<'a>>where
T: Desc<'a, JClass<'c>>,
U: Into<JNIString>,
V: Into<JNIString> + AsRef<str>,
pub fn call_static_method<'c, T, U, V>(
&self,
class: T,
name: U,
sig: V,
args: &[JValue<'_>]
) -> Result<JValue<'a>>where
T: Desc<'a, JClass<'c>>,
U: Into<JNIString>,
V: Into<JNIString> + AsRef<str>,
Calls a static method safely. This comes with a number of lookups/checks. It
- Parses the type signature to find the number of arguments and return type
- Looks up the JMethodID for the class/name/signature combination
- Ensures that the number of args matches the signature
- Calls
call_method_unchecked
with the verified safe arguments.
Note: this may cause a java exception if the arguments are the wrong type, in addition to if the method itself throws.
sourcepub fn new_object<'c, T, U>(
&self,
class: T,
ctor_sig: U,
ctor_args: &[JValue<'_>]
) -> Result<JObject<'a>>where
T: Desc<'a, JClass<'c>>,
U: Into<JNIString> + AsRef<str>,
pub fn new_object<'c, T, U>(
&self,
class: T,
ctor_sig: U,
ctor_args: &[JValue<'_>]
) -> Result<JObject<'a>>where
T: Desc<'a, JClass<'c>>,
U: Into<JNIString> + AsRef<str>,
Create a new object using a constructor. This is done safely using
checks similar to those in call_static_method
.
sourcepub fn new_object_unchecked<'c, T>(
&self,
class: T,
ctor_id: JMethodID,
ctor_args: &[JValue<'_>]
) -> Result<JObject<'a>>where
T: Desc<'a, JClass<'c>>,
pub fn new_object_unchecked<'c, T>(
&self,
class: T,
ctor_id: JMethodID,
ctor_args: &[JValue<'_>]
) -> Result<JObject<'a>>where
T: Desc<'a, JClass<'c>>,
Create a new object using a constructor. Arguments aren’t checked
because
of the JMethodID
usage.
sourcepub fn get_list(&self, obj: JObject<'a>) -> Result<JList<'a, '_>>
pub fn get_list(&self, obj: JObject<'a>) -> Result<JList<'a, '_>>
Cast a JObject to a JList
. This won’t throw exceptions or return errors
in the event that the object isn’t actually a list, but the methods on
the resulting map object will.
sourcepub fn get_map(&self, obj: JObject<'a>) -> Result<JMap<'a, '_>>
pub fn get_map(&self, obj: JObject<'a>) -> Result<JMap<'a, '_>>
Cast a JObject to a JMap. This won’t throw exceptions or return errors in the event that the object isn’t actually a map, but the methods on the resulting map object will.
sourcepub fn get_string(&self, obj: JString<'a>) -> Result<JavaStr<'a, '_>>
pub fn get_string(&self, obj: JString<'a>) -> Result<JavaStr<'a, '_>>
Get a JavaStr from a JString. This allows conversions from java string objects to rust strings.
This entails a call to GetStringUTFChars
and only decodes java’s
modified UTF-8 format on conversion to a rust-compatible string.
Panics
This call panics when given an Object that is not a java.lang.String
sourcepub fn get_string_utf_chars(&self, obj: JString<'_>) -> Result<*const c_char>
pub fn get_string_utf_chars(&self, obj: JString<'_>) -> Result<*const c_char>
Get a pointer to the character array beneath a JString.
Array contains Java’s modified UTF-8.
Attention
This will leak memory if release_string_utf_chars
is never called.
sourcepub unsafe fn release_string_utf_chars(
&self,
obj: JString<'_>,
arr: *const c_char
) -> Result<()>
pub unsafe fn release_string_utf_chars(
&self,
obj: JString<'_>,
arr: *const c_char
) -> Result<()>
Unpin the array returned by get_string_utf_chars
.
Safety
The behaviour is undefined if the array isn’t returned by the get_string_utf_chars
function.
Examples
let s = env.new_string("test").unwrap();
let array = env.get_string_utf_chars(s).unwrap();
unsafe { env.release_string_utf_chars(s, array).unwrap() };
sourcepub fn new_string<S: Into<JNIString>>(&self, from: S) -> Result<JString<'a>>
pub fn new_string<S: Into<JNIString>>(&self, from: S) -> Result<JString<'a>>
Create a new java string object from a rust string. This requires a re-encoding of rusts real UTF-8 strings to java’s modified UTF-8 format.
sourcepub fn get_array_length(&self, array: jarray) -> Result<jsize>
pub fn get_array_length(&self, array: jarray) -> Result<jsize>
Get the length of a java array
sourcepub fn new_object_array<'c, T, U>(
&self,
length: jsize,
element_class: T,
initial_element: U
) -> Result<jobjectArray>where
T: Desc<'a, JClass<'c>>,
U: Into<JObject<'a>>,
pub fn new_object_array<'c, T, U>(
&self,
length: jsize,
element_class: T,
initial_element: U
) -> Result<jobjectArray>where
T: Desc<'a, JClass<'c>>,
U: Into<JObject<'a>>,
Construct a new array holding objects in class element_class
.
All elements are initially set to initial_element
.
This function returns a local reference, that must not be allocated excessively. See Java documentation for details.
sourcepub fn get_object_array_element(
&self,
array: jobjectArray,
index: jsize
) -> Result<JObject<'a>>
pub fn get_object_array_element(
&self,
array: jobjectArray,
index: jsize
) -> Result<JObject<'a>>
Returns an element of the jobjectArray
array.
sourcepub fn set_object_array_element<O>(
&self,
array: jobjectArray,
index: jsize,
value: O
) -> Result<()>where
O: Into<JObject<'a>>,
pub fn set_object_array_element<O>(
&self,
array: jobjectArray,
index: jsize,
value: O
) -> Result<()>where
O: Into<JObject<'a>>,
Sets an element of the jobjectArray
array.
sourcepub fn byte_array_from_slice(&self, buf: &[u8]) -> Result<jbyteArray>
pub fn byte_array_from_slice(&self, buf: &[u8]) -> Result<jbyteArray>
Create a new java byte array from a rust byte slice.
sourcepub fn convert_byte_array(&self, array: jbyteArray) -> Result<Vec<u8>>
pub fn convert_byte_array(&self, array: jbyteArray) -> Result<Vec<u8>>
Converts a java byte array to a rust vector of bytes.
sourcepub fn new_boolean_array(&self, length: jsize) -> Result<jbooleanArray>
pub fn new_boolean_array(&self, length: jsize) -> Result<jbooleanArray>
Create a new java boolean array of supplied length.
sourcepub fn new_byte_array(&self, length: jsize) -> Result<jbyteArray>
pub fn new_byte_array(&self, length: jsize) -> Result<jbyteArray>
Create a new java byte array of supplied length.
sourcepub fn new_char_array(&self, length: jsize) -> Result<jcharArray>
pub fn new_char_array(&self, length: jsize) -> Result<jcharArray>
Create a new java char array of supplied length.
sourcepub fn new_short_array(&self, length: jsize) -> Result<jshortArray>
pub fn new_short_array(&self, length: jsize) -> Result<jshortArray>
Create a new java short array of supplied length.
sourcepub fn new_int_array(&self, length: jsize) -> Result<jintArray>
pub fn new_int_array(&self, length: jsize) -> Result<jintArray>
Create a new java int array of supplied length.
sourcepub fn new_long_array(&self, length: jsize) -> Result<jlongArray>
pub fn new_long_array(&self, length: jsize) -> Result<jlongArray>
Create a new java long array of supplied length.
sourcepub fn new_float_array(&self, length: jsize) -> Result<jfloatArray>
pub fn new_float_array(&self, length: jsize) -> Result<jfloatArray>
Create a new java float array of supplied length.
sourcepub fn new_double_array(&self, length: jsize) -> Result<jdoubleArray>
pub fn new_double_array(&self, length: jsize) -> Result<jdoubleArray>
Create a new java double array of supplied length.
sourcepub fn get_boolean_array_region(
&self,
array: jbooleanArray,
start: jsize,
buf: &mut [jboolean]
) -> Result<()>
pub fn get_boolean_array_region(
&self,
array: jbooleanArray,
start: jsize,
buf: &mut [jboolean]
) -> Result<()>
Copy elements of the java boolean array from the start
index to the
buf
slice. The number of copied elements is equal to the buf
length.
Errors
If start
is negative or start + buf.len()
is greater than array.length
then no elements are copied, an ArrayIndexOutOfBoundsException
is thrown,
and Err
is returned.
sourcepub fn get_byte_array_region(
&self,
array: jbyteArray,
start: jsize,
buf: &mut [jbyte]
) -> Result<()>
pub fn get_byte_array_region(
&self,
array: jbyteArray,
start: jsize,
buf: &mut [jbyte]
) -> Result<()>
Copy elements of the java byte array from the start
index to the buf
slice. The number of copied elements is equal to the buf
length.
Errors
If start
is negative or start + buf.len()
is greater than array.length
then no elements are copied, an ArrayIndexOutOfBoundsException
is thrown,
and Err
is returned.
sourcepub fn get_char_array_region(
&self,
array: jcharArray,
start: jsize,
buf: &mut [jchar]
) -> Result<()>
pub fn get_char_array_region(
&self,
array: jcharArray,
start: jsize,
buf: &mut [jchar]
) -> Result<()>
Copy elements of the java char array from the start
index to the
buf
slice. The number of copied elements is equal to the buf
length.
Errors
If start
is negative or start + buf.len()
is greater than array.length
then no elements are copied, an ArrayIndexOutOfBoundsException
is thrown,
and Err
is returned.
sourcepub fn get_short_array_region(
&self,
array: jshortArray,
start: jsize,
buf: &mut [jshort]
) -> Result<()>
pub fn get_short_array_region(
&self,
array: jshortArray,
start: jsize,
buf: &mut [jshort]
) -> Result<()>
Copy elements of the java short array from the start
index to the
buf
slice. The number of copied elements is equal to the buf
length.
Errors
If start
is negative or start + buf.len()
is greater than array.length
then no elements are copied, an ArrayIndexOutOfBoundsException
is thrown,
and Err
is returned.
sourcepub fn get_int_array_region(
&self,
array: jintArray,
start: jsize,
buf: &mut [jint]
) -> Result<()>
pub fn get_int_array_region(
&self,
array: jintArray,
start: jsize,
buf: &mut [jint]
) -> Result<()>
Copy elements of the java int array from the start
index to the
buf
slice. The number of copied elements is equal to the buf
length.
Errors
If start
is negative or start + buf.len()
is greater than array.length
then no elements are copied, an ArrayIndexOutOfBoundsException
is thrown,
and Err
is returned.
sourcepub fn get_long_array_region(
&self,
array: jlongArray,
start: jsize,
buf: &mut [jlong]
) -> Result<()>
pub fn get_long_array_region(
&self,
array: jlongArray,
start: jsize,
buf: &mut [jlong]
) -> Result<()>
Copy elements of the java long array from the start
index to the
buf
slice. The number of copied elements is equal to the buf
length.
Errors
If start
is negative or start + buf.len()
is greater than array.length
then no elements are copied, an ArrayIndexOutOfBoundsException
is thrown,
and Err
is returned.
sourcepub fn get_float_array_region(
&self,
array: jfloatArray,
start: jsize,
buf: &mut [jfloat]
) -> Result<()>
pub fn get_float_array_region(
&self,
array: jfloatArray,
start: jsize,
buf: &mut [jfloat]
) -> Result<()>
Copy elements of the java float array from the start
index to the
buf
slice. The number of copied elements is equal to the buf
length.
Errors
If start
is negative or start + buf.len()
is greater than array.length
then no elements are copied, an ArrayIndexOutOfBoundsException
is thrown,
and Err
is returned.
sourcepub fn get_double_array_region(
&self,
array: jdoubleArray,
start: jsize,
buf: &mut [jdouble]
) -> Result<()>
pub fn get_double_array_region(
&self,
array: jdoubleArray,
start: jsize,
buf: &mut [jdouble]
) -> Result<()>
Copy elements of the java double array from the start
index to the
buf
slice. The number of copied elements is equal to the buf
length.
Errors
If start
is negative or start + buf.len()
is greater than array.length
then no elements are copied, an ArrayIndexOutOfBoundsException
is thrown,
and Err
is returned.
sourcepub fn set_boolean_array_region(
&self,
array: jbooleanArray,
start: jsize,
buf: &[jboolean]
) -> Result<()>
pub fn set_boolean_array_region(
&self,
array: jbooleanArray,
start: jsize,
buf: &[jboolean]
) -> Result<()>
Copy the contents of the buf
slice to the java boolean array at the
start
index.
sourcepub fn set_byte_array_region(
&self,
array: jbyteArray,
start: jsize,
buf: &[jbyte]
) -> Result<()>
pub fn set_byte_array_region(
&self,
array: jbyteArray,
start: jsize,
buf: &[jbyte]
) -> Result<()>
Copy the contents of the buf
slice to the java byte array at the
start
index.
sourcepub fn set_char_array_region(
&self,
array: jcharArray,
start: jsize,
buf: &[jchar]
) -> Result<()>
pub fn set_char_array_region(
&self,
array: jcharArray,
start: jsize,
buf: &[jchar]
) -> Result<()>
Copy the contents of the buf
slice to the java char array at the
start
index.
sourcepub fn set_short_array_region(
&self,
array: jshortArray,
start: jsize,
buf: &[jshort]
) -> Result<()>
pub fn set_short_array_region(
&self,
array: jshortArray,
start: jsize,
buf: &[jshort]
) -> Result<()>
Copy the contents of the buf
slice to the java short array at the
start
index.
sourcepub fn set_int_array_region(
&self,
array: jintArray,
start: jsize,
buf: &[jint]
) -> Result<()>
pub fn set_int_array_region(
&self,
array: jintArray,
start: jsize,
buf: &[jint]
) -> Result<()>
Copy the contents of the buf
slice to the java int array at the
start
index.
sourcepub fn set_long_array_region(
&self,
array: jlongArray,
start: jsize,
buf: &[jlong]
) -> Result<()>
pub fn set_long_array_region(
&self,
array: jlongArray,
start: jsize,
buf: &[jlong]
) -> Result<()>
Copy the contents of the buf
slice to the java long array at the
start
index.
sourcepub fn set_float_array_region(
&self,
array: jfloatArray,
start: jsize,
buf: &[jfloat]
) -> Result<()>
pub fn set_float_array_region(
&self,
array: jfloatArray,
start: jsize,
buf: &[jfloat]
) -> Result<()>
Copy the contents of the buf
slice to the java float array at the
start
index.
sourcepub fn set_double_array_region(
&self,
array: jdoubleArray,
start: jsize,
buf: &[jdouble]
) -> Result<()>
pub fn set_double_array_region(
&self,
array: jdoubleArray,
start: jsize,
buf: &[jdouble]
) -> Result<()>
Copy the contents of the buf
slice to the java double array at the
start
index.
sourcepub fn get_field_unchecked<O, T>(
&self,
obj: O,
field: T,
ty: ReturnType
) -> Result<JValue<'a>>where
O: Into<JObject<'a>>,
T: Desc<'a, JFieldID>,
pub fn get_field_unchecked<O, T>(
&self,
obj: O,
field: T,
ty: ReturnType
) -> Result<JValue<'a>>where
O: Into<JObject<'a>>,
T: Desc<'a, JFieldID>,
Get a field without checking the provided type against the actual field.
sourcepub fn set_field_unchecked<O, T>(
&self,
obj: O,
field: T,
val: JValue<'_>
) -> Result<()>where
O: Into<JObject<'a>>,
T: Desc<'a, JFieldID>,
pub fn set_field_unchecked<O, T>(
&self,
obj: O,
field: T,
val: JValue<'_>
) -> Result<()>where
O: Into<JObject<'a>>,
T: Desc<'a, JFieldID>,
Set a field without any type checking.
sourcepub fn get_field<O, S, T>(&self, obj: O, name: S, ty: T) -> Result<JValue<'a>>where
O: Into<JObject<'a>>,
S: Into<JNIString>,
T: Into<JNIString> + AsRef<str>,
pub fn get_field<O, S, T>(&self, obj: O, name: S, ty: T) -> Result<JValue<'a>>where
O: Into<JObject<'a>>,
S: Into<JNIString>,
T: Into<JNIString> + AsRef<str>,
Get a field. Requires an object class lookup and a field id lookup internally.
sourcepub fn set_field<O, S, T>(
&self,
obj: O,
name: S,
ty: T,
val: JValue<'_>
) -> Result<()>where
O: Into<JObject<'a>>,
S: Into<JNIString>,
T: Into<JNIString> + AsRef<str>,
pub fn set_field<O, S, T>(
&self,
obj: O,
name: S,
ty: T,
val: JValue<'_>
) -> Result<()>where
O: Into<JObject<'a>>,
S: Into<JNIString>,
T: Into<JNIString> + AsRef<str>,
Set a field. Does the same lookups as get_field
and ensures that the
type matches the given value.
sourcepub fn get_static_field_unchecked<'c, T, U>(
&self,
class: T,
field: U,
ty: JavaType
) -> Result<JValue<'a>>where
T: Desc<'a, JClass<'c>>,
U: Desc<'a, JStaticFieldID>,
pub fn get_static_field_unchecked<'c, T, U>(
&self,
class: T,
field: U,
ty: JavaType
) -> Result<JValue<'a>>where
T: Desc<'a, JClass<'c>>,
U: Desc<'a, JStaticFieldID>,
Get a static field without checking the provided type against the actual field.
sourcepub fn get_static_field<'c, T, U, V>(
&self,
class: T,
field: U,
sig: V
) -> Result<JValue<'a>>where
T: Desc<'a, JClass<'c>>,
U: Into<JNIString>,
V: Into<JNIString> + AsRef<str>,
pub fn get_static_field<'c, T, U, V>(
&self,
class: T,
field: U,
sig: V
) -> Result<JValue<'a>>where
T: Desc<'a, JClass<'c>>,
U: Into<JNIString>,
V: Into<JNIString> + AsRef<str>,
Get a static field. Requires a class lookup and a field id lookup internally.
sourcepub fn set_static_field<'c, T, U>(
&self,
class: T,
field: U,
value: JValue<'_>
) -> Result<()>where
T: Desc<'a, JClass<'c>>,
U: Desc<'a, JStaticFieldID>,
pub fn set_static_field<'c, T, U>(
&self,
class: T,
field: U,
value: JValue<'_>
) -> Result<()>where
T: Desc<'a, JClass<'c>>,
U: Desc<'a, JStaticFieldID>,
Set a static field. Requires a class lookup and a field id lookup internally.
sourcepub unsafe fn set_rust_field<O, S, T>(
&self,
obj: O,
field: S,
rust_object: T
) -> Result<()>where
O: Into<JObject<'a>>,
S: AsRef<str>,
T: Send + 'static,
pub unsafe fn set_rust_field<O, S, T>(
&self,
obj: O,
field: S,
rust_object: T
) -> Result<()>where
O: Into<JObject<'a>>,
S: AsRef<str>,
T: Send + 'static,
Surrenders ownership of a Rust value to Java.
This requires an object with a long
field to store the pointer.
The Rust value will be implicitly wrapped in a Box<Mutex<T>>
.
The Java object will be locked before changing the field value.
Safety
It’s important to note that using this API will leak memory if
Self::take_rust_field
is never called so that the Rust type may be
dropped.
One suggestion that may help ensure that a set Rust field will be
cleaned up later is for the Java object to implement Closeable
and let
people use a use
block (Kotlin) or try-with-resources
(Java).
DO NOT make a copy of the object containing one of these fields since that will lead to a use-after-free error if the Rust type is taken and dropped multiple times from Rust.
sourcepub unsafe fn get_rust_field<O, S, T>(
&self,
obj: O,
field: S
) -> Result<MutexGuard<'_, T>>where
O: Into<JObject<'a>>,
S: Into<JNIString>,
T: Send + 'static,
pub unsafe fn get_rust_field<O, S, T>(
&self,
obj: O,
field: S
) -> Result<MutexGuard<'_, T>>where
O: Into<JObject<'a>>,
S: Into<JNIString>,
T: Send + 'static,
Gets a lock on a Rust value that’s been given to a Java object.
Java still retains ownership and Self::take_rust_field
will still
need to be called at some point.
The Java object will be locked before reading the field value but the
Java object lock will be released after the Rust Mutex
lock for the
field value has been taken (i.e the Java object won’t be locked once
this function returns).
Safety
Checks for a null pointer, but assumes that the data it points to is valid for T.
sourcepub unsafe fn take_rust_field<O, S, T>(&self, obj: O, field: S) -> Result<T>where
O: Into<JObject<'a>>,
S: AsRef<str>,
T: Send + 'static,
pub unsafe fn take_rust_field<O, S, T>(&self, obj: O, field: S) -> Result<T>where
O: Into<JObject<'a>>,
S: AsRef<str>,
T: Send + 'static,
Take a Rust field back from Java.
It sets the field to a null pointer to signal that it’s empty.
The Java object will be locked before taking the field value.
Safety
This will make sure that the pointer is non-null, but still assumes that the data it points to is valid for T.
sourcepub fn lock_obj<O>(&self, obj: O) -> Result<MonitorGuard<'a>>where
O: Into<JObject<'a>>,
pub fn lock_obj<O>(&self, obj: O) -> Result<MonitorGuard<'a>>where
O: Into<JObject<'a>>,
Lock a Java object. The MonitorGuard that this returns is responsible for ensuring that it gets unlocked.
sourcepub fn get_native_interface(&self) -> *mut JNIEnv
pub fn get_native_interface(&self) -> *mut JNIEnv
Returns underlying sys::JNIEnv
interface.
sourcepub fn get_java_vm(&self) -> Result<JavaVM>
pub fn get_java_vm(&self) -> Result<JavaVM>
Returns the Java VM interface.
sourcepub fn ensure_local_capacity(&self, capacity: jint) -> Result<()>
pub fn ensure_local_capacity(&self, capacity: jint) -> Result<()>
Ensures that at least a given number of local references can be created in the current thread.
sourcepub fn register_native_methods<'c, T>(
&self,
class: T,
methods: &[NativeMethod]
) -> Result<()>where
T: Desc<'a, JClass<'c>>,
pub fn register_native_methods<'c, T>(
&self,
class: T,
methods: &[NativeMethod]
) -> Result<()>where
T: Desc<'a, JClass<'c>>,
Bind function pointers to native methods of class according to method name and signature. For details see documentation.
sourcepub fn unregister_native_methods<'c, T>(&self, class: T) -> Result<()>where
T: Desc<'a, JClass<'c>>,
pub fn unregister_native_methods<'c, T>(&self, class: T) -> Result<()>where
T: Desc<'a, JClass<'c>>,
Unbind all native methods of class.
sourcepub fn get_array_elements<T: TypeArray>(
&self,
array: jarray,
mode: ReleaseMode
) -> Result<AutoArray<'a, T>>
pub fn get_array_elements<T: TypeArray>(
&self,
array: jarray,
mode: ReleaseMode
) -> Result<AutoArray<'a, T>>
Return an AutoArray of the given Java array.
The result is valid until the AutoArray object goes out of scope, when the release happens automatically according to the mode parameter.
Since the returned array may be a copy of the Java array, changes made to the
returned array will not necessarily be reflected in the original array until
the corresponding Release*ArrayElements JNI method is called.
AutoArray has a commit() method, to force a copy of the array if needed (and without
releasing it).
Prefer to use the convenience wrappers:
get_int_array_elements
get_long_array_elements
get_byte_array_elements
get_boolean_array_elements
get_char_array_elements
get_short_array_elements
get_float_array_elements
get_double_array_elements
And the associated AutoArray
struct.
sourcepub fn get_int_array_elements(
&self,
array: jintArray,
mode: ReleaseMode
) -> Result<AutoArray<'a, jint>>
pub fn get_int_array_elements(
&self,
array: jintArray,
mode: ReleaseMode
) -> Result<AutoArray<'a, jint>>
See also get_array_elements
sourcepub fn get_long_array_elements(
&self,
array: jlongArray,
mode: ReleaseMode
) -> Result<AutoArray<'a, jlong>>
pub fn get_long_array_elements(
&self,
array: jlongArray,
mode: ReleaseMode
) -> Result<AutoArray<'a, jlong>>
See also get_array_elements
sourcepub fn get_byte_array_elements(
&self,
array: jbyteArray,
mode: ReleaseMode
) -> Result<AutoArray<'a, jbyte>>
pub fn get_byte_array_elements(
&self,
array: jbyteArray,
mode: ReleaseMode
) -> Result<AutoArray<'a, jbyte>>
See also get_array_elements
sourcepub fn get_boolean_array_elements(
&self,
array: jbooleanArray,
mode: ReleaseMode
) -> Result<AutoArray<'a, jboolean>>
pub fn get_boolean_array_elements(
&self,
array: jbooleanArray,
mode: ReleaseMode
) -> Result<AutoArray<'a, jboolean>>
See also get_array_elements
sourcepub fn get_char_array_elements(
&self,
array: jcharArray,
mode: ReleaseMode
) -> Result<AutoArray<'a, jchar>>
pub fn get_char_array_elements(
&self,
array: jcharArray,
mode: ReleaseMode
) -> Result<AutoArray<'a, jchar>>
See also get_array_elements
sourcepub fn get_short_array_elements(
&self,
array: jshortArray,
mode: ReleaseMode
) -> Result<AutoArray<'a, jshort>>
pub fn get_short_array_elements(
&self,
array: jshortArray,
mode: ReleaseMode
) -> Result<AutoArray<'a, jshort>>
See also get_array_elements
sourcepub fn get_float_array_elements(
&self,
array: jfloatArray,
mode: ReleaseMode
) -> Result<AutoArray<'a, jfloat>>
pub fn get_float_array_elements(
&self,
array: jfloatArray,
mode: ReleaseMode
) -> Result<AutoArray<'a, jfloat>>
See also get_array_elements
sourcepub fn get_double_array_elements(
&self,
array: jdoubleArray,
mode: ReleaseMode
) -> Result<AutoArray<'a, jdouble>>
pub fn get_double_array_elements(
&self,
array: jdoubleArray,
mode: ReleaseMode
) -> Result<AutoArray<'a, jdouble>>
See also get_array_elements
sourcepub fn get_primitive_array_critical(
&self,
array: jarray,
mode: ReleaseMode
) -> Result<AutoPrimitiveArray<'_, '_>>
pub fn get_primitive_array_critical(
&self,
array: jarray,
mode: ReleaseMode
) -> Result<AutoPrimitiveArray<'_, '_>>
Return an AutoPrimitiveArray of the given Java primitive array.
The result is valid until the corresponding AutoPrimitiveArray object goes out of scope, when the release happens automatically according to the mode parameter.
Given that Critical sections must be as short as possible, and that they come with a number of important restrictions (see GetPrimitiveArrayCritical JNI doc), use this wrapper wisely, to avoid holding the array longer that strictly necessary. In any case, you can:
- Use std::mem::drop explicitly, to force / anticipate resource release.
- Use a nested scope, to release the array at the nested scope’s exit.
Since the returned array may be a copy of the Java array, changes made to the returned array will not necessarily be reflected in the original array until ReleasePrimitiveArrayCritical is called; which happens at AutoPrimitiveArray destruction.
If the given array is null
, an Error::NullPtr
is returned.
See also get_byte_array_elements