OSDN Git Service

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