diff --git a/docs/html/guide/practices/design/jni.jd b/docs/html/guide/practices/design/jni.jd index 6e984b00a8811..9980efdf0c3f4 100644 --- a/docs/html/guide/practices/design/jni.jd +++ b/docs/html/guide/practices/design/jni.jd @@ -26,9 +26,9 @@ page.title=JNI Tips -
JNI is the Java Native Interface. It defines a way for code written in the -Java programming language to interact with native -code: functions written in C/C++. It's VM-neutral, has support for loading code from +
JNI is the Java Native Interface. It defines a way for managed code +(written in the Java programming language) to interact with native +code (written in C/C++). It's vendor-neutral, has support for loading code from dynamic shared libraries, and while cumbersome at times is reasonably efficient.
You really should read through the @@ -46,13 +46,13 @@ There's a more detailed +which allow you to create and destroy a JavaVM. In theory you can have multiple JavaVMs per process, +but Android only allows one.
The JNIEnv provides most of the JNI functions. Your native functions all receive a JNIEnv as the first argument.
-On some VMs, the JNIEnv is used for thread-local storage. For this reason, you cannot share a JNIEnv between threads. +
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 GetEnv to discover the thread's JNIEnv. (Assuming it has one; see AttachCurrentThread below.)
All VM threads are Linux threads, scheduled by the kernel. They're usually
-started using Java language features (notably Thread.start),
-but they can also be created elsewhere and then attached to the VM. For
+
All threads are Linux threads, scheduled by the kernel. They're usually
+started from managed code (using Thread.start),
+but they can also be created elsewhere and then attached to the JavaVM. For
example, a thread started with pthread_create can be attached
with the JNI AttachCurrentThread or
AttachCurrentThreadAsDaemon functions. Until a thread is
-attached to the VM, it has no JNIEnv, and
-cannot make JNI calls.
Attaching a natively-created thread causes the VM to allocate and initialize
-a Thread object, add it to the "main" ThreadGroup,
-and add the thread to the set that is visible to the debugger. Calling
-AttachCurrentThread on an already-attached thread is a no-op.
Attaching a natively-created thread causes a java.lang.Thread
+object to be constructed and added to the "main" ThreadGroup,
+making it visible to the debugger. Calling AttachCurrentThread
+on an already-attached thread is a no-op.
The Dalvik VM does not suspend threads executing native code. If +
Android does not suspend threads executing native code. If garbage collection is in progress, or the debugger has issued a suspend -request, the VM will pause the thread the next time it makes a JNI call.
+request, Android will pause the thread the next time it makes a JNI call.Threads attached through JNI must call
DetachCurrentThread before they exit.
@@ -108,12 +107,12 @@ the argument.)
Similarly, to call a method, you'd first get a class object reference and then a method ID. The IDs are often just -pointers to internal VM data structures. Looking them up may require several string +pointers to internal runtime data structures. Looking them up may require several string comparisons, but once you have them the actual call to get the field or invoke the method is very quick.
If performance is important, it's useful to look the values up once and cache the results -in your native code. Because there is a limit of one VM per process, it's reasonable +in your native code. Because there is a limit of one JavaVM 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 @@ -145,13 +144,17 @@ then reloaded, it will be executed again.
Every object that JNI returns is a "local reference". This means that it's valid for the +
Every argument passed to a native method, and almost every object returned
+by a JNI function is a "local reference". This means that it's valid for the
duration of the current native method in the current thread.
-Even if the object itself continues to live on after the native method returns, the reference is not valid.
-This applies to all sub-classes of jobject, including
+Even if the object itself continues to live on after the native method
+returns, the reference is not valid.
+
This applies to all sub-classes of jobject, including
jclass, jstring, and jarray.
-(Dalvik VM will warn you about most reference mis-uses when extended JNI
+(The runtime will warn you about most reference mis-uses when extended JNI
checks are enabled.)
The only way to get non-local references is via the functions
+NewGlobalRef and NewWeakGlobalRef.
If you want to hold on to a reference for a longer period, you must use
a "global" reference. The NewGlobalRef function takes the
@@ -159,7 +162,7 @@ local reference as an argument and returns a global one.
The global reference is guaranteed to be valid until you call
DeleteGlobalRef.
This pattern is commonly used when caching copies of class objects obtained +
This pattern is commonly used when caching a jclass returned
from FindClass, e.g.:
jclass localClass = env->FindClass("MyClass");
jclass globalClass = reinterpret_cast<jclass>(env->NewGlobalRef(localClass));
@@ -181,22 +184,25 @@ not use jobject values as keys.
Programmers are required to "not excessively allocate" local references. In practical terms this means
that if you're creating large numbers of local references, perhaps while running through an array of
-Objects, you should free them manually with
+objects, you should free them manually with
DeleteLocalRef instead of letting JNI do it for you. The
-VM is only required to reserve slots for
+implementation 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.
EnsureLocalCapacity/PushLocalFrame to reserve more.
-Note that jfieldIDs and jmethodIDs are just integers, not object
-references, and should not be passed to NewGlobalRef. The raw data
+
Note that jfieldIDs and jmethodIDs are opaque
+types, 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.
GetByteArrayElements are also not objects. (They may be passed
+between threads, and are valid until the matching Release call.)
One unusual case deserves separate mention. If you attach a native
-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.
AttachCurrentThread, the code you are running will
+never automatically free local references until the thread detaches. Any local
+references you create will have to be deleted manually. In general, any native
+code that creates local references in a loop probably needs to do some manual
+deletion.
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
+
If possible, it's usually faster to operate with UTF-16 strings. Android
+currently does not require a copy in GetStringChars, whereas
+GetStringUTFChars requires an allocation and a conversion to
+UTF-8. 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
string functions return jchar* or jbyte*, which
@@ -237,9 +244,8 @@ While arrays of objects must be accessed one entry at a time, arrays of
primitives can be read and written directly as if they were declared in C.
To make the interface as efficient as possible without constraining
-the VM implementation,
-the Get<PrimitiveType>ArrayElements family of calls
-allows the VM to either return a pointer to the actual elements, or
+the VM implementation, the Get<PrimitiveType>ArrayElements
+family of calls allows the runtime to either return a pointer to the actual elements, or
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
@@ -253,7 +259,7 @@ non-NULL pointer for the isCopy argument. This is rarely
useful.
The Release call takes a mode argument that can
-have one of three values. The actions performed by the VM depend upon
+have one of three values. The actions performed by the runtime depend upon
whether it returned a pointer to the actual data or a copy of it:
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.
+elements out of it, and then releases the array. Depending upon the
+implementation, the Get call will either pin or copy the array
+contents.
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.
GetStringRegion or
-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,
@@ -369,11 +376,11 @@ you call a method (using a function like CallObjectMethod),
you must always check for an exception, because the return value is not
going to be valid if an exception was thrown.
Note that exceptions thrown by interpreted code do not "leap over" native code, -and C++ exceptions thrown by native code are not handled by Dalvik. +
Note that exceptions thrown by interpreted code do not unwind native stack
+frames, and Android does not yet support C++ exceptions.
The JNI Throw and ThrowNew instructions just
-set an exception pointer in the current thread. Upon returning to the VM from
-native code, the exception will be noted and handled appropriately.
Native code can "catch" an exception by calling ExceptionCheck or
ExceptionOccurred, and clear it with
@@ -476,23 +483,19 @@ written in C++:
This is the recommended approach, but not the only approach. The VM does -not require explicit registration, nor that you provide a +
This is the recommended approach, but not the only approach. Explicit
+registration is not required, nor is it necessary that you provide a
JNI_OnLoad function.
You can instead use "discovery" of native methods that are named in a
-specific way (see
- the JNI spec for details), though this is less desirable.
-It requires more space in the shared object symbol table,
-loading is slower because it requires string searches through all of the
-loaded shared libraries, and if a method signature is wrong you won't know
+specific way (see the JNI spec for details), though this is less desirable because if a method signature is wrong you won't know
about it until the first time the method is actually used.
One other note about JNI_OnLoad: any FindClass
calls you make from there will happen in the context of the class loader
that was used to load the shared library. Normally FindClass
uses the loader associated with the method at the top of the interpreted
-stack, or if there isn't one (because the thread was just attached to
-the VM) it uses the "system" class loader. This makes
+stack, or if there isn't one (because the thread was just attached) it uses
+the "system" class loader. This makes
JNI_OnLoad a convenient place to look up and cache class
object references.
All JNI 1.6 features are supported, with the following exceptions:
DefineClass is not implemented. Dalvik does not use
+ DefineClass is not implemented. Android does not use
Java bytecodes or class files, so passing in binary class data
- doesn't work. Translation facilities may be added in a future
- version of the VM.NewLocalRef, NewGlobalRef, and
DeleteWeakGlobalRef. (The spec strongly encourages
@@ -536,12 +538,16 @@ that use 64-bit pointers, you need to stash your native pointers in a
around this requires using explicit registration or moving the
native methods out of inner classes.
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,
+ destructor function to avoid the "thread must be detached before
+ exit" check. (The runtime also uses a pthread key destructor function,
so it'd be a race to see which gets called first.)
In logcat, you'll see:
W/dalvikvm( 880): No implementation found for native LFoo;.myfunc ()V-
This means that the VM tried to find a matching method but was unsuccessful. -Some common reasons for this are:
+This means that the runtime tried to find a matching method but was +unsuccessful. Some common reasons for this are:
extern "C". You can use arm-eabi-nm
+ with extern "C" and appropriate
+ visibility (JNIEXPORT). Note that prior to Ice Cream
+ Sandwich, the JNIEXPORT macro was incorrect, so using a new GCC with
+ an old jni.h won't work.
+ You can use arm-eabi-nm
to see the symbols as they appear in the library; if they look
mangled (something like _Z15Java_Foo_myfuncP7_JNIEnvP7_jclass
- rather than Java_Foo_myfunc) then you need to
+ rather than Java_Foo_myfunc), or if the symbol type is
+ a lowercase 't' rather than an uppercase 'T', then you need to
adjust the declaration.
If the class name looks right, you could be running into a class loader
issue. FindClass wants to start the class search in the
-class loader associated with your code. It examines the VM call stack,
+class loader associated with your code. It examines the call stack,
which will look something like:
Foo.myfunc(Native Method)
Foo.main(Foo.java:10)
@@ -623,14 +634,14 @@ finds the ClassLoader object associated with the Foo
class and uses that.
This usually does what you want. You can get into trouble if you
-create a thread outside the VM (perhaps by calling pthread_create
-and then attaching it to the VM with AttachCurrentThread).
+create a thread yourself (perhaps by calling pthread_create
+and then attaching it with AttachCurrentThread).
Now the stack trace looks like this:
dalvik.system.NativeStart.run(Native Method)
The topmost method is NativeStart.run, which isn't part of
your application. If you call FindClass from this thread, the
-VM will start in the "system" class loader instead of the one associated
+JavaVM will start in the "system" class loader instead of the one associated
with your application, so attempts to find app-specific classes will fail.
There are a few ways to work around this:
@@ -656,12 +667,12 @@ with your application, so attempts to find app-specific classes will fail.
FAQ: How do I share raw data with native code?
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
+buffer of raw data from both managed and native code. Common examples
include manipulation of bitmaps or sound samples. There are two
basic approaches.
You can store the data in a byte[]. This allows very fast
-access from code written in Java. On the native side, however, you're
+access from managed code. On the native side, however, you're
not guaranteed to be able to access the data without having to copy it. In
some implementations, GetByteArrayElements and
GetPrimitiveArrayCritical will return actual pointers to the
@@ -674,8 +685,8 @@ the JNI NewDirectByteBuffer function. Unlike regular
byte buffers, the storage is not allocated on the managed heap, and can
always be accessed directly from native code (get the address
with GetDirectBufferAddress). Depending on how direct
-byte buffer access is implemented in the VM, accessing the data from code
-written in Java can be very slow.
+byte buffer access is implemented, accessing the data from managed code
+can be very slow.
The choice of which to use depends on two factors:
@@ -688,5 +699,4 @@ written in Java can be very slow.
If there's no clear winner, use a direct byte buffer. Support for them
-is built directly into JNI, and access to them from code written in
-Java can be made faster with VM improvements.
+is built directly into JNI, and performance should improve in future releases.