From 4387335ba33344efcfa2105fa098cc877744003f Mon Sep 17 00:00:00 2001
From: Elliott Hughes JNI is the Java Native Interface. It defines a way for code written in the
Java programming language to interact with native
-code, e.g. functions written in C/C++. It's VM-neutral, has support for loading code from
+code: functions written in C/C++. It's VM-neutral, has support for loading code from
dynamic shared libraries, and while cumbersome at times is reasonably efficient. You really should read through the
@@ -40,8 +40,7 @@ dynamic shared libraries, and while cumbersome at times is reasonably efficient.
to get a sense for how JNI works and what features are available. Some
aspects of the interface aren't immediately obvious on
first reading, so you may find the next few sections handy.
-The more detailed JNI Programmer's Guide and Specification can be found
-here.UnsatisfiedLinkErrorFindClass find my class?
On some VMs, the JNIEnv is used for thread-local storage. For this reason, you cannot share a JNIEnv between threads.
If a piece of code has no other way to get its JNIEnv, you should share
-the JavaVM, and use JavaVM->GetEnv to discover the thread's JNIEnv. (Assuming it has one; see AttachCurrentThread below.)
GetEnv to discover the thread's JNIEnv. (Assuming it has one; see AttachCurrentThread below.)
The C declarations of JNIEnv and JavaVM are different from the C++
-declarations. "jni.h" provides different typedefs
-depending on whether it's included into ".c" or ".cpp". For this reason it's a bad idea to
+declarations. The "jni.h" include file provides different typedefs
+depending on whether it's included into C or C++. For this reason it's a bad idea to
include JNIEnv arguments in header files included by both languages. (Put another way: if your
-header file requires "#ifdef __cplusplus", you may have to do some extra work if anything in
+header file requires #ifdef __cplusplus, you may have to do some extra work if anything in
that header refers to JNIEnv.)
All VM threads are Linux threads, scheduled by the kernel. They're usually
-started using Java language features (notably Thread.start()),
+started using Java language features (notably Thread.start),
but they can also be created elsewhere and then attached to the VM. For
example, a thread started with pthread_create can be attached
with the JNI AttachCurrentThread or
@@ -91,7 +90,7 @@ request, the VM will pause the thread the next time it makes a JNI call.
Threads attached through JNI must call
DetachCurrentThread before they exit.
-If coding this directly is awkward, in Android >= 2.0 ("Eclair") you
+If coding this directly is awkward, in Android 2.0 (Eclair) and higher you
can use pthread_key_create to define a destructor
function that will be called before the thread exits, and
call DetachCurrentThread from there. (Use that
@@ -108,7 +107,7 @@ the argument.)
FindClassGetFieldIDGetIntFieldIf performance is important, it's useful to look the values up once and cache the results -in your native code. Because we are limiting ourselves to one VM per process, it's reasonable +in your native code. Because there is a limit of one VM per process, it's reasonable to store this data in a static local structure.
The class references, field IDs, and method IDs are guaranteed valid until the class is unloaded. Classes
are only unloaded if all classes associated with a ClassLoader can be garbage collected,
-which is rare but will not be impossible in our system. Note however that
+which is rare but will not be impossible in Android. Note however that
the jclass
is a class reference and must be protected with a call
to NewGlobalRef (see the next section).
/*
* We use a class initializer to allow the native code to cache some
- * field offsets.
+ * field offsets. This native function looks up and caches interesting
+ * class/field/method IDs. Throws on failure.
*/
+ private static native void nativeInit();
- /*
- * A native function that looks up and caches interesting
- * class/field/method IDs for this class. Returns false on failure.
- */
- native private static boolean nativeClassInit();
-
- /*
- * Invoke the native initializer when the class is loaded.
- */
static {
- if (!nativeClassInit())
- throw new RuntimeException("native init failed");
+ nativeInit();
}
-Create a nativeClassInit method in your C/C++ code that performs the ID lookups. The code +
Create a nativeClassInit method in your C/C++ code that performs the ID lookups. The code
will be executed once, when the class is initialized. If the class is ever unloaded and
-then reloaded, it will be executed again. (See the implementation of java.io.FileDescriptor
-for an example in our source tree.)
FindClass, e.g.:
jclass globalClass = reinterpret_cast<jclass>(env->NewGlobalRef(localClass));
All JNI methods accept both local and global references as arguments.
-It's possible for references to the same object to have different values;
-for example, the return values from consecutive calls to
+It's possible for references to the same object to have different values.
+For example, the return values from consecutive calls to
NewGlobalRef on the same object may be different.
To see if two references refer to the same object,
you must use the IsSameObject function. Never compare
-references with "==" in native code.
== in native code.
One consequence of this is that you
must not assume object references are constant or unique
@@ -201,13 +191,13 @@ VM is only required to reserve slots for
16 local references, so if you need more than that you should either delete as you go or use
EnsureLocalCapacity to reserve more.
Note: method and field IDs are just 32-bit identifiers, not object +
Note that jfieldIDs and jmethodIDs are just integers, not object
references, and should not be passed to NewGlobalRef. The raw data
pointers returned by functions like GetStringUTFChars
and GetByteArrayElements are also not objects.
One unusual case deserves separate mention. If you attach a native
-thread to the VM with AttachCurrentThread, the code you are running will
+thread to the VM with AttachCurrentThread, the code you are running will
never "return" to the VM until the thread detaches from the VM. Any local
references you create will have to be deleted manually unless you're going
to detach the thread soon.
It's usually best to operate with UTF-16 strings. With our current VMs, the +
It's usually best to operate with UTF-16 strings. With Android's current VMs, the
GetStringChars method
does not require a copy, whereas GetStringUTFChars requires a malloc and a UTF conversion. Note that
UTF-16 strings are not zero-terminated, and \u0000 is allowed,
so you need to hang on to the string length as well as
the string pointer.
Don't forget to Release the strings you Get. The +
Don't forget to Release the strings you Get. The
string functions return jchar* or jbyte*, which
are C-style pointers to primitive data rather than local references. They
-are guaranteed valid until Release is called, which means they are not
+are guaranteed valid until Release is called, which means they are not
released when the native method returns.
Data passed to NewStringUTF must be in Modified UTF-8 format. A
@@ -258,8 +248,8 @@ allocate some memory and make a copy. Either way, the raw pointer returned
is guaranteed to be valid until the corresponding Release call
is issued (which implies that, if the data wasn't copied, the array object
will be pinned down and can't be relocated as part of compacting the heap).
-You must Release every array you Get. Also, if the Get
-call fails, you must ensure that your code doesn't try to Release a NULL
+You must Release every array you Get. Also, if the Get
+call fails, you must ensure that your code doesn't try to Release a NULL
pointer later.
You can determine whether or not the data was copied by passing in a @@ -302,12 +292,12 @@ then discard the changes. If you know that JNI is making a new copy for you, there's no need to create another "editable" copy. If JNI is passing you the original, then you do need to make your own copy.
-Some have asserted that you can skip the Release call if
+
It is a common mistake (repeated in example code) to assume that you can skip the Release call if
*isCopy is false. This is not the case. If no copy buffer was
allocated, then the original memory must be pinned down and can't be moved by
the garbage collector.
Also note that the JNI_COMMIT flag does NOT release the array,
+
Also note that the JNI_COMMIT flag does not release the array,
and you will need to call Release again with a different flag
eventually.
GetStringChars that may be very helpful when all you want
to do is copy data in or out. Consider the following:
-
- jbyte* data = env->GetByteArrayElements(array, NULL);
+ jbyte* data = env->GetByteArrayElements(array, NULL);
if (data != NULL) {
memcpy(buffer, data, len);
env->ReleaseByteArrayElements(array, data, JNI_ABORT);
@@ -329,12 +318,11 @@ to do is copy data in or out. Consider the following:
This grabs the array, copies the first len byte
elements out of it, and then releases the array. Depending upon the VM
policies the Get call will either pin or copy the array contents.
-We copy the data (for perhaps a second time), then call Release; in this case
-we use JNI_ABORT so there's no chance of a third copy.
+The code copies the data (for perhaps a second time), then calls Release; in this case
+JNI_ABORT ensures there's no chance of a third copy.
-We can accomplish the same thing with this:
-
- env->GetByteArrayRegion(array, 0, len, buffer);
+One can accomplish the same thing more simply:
+ env->GetByteArrayRegion(array, 0, len, buffer);
This has several advantages:
GetStringRegion or
You may not call most JNI functions while an exception is pending. +
You must not call most JNI functions while an exception is pending.
Your code is expected to notice the exception (via the function's return value,
-ExceptionCheck(), or ExceptionOccurred()) and return,
+ExceptionCheck, or ExceptionOccurred) and return,
or clear the exception and handle it.
The only JNI functions that you are allowed to call while an exception is pending are:
DeleteGlobalRef
+ DeleteLocalRef
+ DeleteWeakGlobalRef
+ ExceptionCheck
+ ExceptionClear
+ ExceptionDescribe
+ ExceptionOccurred
+ MonitorExit
+ PopLocalFrame
+ PushLocalFrame
+ Release<PrimitiveType>ArrayElements
+ ReleasePrimitiveArrayCritical
+ ReleaseStringChars
+ ReleaseStringCritical
+ ReleaseStringUTFChars
Many JNI calls can throw an exception, but often provide a simpler way @@ -396,86 +384,80 @@ native code, the exception will be noted and handled appropriately.
ExceptionClear. As usual,
discarding exceptions without handling them can lead to problems.
-There are no built-in functions for manipulating the Throwable object +
There are no built-in functions for manipulating the Throwable object
itself, so if you want to (say) get the exception string you will need to
-find the Throwable class, look up the method ID for
+find the Throwable class, look up the method ID for
getMessage "()Ljava/lang/String;", invoke it, and if the result
is non-NULL use GetStringUTFChars to get something you can
-hand to printf or a LOG macro.
printf(3) or equivalent.
JNI does very little error checking. Calling SetIntField
-on an Object field will succeed, even if the field is marked
-private and final. The
-goal is to minimize the overhead on the assumption that, if you've written it in native code,
-you probably did it for performance reasons.
JNI does very little error checking. Errors usually result in a crash. Android also offers a mode called CheckJNI, where the JavaVM and JNIEnv function table pointers are switched to tables of functions that perform an extended series of checks before calling the standard implementation.
-In Dalvik, you can enable additional checks by setting the
-"-Xcheck:jni" flag. If the flag is set, the VM directs
-the JavaVM and JNIEnv pointers to a different table of functions.
-These functions perform an extended series of checks before calling the
-standard implementation.
The additional tests include:
+The additional checks include:
NewDirectByteBuffer.Call*Method JNI call: incorrect return type, static/non-static mismatch, wrong type for ‘this’ (for non-static calls) or wrong class (for static calls).DeleteGlobalRef/DeleteLocalRef on the wrong kind of reference.0, JNI_ABORT, or JNI_COMMIT).Accessibility of methods and fields (i.e. public vs. private) is not -checked.
+(Accessibility of methods and fields is still not checked: access restrictions don't apply to native code.)
-For a description of how to enable CheckJNI for Android apps, see -Controlling the Embedded VM. -It's currently enabled by default in the Android emulator and on -"engineering" device builds.
+There are several ways to enable CheckJNI.
+ +If you’re using the emulator, CheckJNI is on by default.
+ +If you have a rooted device, you can use the following sequence of commands to restart the runtime with CheckJNI enabled:
+ +adb shell stop +adb shell setprop dalvik.vm.checkjni true +adb shell start+ +
In either of these cases, you’ll see something like this in your logcat output when the runtime starts:
+ +D AndroidRuntime: CheckJNI is ON+ +
If you have a regular device, you can use the following command:
+ +adb shell setprop debug.checkjni 1+ +
This won’t affect already-running apps, but any app launched from that point on will have CheckJNI enabled. (Change the property to any other value or simply rebooting will disable CheckJNI again.) In this case, you’ll see something like this in your logcat output the next time an app starts:
+ +D Late-enabling CheckJNI-
JNI checks can be modified with the -Xjniopts command-line
-flag. Currently supported values include:
You can load native code from shared libraries with the standard
-System.loadLibrary() call. The
+System.loadLibrary call. The
preferred way to get at your native code is:
System.loadLibrary() from a static class
+System.loadLibrary from a static class
initializer. (See the earlier example, where one is used to call
-nativeClassInit().) The argument is the "undecorated"
-library name, e.g. to load "libfubar.so" you would pass in "fubar".nativeClassInit.) The argument is the "undecorated"
+library name, so to load "libfubar.so" you would pass in "fubar".
jint JNI_OnLoad(JavaVM* vm, void* reserved)JNI_OnLoad, register all of your native methods. You
should declare
-the functions static so the names don't take up space in the symbol table
+the methods "static" so the names don't take up space in the symbol table
on the device.You can also call System.load() with the full path name of the
+
You can also call System.load with the full path name of the
shared library. For Android apps, you may find it useful to get the full
path to the application's private data storage area from the context object.
For backward compatibility, you may need to be aware of:
pthread_key_create
+ pthread_key_create
destructor function to avoid the VM's "thread must be detached before
exit" check. (The VM also uses a pthread key destructor function,
so it'd be a race to see which gets called first.)
- UnsatisfiedLinkError?When working on native code it's not uncommon to see a failure like this:
java.lang.UnsatisfiedLinkError: Library foo not found
In some cases it means what it says — the library wasn't found. In
-other cases the library exists but couldn't be opened by dlopen(), and
+other cases the library exists but couldn't be opened by dlopen(3), and
the details of the failure can be found in the exception's detail message.
Common reasons why you might encounter "library not found" exceptions:
@@ -605,7 +587,7 @@ Some common reasons for this are:extern "C". You can use arm-eabi-nm
to see the symbols as they appear in the library; if they look
- mangled (e.g. _Z15Java_Foo_myfuncP7_JNIEnvP7_jclass
+ mangled (something like _Z15Java_Foo_myfuncP7_JNIEnvP7_jclass
rather than Java_Foo_myfunc) then you need to
adjust the declaration.
byte and 'Z' is boolean.
Class name components in signatures start with 'L', end with ';',
use '/' to separate package/class names, and use '$' to separate
- inner-class names
- (e.g. Ljava/util/Map$Entry;).
+ inner-class names (Ljava/util/Map$Entry;, say).
@@ -624,11 +605,11 @@ avoid some problems.
-FindClass find my class?Make sure that the class name string has the correct format. JNI class
names start with the package name and are separated with slashes,
-e.g. java/lang/String. If you're looking up an array class,
+such as java/lang/String. If you're looking up an array class,
you need to start with the appropriate number of square brackets and
must also wrap the class with 'L' and ';', so a one-dimensional array of
String would be [Ljava/lang/String;.
FindClass
will use the correct class loader.
Foo.class in.
+ it, by declaring your native method to take a Class argument and
+ then passing Foo.class in.
ClassLoader object somewhere
handy, and issue loadClass calls directly. This requires
some effort.
@@ -676,7 +657,7 @@ with your application, so attempts to find app-specific classes will fail.
-You may find yourself in a situation where you need to access a large buffer of raw data from code written in Java and C/C++. Common examples