blob: 3e9ddc4ba1d1101cdabb1d5c3f735712842737a5 [file] [log] [blame]
Elliott Hughes10c7ceb2011-04-13 19:01:11 -07001page.title=JNI Tips
2@jd:body
3
4<div id="qv-wrapper">
5<div id="qv">
6
7<h2>In this document</h2>
8<ol>
9 <li><a href="#what">What is JNI?</a></li>
10 <li><a href="#JavaVM_and_JNIEnv">JavaVM and JNIEnv</a></li>
11 <li><a href="#threads">Threads</a></li>
12 <li><a href="#jclass_jmethodID_and_jfieldID">jclass, jmethodID, and jfieldID</a></li>
13 <li><a href="#local_and_global_references">Local and Global References</a></li>
14 <li><a href="#UTF_8_and_UTF_16_strings">UTF-8 and UTF-16 Strings</a></li>
15 <li><a href="#arrays">Primitive Arrays</a></li>
16 <li><a href="#region_calls">Region Calls</a></li>
17 <li><a href="#exceptions">Exceptions</a></li>
18 <li><a href="#extended_checking">Extended Checking</a> </li>
19 <li><a href="#native_libraries">Native Libraries</a></li>
20 <li><a href="#64_bit">64-bit Considerations</a></li>
21 <li><a href="#unsupported">Unsupported Features</a></li>
22 <li><a href="#faq_ULE">FAQ: UnsatisfiedLinkError</a></li>
23 <li><a href="#faq_FindClass">FAQ: FindClass didn't find my class</a></li>
24 <li><a href="#faq_sharing">FAQ: Sharing raw data with native code</a></li>
25</ol>
26
27</div>
28</div>
29
30<a name="what_is_jni" id="what_is_jni"></a>
31<h2>What is JNI?</h2>
32
33<p>JNI is the Java Native Interface. It defines a way for code written in the
34Java programming language to interact with native
35code, e.g. functions written in C/C++. It's VM-neutral, has support for loading code from
36dynamic shared libraries, and while cumbersome at times is reasonably efficient.</p>
37
38<p>You really should read through the
Elliott Hughesf2433432011-04-13 19:01:11 -070039<a href="http://java.sun.com/javase/6/docs/technotes/guides/jni/spec/jniTOC.html">JNI spec for J2SE 6</a>
Elliott Hughes10c7ceb2011-04-13 19:01:11 -070040to get a sense for how JNI works and what features are available. Some
41aspects of the interface aren't immediately obvious on
42first reading, so you may find the next few sections handy.
43The more detailed <i>JNI Programmer's Guide and Specification</i> can be found
44<a href="http://java.sun.com/docs/books/jni/html/jniTOC.html">here</a>.</p>
45
46
47<a name="JavaVM_and_JNIEnv" id="JavaVM_and_JNIEnv"></a>
48<h2>JavaVM and JNIEnv</h2>
49
50<p>JNI defines two key data structures, "JavaVM" and "JNIEnv". Both of these are essentially
Elliott Hughesf2433432011-04-13 19:01:11 -070051pointers to pointers to function tables. (In the C++ version, they're classes with a
52pointer to a function table and a member function for each JNI function that indirects through
53the table.) The JavaVM provides the "invocation interface" functions,
Elliott Hughes10c7ceb2011-04-13 19:01:11 -070054which allow you to create and destroy the VM. In theory you can have multiple VMs per process,
55but Android's VM only allows one.</p>
56
57<p>The JNIEnv provides most of the JNI functions. Your native functions all receive a JNIEnv as
58the first argument.</p>
59
60<p>On some VMs, the JNIEnv is used for thread-local storage. For this reason, <strong>you cannot share a JNIEnv between threads</strong>.
61If a piece of code has no other way to get its JNIEnv, you should share
Elliott Hughesf2433432011-04-13 19:01:11 -070062the JavaVM, and use JavaVM-&gt;GetEnv to discover the thread's JNIEnv. (Assuming it has one; see <code>AttachCurrentThread</code> below.)</p>
Elliott Hughes10c7ceb2011-04-13 19:01:11 -070063
64<p>The C declarations of JNIEnv and JavaVM are different from the C++
65declarations. "jni.h" provides different typedefs
66depending on whether it's included into ".c" or ".cpp". For this reason it's a bad idea to
67include JNIEnv arguments in header files included by both languages. (Put another way: if your
68header file requires "#ifdef __cplusplus", you may have to do some extra work if anything in
69that header refers to JNIEnv.)</p>
70
71<a name="threads" id="threads"></a>
72<h2>Threads</h2>
73
74<p>All VM threads are Linux threads, scheduled by the kernel. They're usually
75started using Java language features (notably <code>Thread.start()</code>),
76but they can also be created elsewhere and then attached to the VM. For
77example, a thread started with <code>pthread_create</code> can be attached
78with the JNI <code>AttachCurrentThread</code> or
79<code>AttachCurrentThreadAsDaemon</code> functions. Until a thread is
80attached to the VM, it has no JNIEnv, and
81<strong>cannot make JNI calls</strong>.</p>
82
83<p>Attaching a natively-created thread causes the VM to allocate and initialize
84a <code>Thread</code> object, add it to the "main" <code>ThreadGroup</code>,
85and add the thread to the set that is visible to the debugger. Calling
86<code>AttachCurrentThread</code> on an already-attached thread is a no-op.</p>
87
88<p>The Dalvik VM does not suspend threads executing native code. If
89garbage collection is in progress, or the debugger has issued a suspend
90request, the VM will pause the thread the next time it makes a JNI call.</p>
91
92<p>Threads attached through JNI <strong>must call
93<code>DetachCurrentThread</code> before they exit</strong>.
Elliott Hughesf2433432011-04-13 19:01:11 -070094If coding this directly is awkward, in Android &gt;= 2.0 ("Eclair") you
Elliott Hughes10c7ceb2011-04-13 19:01:11 -070095can use <code>pthread_key_create</code> to define a destructor
96function that will be called before the thread exits, and
97call <code>DetachCurrentThread</code> from there. (Use that
98key with <code>pthread_setspecific</code> to store the JNIEnv in
99thread-local-storage; that way it'll be passed into your destructor as
100the argument.)</p>
101
Elliott Hughesf2433432011-04-13 19:01:11 -0700102
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700103<a name="jclass_jmethodID_and_jfieldID" id="jclass_jmethodID_and_jfieldID"></a>
104<h2>jclass, jmethodID, and jfieldID</h2>
105
106<p>If you want to access an object's field from native code, you would do the following:</p>
107
108<ul>
109<li> Get the class object reference for the class with <code>FindClass</code></li>
110<li> Get the field ID for the field with <code>GetFieldID</code></li>
111<li> Get the contents of the field with something appropriate, e.g.
112<code>GetIntField</code></li>
113</ul>
114
115<p>Similarly, to call a method, you'd first get a class object reference and then a method ID. The IDs are often just
116pointers to internal VM data structures. Looking them up may require several string
117comparisons, but once you have them the actual call to get the field or invoke the method
118is very quick.</p>
119
120<p>If performance is important, it's useful to look the values up once and cache the results
121in your native code. Because we are limiting ourselves to one VM per process, it's reasonable
122to store this data in a static local structure.</p>
123
124<p>The class references, field IDs, and method IDs are guaranteed valid until the class is unloaded. Classes
125are only unloaded if all classes associated with a ClassLoader can be garbage collected,
126which is rare but will not be impossible in our system. Note however that
127the <code>jclass</code>
128is a class reference and <strong>must be protected</strong> with a call
129to <code>NewGlobalRef</code> (see the next section).</p>
130
131<p>If you would like to cache the IDs when a class is loaded, and automatically re-cache them
132if the class is ever unloaded and reloaded, the correct way to initialize
133the IDs is to add a piece of code that looks like this to the appropriate class:</p>
134
135<pre> /*
136 * We use a class initializer to allow the native code to cache some
137 * field offsets.
138 */
139
140 /*
141 * A native function that looks up and caches interesting
142 * class/field/method IDs for this class. Returns false on failure.
143 */
144 native private static boolean nativeClassInit();
145
146 /*
147 * Invoke the native initializer when the class is loaded.
148 */
149 static {
150 if (!nativeClassInit())
151 throw new RuntimeException("native init failed");
152 }</pre>
Elliott Hughesf2433432011-04-13 19:01:11 -0700153
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700154<p>Create a nativeClassInit method in your C/C++ code that performs the ID lookups. The code
155will be executed once, when the class is initialized. If the class is ever unloaded and
156then reloaded, it will be executed again. (See the implementation of java.io.FileDescriptor
157for an example in our source tree.)</p>
158
159<a name="local_and_global_references" id="local_and_global_references"></a>
160<h2>Local and Global References</h2>
161
162<p>Every object that JNI returns is a "local reference". This means that it's valid for the
163duration of the current native method in the current thread.
164<strong>Even if the object itself continues to live on after the native method returns, the reference is not valid.</strong>
165This applies to all sub-classes of <code>jobject</code>, including
166<code>jclass</code>, <code>jstring</code>, and <code>jarray</code>.
167(Dalvik VM will warn you about most reference mis-uses when extended JNI
168checks are enabled.)</p>
169
170<p>If you want to hold on to a reference for a longer period, you must use
171a "global" reference. The <code>NewGlobalRef</code> function takes the
172local reference as an argument and returns a global one.
173The global reference is guaranteed to be valid until you call
174<code>DeleteGlobalRef</code>.</p>
175
176<p>This pattern is commonly used when caching copies of class objects obtained
177from <code>FindClass</code>, e.g.:</p>
178<pre>jclass* localClass = env-&gt;FindClass("MyClass");
179jclass* globalClass = (jclass*) env-&gt;NewGlobalRef(localClass);</pre>
180
181<p>All JNI methods accept both local and global references as arguments.
182It's possible for references to the same object to have different values;
183for example, the return values from consecutive calls to
184<code>NewGlobalRef</code> on the same object may be different.
185<strong>To see if two references refer to the same object,
186you must use the <code>IsSameObject</code> function.</strong> Never compare
187references with "==" in native code.</p>
188
189<p>One consequence of this is that you
190<strong>must not assume object references are constant or unique</strong>
191in native code. The 32-bit value representing an object may be different
192from one invocation of a method to the next, and it's possible that two
193different objects could have the same 32-bit value on consecutive calls. Do
194not use <code>jobject</code> values as keys.</p>
195
196<p>Programmers are required to "not excessively allocate" local references. In practical terms this means
197that if you're creating large numbers of local references, perhaps while running through an array of
198Objects, you should free them manually with
199<code>DeleteLocalRef</code> instead of letting JNI do it for you. The
200VM is only required to reserve slots for
20116 local references, so if you need more than that you should either delete as you go or use
202<code>EnsureLocalCapacity</code> to reserve more.</p>
203
204<p>Note: method and field IDs are just 32-bit identifiers, not object
205references, and should not be passed to <code>NewGlobalRef</code>. The raw data
206pointers returned by functions like <code>GetStringUTFChars</code>
207and <code>GetByteArrayElements</code> are also not objects.</p>
208
209<p>One unusual case deserves separate mention. If you attach a native
210thread to the VM with AttachCurrentThread, the code you are running will
211never "return" to the VM until the thread detaches from the VM. Any local
212references you create will have to be deleted manually unless you're going
213to detach the thread soon.</p>
214
215<a name="UTF_8_and_UTF_16_strings" id="UTF_8_and_UTF_16_strings"></a>
216<h2>UTF-8 and UTF-16 Strings</h2>
217
218<p>The Java programming language uses UTF-16. For convenience, JNI provides methods that work with "modified UTF-8" encoding
219as well. (Some VMs use the modified UTF-8 internally to store strings; ours do not.) The
220modified encoding only supports the 8- and 16-bit forms, and stores ASCII NUL values in a 16-bit encoding.
221The nice thing about it is that you can count on having C-style zero-terminated strings,
222suitable for use with standard libc string functions. The down side is that you cannot pass
223arbitrary UTF-8 data into the VM and expect it to work correctly.</p>
224
225<p>It's usually best to operate with UTF-16 strings. With our current VMs, the
226<code>GetStringChars</code> method
227does not require a copy, whereas <code>GetStringUTFChars</code> requires a malloc and a UTF conversion. Note that
228<strong>UTF-16 strings are not zero-terminated</strong>, and \u0000 is allowed,
229so you need to hang on to the string length as well as
230the string pointer.</p>
231
232<p><strong>Don't forget to Release the strings you Get</strong>. The
233string functions return <code>jchar*</code> or <code>jbyte*</code>, which
234are C-style pointers to primitive data rather than local references. They
235are guaranteed valid until Release is called, which means they are not
236released when the native method returns.</p>
237
238<p><strong>Data passed to NewStringUTF must be in "modified" UTF-8 format</strong>. A
239common mistake is reading character data from a file or network stream
240and handing it to <code>NewStringUTF</code> without filtering it.
241Unless you know the data is 7-bit ASCII, you need to strip out high-ASCII
242characters or convert them to proper "modified" UTF-8 form. If you don't,
243the UTF-16 conversion will likely not be what you expect. The extended
244JNI checks will scan strings and warn you about invalid data, but they
245won't catch everything.</p>
246
247<a name="arrays" id="arrays"></a>
248<h2>Primitive Arrays</h2>
249
250<p>JNI provides functions for accessing the contents of array objects.
251While arrays of objects must be accessed one entry at a time, arrays of
252primitives can be read and written directly as if they were declared in C.</p>
253
254<p>To make the interface as efficient as possible without constraining
255the VM implementation,
256the <code>Get&lt;PrimitiveType&gt;ArrayElements</code> family of calls
257allows the VM to either return a pointer to the actual elements, or
258allocate some memory and make a copy. Either way, the raw pointer returned
259is guaranteed to be valid until the corresponding <code>Release</code> call
260is issued (which implies that, if the data wasn't copied, the array object
261will be pinned down and can't be relocated as part of compacting the heap).
262<strong>You must Release every array you Get.</strong> Also, if the Get
263call fails, you must ensure that your code doesn't try to Release a NULL
264pointer later.</p>
265
266<p>You can determine whether or not the data was copied by passing in a
267non-NULL pointer for the <code>isCopy</code> argument. This is rarely
268useful.</p>
269
270<p>The <code>Release</code> call takes a <code>mode</code> argument that can
271have one of three values. The actions performed by the VM depend upon
272whether it returned a pointer to the actual data or a copy of it:</p>
273
274<ul>
275 <li><code>0</code>
276 <ul>
277 <li>Actual: the array object is un-pinned.
278 <li>Copy: data is copied back. The buffer with the copy is freed.
279 </ul>
280 <li><code>JNI_COMMIT</code>
281 <ul>
282 <li>Actual: does nothing.
283 <li>Copy: data is copied back. The buffer with the copy
284 <strong>is not freed</strong>.
285 </ul>
286 <li><code>JNI_ABORT</code>
287 <ul>
288 <li>Actual: the array object is un-pinned. Earlier
289 writes are <strong>not</strong> aborted.
290 <li>Copy: the buffer with the copy is freed; any changes to it are lost.
291 </ul>
292</ul>
293
294<p>One reason for checking the <code>isCopy</code> flag is to know if
295you need to call <code>Release</code> with <code>JNI_COMMIT</code>
296after making changes to an array &mdash; if you're alternating between making
297changes and executing code that uses the contents of the array, you may be
298able to
299skip the no-op commit. Another possible reason for checking the flag is for
300efficient handling of <code>JNI_ABORT</code>. For example, you might want
301to get an array, modify it in place, pass pieces to other functions, and
302then discard the changes. If you know that JNI is making a new copy for
303you, there's no need to create another "editable" copy. If JNI is passing
304you the original, then you do need to make your own copy.</p>
305
306<p>Some have asserted that you can skip the <code>Release</code> call if
307<code>*isCopy</code> is false. This is not the case. If no copy buffer was
308allocated, then the original memory must be pinned down and can't be moved by
309the garbage collector.</p>
310
311<p>Also note that the <code>JNI_COMMIT</code> flag does NOT release the array,
312and you will need to call <code>Release</code> again with a different flag
313eventually.</p>
314
315
316<a name="region_calls" id="region_calls"></a>
317<h2>Region Calls</h2>
318
319<p>There is an alternative to calls like <code>Get&lt;Type&gt;ArrayElements</code>
320and <code>GetStringChars</code> that may be very helpful when all you want
321to do is copy data in or out. Consider the following:</p>
322
323<pre>
324 jbyte* data = env->GetByteArrayElements(array, NULL);
325 if (data != NULL) {
326 memcpy(buffer, data, len);
327 env->ReleaseByteArrayElements(array, data, JNI_ABORT);
328 }</pre>
Elliott Hughesf2433432011-04-13 19:01:11 -0700329
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700330<p>This grabs the array, copies the first <code>len</code> byte
331elements out of it, and then releases the array. Depending upon the VM
332policies the <code>Get</code> call will either pin or copy the array contents.
333We copy the data (for perhaps a second time), then call Release; in this case
334we use <code>JNI_ABORT</code> so there's no chance of a third copy.</p>
335
336<p>We can accomplish the same thing with this:</p>
337<pre>
338 env->GetByteArrayRegion(array, 0, len, buffer);</pre>
Elliott Hughesf2433432011-04-13 19:01:11 -0700339
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700340<p>This has several advantages:</p>
341<ul>
342 <li>Requires one JNI call instead of 2, reducing overhead.
343 <li>Doesn't require pinning or extra data copies.
344 <li>Reduces the risk of programmer error &mdash; no risk of forgetting
345 to call <code>Release</code> after something fails.
346</ul>
347
348<p>Similarly, you can use the <code>Set&lt;Type&gt;ArrayRegion</code> call
349to copy data into an array, and <code>GetStringRegion</code> or
350<code>GetStringUTFRegion</code> to copy characters out of a
351<code>String</code>.
352
353
354<a name="exceptions" id="exceptions"></a>
355<h2>Exception</h2>
356
357<p><strong>You may not call most JNI functions while an exception is pending.</strong>
358Your code is expected to notice the exception (via the function's return value,
359<code>ExceptionCheck()</code>, or <code>ExceptionOccurred()</code>) and return,
360or clear the exception and handle it.</p>
361
362<p>The only JNI functions that you are allowed to call while an exception is
363pending are:</p>
364<ul>
365 <li>DeleteGlobalRef
366 <li>DeleteLocalRef
367 <li>DeleteWeakGlobalRef
368 <li>ExceptionCheck
369 <li>ExceptionClear
370 <li>ExceptionDescribe
371 <li>ExceptionOccurred
372 <li>MonitorExit
373 <li>PopLocalFrame
374 <li>PushLocalFrame
375 <li>Release&lt;PrimitiveType&gt;ArrayElements
376 <li>ReleasePrimitiveArrayCritical
377 <li>ReleaseStringChars
378 <li>ReleaseStringCritical
379 <li>ReleaseStringUTFChars
380</ul>
381
382<p>Many JNI calls can throw an exception, but often provide a simpler way
383of checking for failure. For example, if <code>NewString</code> returns
384a non-NULL value, you don't need to check for an exception. However, if
385you call a method (using a function like <code>CallObjectMethod</code>),
386you must always check for an exception, because the return value is not
387going to be valid if an exception was thrown.</p>
388
389<p>Note that exceptions thrown by interpreted code do not "leap over" native code,
390and C++ exceptions thrown by native code are not handled by Dalvik.
391The JNI <code>Throw</code> and <code>ThrowNew</code> instructions just
392set an exception pointer in the current thread. Upon returning to the VM from
393native code, the exception will be noted and handled appropriately.</p>
394
395<p>Native code can "catch" an exception by calling <code>ExceptionCheck</code> or
396<code>ExceptionOccurred</code>, and clear it with
397<code>ExceptionClear</code>. As usual,
398discarding exceptions without handling them can lead to problems.</p>
399
400<p>There are no built-in functions for manipulating the Throwable object
401itself, so if you want to (say) get the exception string you will need to
402find the Throwable class, look up the method ID for
403<code>getMessage "()Ljava/lang/String;"</code>, invoke it, and if the result
404is non-NULL use <code>GetStringUTFChars</code> to get something you can
405hand to printf or a LOG macro.</p>
406
407
408<a name="extended_checking" id="extended_checking"></a>
409<h2>Extended Checking</h2>
410
411<p>JNI does very little error checking. Calling <code>SetIntField</code>
412on an Object field will succeed, even if the field is marked
413<code>private</code> and <code>final</code>. The
414goal is to minimize the overhead on the assumption that, if you've written it in native code,
415you probably did it for performance reasons.</p>
416
417<p>In Dalvik, you can enable additional checks by setting the
418"<code>-Xcheck:jni</code>" flag. If the flag is set, the VM directs
419the JavaVM and JNIEnv pointers to a different table of functions.
420These functions perform an extended series of checks before calling the
421standard implementation.</p>
422
423<p>The additional tests include:</p>
424
425<ul>
426<li> Check for null pointers where not allowed.</li>
427<li> Verify argument type correctness (jclass is a class object,
428jfieldID points to field data, jstring is a java.lang.String).</li>
429<li> Field type correctness, e.g. don't store a HashMap in a String field.</li>
430<li> Ensure jmethodID is appropriate when making a static or virtual
431method call.</li>
432<li> Check to see if an exception is pending on calls where pending exceptions are not legal.</li>
433<li> Check for calls to inappropriate functions between Critical get/release calls.</li>
434<li> Check that JNIEnv structs aren't being shared between threads.</li>
435<li> Make sure local references aren't used outside their allowed lifespan.</li>
436<li> UTF-8 strings contain only valid "modified UTF-8" data.</li>
437</ul>
438
439<p>Accessibility of methods and fields (i.e. public vs. private) is not
440checked.</p>
441
442<p>For a description of how to enable CheckJNI for Android apps, see
443<a href="embedded-vm-control.html">Controlling the Embedded VM</a>.
444It's currently enabled by default in the Android emulator and on
445"engineering" device builds.</p>
446
447<p>JNI checks can be modified with the <code>-Xjniopts</code> command-line
448flag. Currently supported values include:</p>
449
450<dl>
451<dt>forcecopy
452<dd>When set, any function that can return a copy of the original data
453(array of primitive values, UTF-16 chars) will always do so. The buffers
454are over-allocated and surrounded with a guard pattern to help identify
455code writing outside the buffer, and the contents are erased before the
456storage is freed to trip up code that uses the data after calling Release.
457This will have a noticeable performance impact on some applications.
458<dt>warnonly
459<dd>By default, JNI "warnings" cause the VM to abort. With this flag
460it continues on.
461</dl>
462
463
464<a name="native_libraries" id="native_libraries"></a>
465<h2>Native Libraries</h2>
466
467<p>You can load native code from shared libraries with the standard
468<code>System.loadLibrary()</code> call. The
469preferred way to get at your native code is:</p>
470
471<ul>
472<li> Call <code>System.loadLibrary()</code> from a static class
473initializer. (See the earlier example, where one is used to call
474<code>nativeClassInit()</code>.) The argument is the "undecorated"
475library name, e.g. to load "libfubar.so" you would pass in "fubar".</li>
476<li> Provide a native function: <code><strong>jint JNI_OnLoad(JavaVM* vm, void* reserved)</strong></code></li>
477<li>In <code>JNI_OnLoad</code>, register all of your native methods. You
478should declare
479the methods "static" so the names don't take up space in the symbol table
480on the device.</li>
481</ul>
482
483<p>The <code>JNI_OnLoad</code> function should look something like this if
484written in C:</p>
485<pre>jint JNI_OnLoad(JavaVM* vm, void* reserved)
486{
487 JNIEnv* env;
488 if ((*vm)->GetEnv(vm, (void**) &env, JNI_VERSION_1_6) != JNI_OK)
489 return -1;
490
491 /* get class with (*env)->FindClass */
492 /* register methods with (*env)->RegisterNatives */
493
494 return JNI_VERSION_1_6;
495}</pre>
496
497<p>You can also call <code>System.load()</code> with the full path name of the
498shared library. For Android apps, you may find it useful to get the full
499path to the application's private data storage area from the context object.</p>
500
501<p>This is the recommended approach, but not the only approach. The VM does
502not require explicit registration, nor that you provide a
503<code>JNI_OnLoad</code> function.
504You can instead use "discovery" of native methods that are named in a
505specific way (see <a href="http://java.sun.com/javase/6/docs/technotes/guides/jni/spec/design.html#wp615">
506 the JNI spec</a> for details), though this is less desirable.
507It requires more space in the shared object symbol table,
508loading is slower because it requires string searches through all of the
509loaded shared libraries, and if a method signature is wrong you won't know
510about it until the first time the method is actually used.</p>
511
512<p>One other note about <code>JNI_OnLoad</code>: any <code>FindClass</code>
513calls you make from there will happen in the context of the class loader
514that was used to load the shared library. Normally <code>FindClass</code>
515uses the loader associated with the method at the top of the interpreted
516stack, or if there isn't one (because the thread was just attached to
517the VM) it uses the "system" class loader. This makes
518<code>JNI_OnLoad</code> a convenient place to look up and cache class
519object references.</p>
520
521
522<a name="64_bit" id="64_bit"></a>
523<h2>64-bit Considerations</h2>
524
525<p>Android is currently expected to run on 32-bit platforms. In theory it
526could be built for a 64-bit system, but that is not a goal at this time.
527For the most part this isn't something that you will need to worry about
528when interacting with native code,
529but it becomes significant if you plan to store pointers to native
530structures in integer fields in an object. To support architectures
531that use 64-bit pointers, <strong>you need to stash your native pointers in a
532<code>long</code> field rather than an <code>int</code></strong>.
533
534
535<a name="unsupported" id="unsupported"></a>
536<h2>Unsupported Features</h2>
537
538<p>All JNI 1.6 features are supported, with the following exceptions:</p>
539<ul>
540 <li><code>DefineClass</code> is not implemented. Dalvik does not use
541 Java bytecodes or class files, so passing in binary class data
542 doesn't work. Translation facilities may be added in a future
543 version of the VM.</li>
544 <li>"Weak global" references are implemented, but may only be passed
545 to <code>NewLocalRef</code>, <code>NewGlobalRef</code>, and
546 <code>DeleteWeakGlobalRef</code>. (The spec strongly encourages
547 programmers to create hard references to weak globals before doing
548 anything with them, so this should not be at all limiting.)</li>
Elliott Hughesf2433432011-04-13 19:01:11 -0700549 <li><code>GetObjectRefType</code> (new in JNI 1.6) is implemented but not fully
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700550 functional &mdash; it can't always tell the difference between "local" and
551 "global" references.</li>
552</ul>
553
554<p>For backward compatibility, you may need to be aware of:</p>
555<ul>
Elliott Hughesf2433432011-04-13 19:01:11 -0700556 <li>Until Android 2.0 ("Eclair"), the '$' character was not properly
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700557 converted to "_00024" during searches for method names. Working
558 around this requires using explicit registration or moving the
559 native methods out of inner classes.
Elliott Hughesf2433432011-04-13 19:01:11 -0700560 <li>Until Android 2.0 ("Eclair"), it was not possible to use a <code>pthread_key_create</code>
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700561 destructor function to avoid the VM's "thread must be detached before
562 exit" check. (The VM also uses a pthread key destructor function,
563 so it'd be a race to see which gets called first.)
Elliott Hughesf2433432011-04-13 19:01:11 -0700564 <li>"Weak global" references were not implemented until Android 2.2 ("Froyo").
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700565 Older VMs will vigorously reject attempts to use them. You can use
566 the Android platform version constants to test for support.
567</ul>
568
569
570<a name="faq_ULE" id="faq_ULE"></a>
571<h2>FAQ: UnsatisfiedLinkError</h2>
572
573<p>When working on native code it's not uncommon to see a failure like this:</p>
574<pre>java.lang.UnsatisfiedLinkError: Library foo not found</pre>
575
576<p>In some cases it means what it says &mdash; the library wasn't found. In
577other cases the library exists but couldn't be opened by dlopen(), and
578the details of the failure can be found in the exception's detail message.</p>
579
580<p>Common reasons why you might encounter "library not found" exceptions:</p>
581<ul>
582 <li>The library doesn't exist or isn't accessible to the app. Use
583 <code>adb shell ls -l &lt;path&gt;</code> to check its presence
584 and permissions.
585 <li>The library wasn't built with the NDK. This can result in
586 dependencies on functions or libraries that don't exist on the device.
587</ul>
588
589<p>Another class of <code>UnsatisfiedLinkError</code> failures looks like:</p>
590<pre>java.lang.UnsatisfiedLinkError: myfunc
591 at Foo.myfunc(Native Method)
592 at Foo.main(Foo.java:10)</pre>
593
594<p>In logcat, you'll see:</p>
595<pre>W/dalvikvm( 880): No implementation found for native LFoo;.myfunc ()V</pre>
596
597<p>This means that the VM tried to find a matching method but was unsuccessful.
598Some common reasons for this are:</p>
599<ul>
600 <li>The library isn't getting loaded. Check the logcat output for
601 messages about library loading.
602 <li>The method isn't being found due to a name or signature mismatch. This
603 is commonly caused by:
604 <ul>
605 <li>For lazy method lookup, failing to declare C++ functions
606 with <code>extern C</code>. You can use <code>arm-eabi-nm</code>
607 to see the symbols as they appear in the library; if they look
608 mangled (e.g. <code>_Z15Java_Foo_myfuncP7_JNIEnvP7_jclass</code>
609 rather than <code>Java_Foo_myfunc</code>) then you need to
610 adjust the declaration.
611 <li>For explicit registration, minor errors when entering the
612 method signature. Make sure that what you're passing to the
613 registration call matches the signature in the log file.
614 Remember that 'B' is <code>byte</code> and 'Z' is <code>boolean</code>.
615 Class name components in signatures start with 'L', end with ';',
616 use '/' to separate package/class names, and use '$' to separate
617 inner-class names
618 (e.g. <code>Ljava/util/Map$Entry;</code>).
619 </ul>
620</ul>
621
622<p>Using <code>javah</code> to automatically generate JNI headers may help
623avoid some problems.
624
625
626<a name="faq_FindClass" id="faq_FindClass"></a>
627<h2>FAQ: FindClass didn't find my class</h2>
628
629<p>Make sure that the class name string has the correct format. JNI class
630names start with the package name and are separated with slashes,
631e.g. <code>java/lang/String</code>. If you're looking up an array class,
632you need to start with the appropriate number of square brackets and
633must also wrap the class with 'L' and ';', so a one-dimensional array of
634<code>String</code> would be <code>[Ljava/lang/String;</code>.</p>
635
636<p>If the class name looks right, you could be running into a class loader
637issue. <code>FindClass</code> wants to start the class search in the
638class loader associated with your code. It examines the VM call stack,
639which will look something like:
640<pre> Foo.myfunc(Native Method)
641 Foo.main(Foo.java:10)
642 dalvik.system.NativeStart.main(Native Method)</pre>
643
644<p>The topmost method is <code>Foo.myfunc</code>. <code>FindClass</code>
645finds the <code>ClassLoader</code> object associated with the <code>Foo</code>
646class and uses that.</p>
647
648<p>This usually does what you want. You can get into trouble if you
649create a thread outside the VM (perhaps by calling <code>pthread_create</code>
650and then attaching it to the VM with <code>AttachCurrentThread</code>).
651Now the stack trace looks like this:</p>
652<pre> dalvik.system.NativeStart.run(Native Method)</pre>
653
654<p>The topmost method is <code>NativeStart.run</code>, which isn't part of
655your application. If you call <code>FindClass</code> from this thread, the
656VM will start in the "system" class loader instead of the one associated
657with your application, so attempts to find app-specific classes will fail.</p>
658
659<p>There are a few ways to work around this:</p>
660<ul>
661 <li>Do your <code>FindClass</code> lookups once, in
662 <code>JNI_OnLoad</code>, and cache the class references for later
663 use. Any <code>FindClass</code> calls made as part of executing
664 <code>JNI_OnLoad</code> will use the class loader associated with
665 the function that called <code>System.loadLibrary</code> (this is a
666 special rule, provided to make library initialization more convenient).
667 If your app code is loading the library, <code>FindClass</code>
668 will use the correct class loader.
669 <li>Pass an instance of the class into the functions that need
670 it, e.g. declare your native method to take a Class argument and
671 then pass <code>Foo.class</code> in.
672 <li>Cache a reference to the <code>ClassLoader</code> object somewhere
673 handy, and issue <code>loadClass</code> calls directly. This requires
674 some effort.
675</ul>
676
677
678<a name="faq_sharing" id="faq_sharing"></a>
679<h2>FAQ: Sharing raw data with native code</h2>
680
681<p>You may find yourself in a situation where you need to access a large
682buffer of raw data from code written in Java and C/C++. Common examples
683include manipulation of bitmaps or sound samples. There are two
684basic approaches.</p>
685
686<p>You can store the data in a <code>byte[]</code>. This allows very fast
687access from code written in Java. On the native side, however, you're
688not guaranteed to be able to access the data without having to copy it. In
689some implementations, <code>GetByteArrayElements</code> and
690<code>GetPrimitiveArrayCritical</code> will return actual pointers to the
691raw data in the managed heap, but in others it will allocate a buffer
692on the native heap and copy the data over.</p>
693
694<p>The alternative is to store the data in a direct byte buffer. These
695can be created with <code>java.nio.ByteBuffer.allocateDirect</code>, or
696the JNI <code>NewDirectByteBuffer</code> function. Unlike regular
697byte buffers, the storage is not allocated on the managed heap, and can
698always be accessed directly from native code (get the address
699with <code>GetDirectBufferAddress</code>). Depending on how direct
700byte buffer access is implemented in the VM, accessing the data from code
701written in Java can be very slow.</p>
702
703<p>The choice of which to use depends on two factors:</p>
704<ol>
705 <li>Will most of the data accesses happen from code written in Java
706 or in C/C++?
707 <li>If the data is eventually being passed to a system API, what form
708 must it be in? (For example, if the data is eventually passed to a
709 function that takes a byte[], doing processing in a direct
710 <code>ByteBuffer</code> might be unwise.)
711</ol>
712
713<p>If there's no clear winner, use a direct byte buffer. Support for them
714is built directly into JNI, and access to them from code written in
715Java can be made faster with VM improvements.</p>