Struct jni::AttachGuard [−][src]
pub struct AttachGuard<'a> { /* fields omitted */ }
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>>
Get the java version that we’re being executed from.
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.
Load a class from a buffer of raw class data. The name of the class is inferred from the buffer.
Returns the superclass for a particular class OR JObject::null()
for java.lang.Object
or
an interface. As with find_class
, takes a descriptor.
Tests whether class1 is assignable from class2.
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.
Returns true if ref1 and ref2 refer to the same Java object, or are both NULL
. Otherwise,
returns false.
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");
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");
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.
Print exception information to the console.
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.
Abort the JVM with an error message.
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.
Create a new instance of a direct java.nio.ByteBuffer.
Returns the starting address of the memory of the direct java.nio.ByteBuffer.
Returns the capacity of the direct java.nio.ByteBuffer.
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.
Create a new local ref to an object.
Note that the object passed to this is already a local ref. This creates yet another reference to it, which is most likely not what you want.
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.).
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.
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.
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
.
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.
Allocates a new object from a class descriptor without running a constructor.
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;");
pub fn get_static_method_id<'c, T, U, V>(
&self,
class: T,
name: U,
sig: V
) -> Result<JStaticMethodID<'a>> 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<'a>> 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;");
Look up the field ID for a class/name/type combination.
Example
let field_id = env.get_field_id("com/my/Class", "intField", "I");
pub fn get_static_field_id<'c, T, U, V>(
&self,
class: T,
name: U,
sig: V
) -> Result<JStaticFieldID<'a>> 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<'a>> 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");
Get the class for an object.
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.
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.
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.
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.
Create a new object using a constructor. This is done safely using
checks similar to those in call_static_method
.
Create a new object using a constructor. Arguments aren’t checked
because
of the JMethodID
usage.
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.
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.
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.
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.
Unpin the array returned by get_string_utf_chars
.
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.
Get the length of a java array
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>>,
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.
pub 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.
pub 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.
Create a new java byte array from a rust byte slice.
Converts a java byte array to a rust vector of bytes.
Create a new java boolean array of supplied length.
Create a new java byte array of supplied length.
Create a new java char array of supplied length.
Create a new java short array of supplied length.
Create a new java int array of supplied length.
Create a new java long array of supplied length.
Create a new java float array of supplied length.
Create a new java double array of supplied length.
pub 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.
pub 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.
pub 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.
pub 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.
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.
pub 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.
pub 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.
pub 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.
pub 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.
pub 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.
pub 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.
pub 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.
Copy the contents of the buf
slice to the java int array at the
start
index.
pub 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.
pub 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.
pub 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.
Get a field without checking the provided type against the actual field.
Set a field without any type checking.
Get a field. Requires an object class lookup and a field id lookup internally.
Set a field. Does the same lookups as get_field
and ensures that the
type matches the given value.
pub fn get_static_field_unchecked<'c, 'f, T, U>(
&self,
class: T,
field: U,
ty: JavaType
) -> Result<JValue<'a>> where
T: Desc<'a, JClass<'c>>,
U: Desc<'a, JStaticFieldID<'f>>,
pub fn get_static_field_unchecked<'c, 'f, T, U>(
&self,
class: T,
field: U,
ty: JavaType
) -> Result<JValue<'a>> where
T: Desc<'a, JClass<'c>>,
U: Desc<'a, JStaticFieldID<'f>>,
Get a static field without checking the provided type against the actual field.
Get a static field. Requires a class lookup and a field id lookup internally.
pub fn set_static_field<'c, 'f, T, U>(
&self,
class: T,
field: U,
value: JValue<'_>
) -> Result<()> where
T: Desc<'a, JClass<'c>>,
U: Desc<'a, JStaticFieldID<'f>>,
pub fn set_static_field<'c, 'f, T, U>(
&self,
class: T,
field: U,
value: JValue<'_>
) -> Result<()> where
T: Desc<'a, JClass<'c>>,
U: Desc<'a, JStaticFieldID<'f>>,
Set a static field. Requires a class lookup and a field id lookup internally.
Surrenders ownership of a rust object to Java. Requires an object with a
long
field to store the pointer. The Rust value will be wrapped in a
Mutex since Java will be controlling where it’ll be used thread-wise.
Unsafe because it leaks memory if take_rust_field
is never called (so
be sure to make a finalizer).
DO NOT make a copy of the object containing one of these fields. If you’ve set up a finalizer to pass it back to Rust upon being GC’d, it will point to invalid memory and will likely attempt to be deallocated again.
pub 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 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 take_rust_field
will still need to be
called at some point. Checks for a null pointer, but assumes that the
data it points to is valid for T.
Take a Rust field back from Java. Makes sure that the pointer is non-null, but still assumes that the data it points to is valid for T. Sets the field to a null pointer to signal that it’s empty.
This will return an error in the event that there’s an outstanding lock on the object.
Lock a Java object. The MonitorGuard that this returns is responsible for ensuring that it gets unlocked.
Returns underlying sys::JNIEnv
interface.
Returns the Java VM interface.
Ensures that at least a given number of local references can be created in the current thread.
pub 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.
Unbind all native methods of class.
pub fn get_array_elements<T: TypeArray>(
&self,
array: jarray,
mode: ReleaseMode
) -> Result<AutoArray<'_, '_, T>>
pub fn get_array_elements<T: TypeArray>(
&self,
array: jarray,
mode: ReleaseMode
) -> Result<AutoArray<'_, '_, 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.
pub fn get_int_array_elements(
&self,
array: jintArray,
mode: ReleaseMode
) -> Result<AutoArray<'_, '_, jint>>
pub fn get_int_array_elements(
&self,
array: jintArray,
mode: ReleaseMode
) -> Result<AutoArray<'_, '_, jint>>
See also get_array_elements
pub fn get_long_array_elements(
&self,
array: jlongArray,
mode: ReleaseMode
) -> Result<AutoArray<'_, '_, jlong>>
pub fn get_long_array_elements(
&self,
array: jlongArray,
mode: ReleaseMode
) -> Result<AutoArray<'_, '_, jlong>>
See also get_array_elements
pub fn get_byte_array_elements(
&self,
array: jbyteArray,
mode: ReleaseMode
) -> Result<AutoArray<'_, '_, jbyte>>
pub fn get_byte_array_elements(
&self,
array: jbyteArray,
mode: ReleaseMode
) -> Result<AutoArray<'_, '_, jbyte>>
See also get_array_elements
pub fn get_boolean_array_elements(
&self,
array: jbooleanArray,
mode: ReleaseMode
) -> Result<AutoArray<'_, '_, jboolean>>
pub fn get_boolean_array_elements(
&self,
array: jbooleanArray,
mode: ReleaseMode
) -> Result<AutoArray<'_, '_, jboolean>>
See also get_array_elements
pub fn get_char_array_elements(
&self,
array: jcharArray,
mode: ReleaseMode
) -> Result<AutoArray<'_, '_, jchar>>
pub fn get_char_array_elements(
&self,
array: jcharArray,
mode: ReleaseMode
) -> Result<AutoArray<'_, '_, jchar>>
See also get_array_elements
pub fn get_short_array_elements(
&self,
array: jshortArray,
mode: ReleaseMode
) -> Result<AutoArray<'_, '_, jshort>>
pub fn get_short_array_elements(
&self,
array: jshortArray,
mode: ReleaseMode
) -> Result<AutoArray<'_, '_, jshort>>
See also get_array_elements
pub fn get_float_array_elements(
&self,
array: jfloatArray,
mode: ReleaseMode
) -> Result<AutoArray<'_, '_, jfloat>>
pub fn get_float_array_elements(
&self,
array: jfloatArray,
mode: ReleaseMode
) -> Result<AutoArray<'_, '_, jfloat>>
See also get_array_elements
pub fn get_double_array_elements(
&self,
array: jdoubleArray,
mode: ReleaseMode
) -> Result<AutoArray<'_, '_, jdouble>>
pub fn get_double_array_elements(
&self,
array: jdoubleArray,
mode: ReleaseMode
) -> Result<AutoArray<'_, '_, jdouble>>
See also get_array_elements
pub 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