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