-
Notifications
You must be signed in to change notification settings - Fork 6
Obtaining JNIEnv
Every operation in JNI requires usage of JNIEnv
object. Most of the time this is not a problem: JNIEnv *
is passed to any native method and can be propagated from there. On occasion, however, you might not have it handy. Some common situations include writing destructors which cannot have parameters (you can work around it by storing JNIEnv *
in the class but that introduces its own problems since JNIEnv
is thread specific), operating on a non-Java thread and being called from portable code that has no notion of JNIEnv
. Raw JNI provides various methods to obtain JNIEnv
which are somewhat cumbersome to use.
With SimpleJNI you can always get current JNIEnv *
by calling
JNIEnv * env = jni_provider::get_jni();
It operates as follows:
-
If the thread already has
JNIEnv
attached it will be returned. -
Otherwise the thread is attached to Java as daemon and the resulting
JNIEnv*
is returned.
Why attach as daemon? The expectation that if you call this method to obtainJNIEnv
from a non-Java thread you are unlikely to wish it to be joinable from Java. If you do want to manually add a non daemon native thread to Java you should manually do so deliberately, not as a side effect of obtainingJNIEnv
Note that the thread will be automatically detached on its exit if it was attached by SimpleJNI. You do not need to add any special handling of your own to do so.
- Building
-
User's Guide
Declaring Java Types
Accessing Methods and Fields
Representing Java Classes
Implementing Native Methods
Smart References
Error Handling
Obtaining JNIEnv
Initialization
Strings
Arrays
Direct Buffers
Booleans
Sizes -
JniGen Code Generator
Integrating JniGen
Annotations
Processor Options