blob: ddfa0e3991f52be25274666fe0dba7e4d0ff42b6 [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>
Elliott Hughes10c7ceb2011-04-13 19:01:11 -07009 <li><a href="#JavaVM_and_JNIEnv">JavaVM and JNIEnv</a></li>
10 <li><a href="#threads">Threads</a></li>
11 <li><a href="#jclass_jmethodID_and_jfieldID">jclass, jmethodID, and jfieldID</a></li>
12 <li><a href="#local_and_global_references">Local and Global References</a></li>
13 <li><a href="#UTF_8_and_UTF_16_strings">UTF-8 and UTF-16 Strings</a></li>
14 <li><a href="#arrays">Primitive Arrays</a></li>
15 <li><a href="#region_calls">Region Calls</a></li>
16 <li><a href="#exceptions">Exceptions</a></li>
17 <li><a href="#extended_checking">Extended Checking</a> </li>
18 <li><a href="#native_libraries">Native Libraries</a></li>
19 <li><a href="#64_bit">64-bit Considerations</a></li>
Elliott Hughes1890b872011-12-16 13:59:54 -080020 <li><a href="#unsupported">Unsupported Features/Backwards Compatibility</a></li>
Elliott Hughes43873352011-07-20 15:02:35 -070021 <li><a href="#faq_ULE">FAQ: Why do I get <code>UnsatisfiedLinkError</code></a></li>
22 <li><a href="#faq_FindClass">FAQ: Why didn't <code>FindClass</code> find my class?</a></li>
23 <li><a href="#faq_sharing">FAQ: How do I share raw data with native code?</a></li>
Elliott Hughes10c7ceb2011-04-13 19:01:11 -070024</ol>
25
26</div>
27</div>
28
Elliott Hughes868d74e2011-09-27 16:27:31 -070029<p>JNI is the Java Native Interface. It defines a way for managed code
30(written in the Java programming language) to interact with native
31code (written in C/C++). It's vendor-neutral, has support for loading code from
Elliott Hughes10c7ceb2011-04-13 19:01:11 -070032dynamic shared libraries, and while cumbersome at times is reasonably efficient.</p>
33
34<p>You really should read through the
Elliott Hughesf2433432011-04-13 19:01:11 -070035<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 -070036to get a sense for how JNI works and what features are available. Some
37aspects of the interface aren't immediately obvious on
38first reading, so you may find the next few sections handy.
Elliott Hughes43873352011-07-20 15:02:35 -070039There's a more detailed <a href="http://java.sun.com/docs/books/jni/html/jniTOC.html">JNI Programmer's Guide and Specification</a>.</p>
Elliott Hughes10c7ceb2011-04-13 19:01:11 -070040
41
42<a name="JavaVM_and_JNIEnv" id="JavaVM_and_JNIEnv"></a>
43<h2>JavaVM and JNIEnv</h2>
44
45<p>JNI defines two key data structures, "JavaVM" and "JNIEnv". Both of these are essentially
Elliott Hughesf2433432011-04-13 19:01:11 -070046pointers to pointers to function tables. (In the C++ version, they're classes with a
47pointer to a function table and a member function for each JNI function that indirects through
48the table.) The JavaVM provides the "invocation interface" functions,
Elliott Hughes868d74e2011-09-27 16:27:31 -070049which allow you to create and destroy a JavaVM. In theory you can have multiple JavaVMs per process,
50but Android only allows one.</p>
Elliott Hughes10c7ceb2011-04-13 19:01:11 -070051
52<p>The JNIEnv provides most of the JNI functions. Your native functions all receive a JNIEnv as
53the first argument.</p>
54
Elliott Hughes868d74e2011-09-27 16:27:31 -070055<p>The JNIEnv is used for thread-local storage. For this reason, <strong>you cannot share a JNIEnv between threads</strong>.
Elliott Hughes10c7ceb2011-04-13 19:01:11 -070056If a piece of code has no other way to get its JNIEnv, you should share
Elliott Hughes43873352011-07-20 15:02:35 -070057the JavaVM, and use <code>GetEnv</code> to discover the thread's JNIEnv. (Assuming it has one; see <code>AttachCurrentThread</code> below.)</p>
Elliott Hughes10c7ceb2011-04-13 19:01:11 -070058
59<p>The C declarations of JNIEnv and JavaVM are different from the C++
Elliott Hughes43873352011-07-20 15:02:35 -070060declarations. The <code>"jni.h"</code> include file provides different typedefs
61depending on whether it's included into C or C++. For this reason it's a bad idea to
Elliott Hughes10c7ceb2011-04-13 19:01:11 -070062include JNIEnv arguments in header files included by both languages. (Put another way: if your
Elliott Hughes43873352011-07-20 15:02:35 -070063header file requires <code>#ifdef __cplusplus</code>, you may have to do some extra work if anything in
Elliott Hughes10c7ceb2011-04-13 19:01:11 -070064that header refers to JNIEnv.)</p>
65
66<a name="threads" id="threads"></a>
67<h2>Threads</h2>
68
Elliott Hughes868d74e2011-09-27 16:27:31 -070069<p>All threads are Linux threads, scheduled by the kernel. They're usually
70started from managed code (using <code>Thread.start</code>),
71but they can also be created elsewhere and then attached to the JavaVM. For
Elliott Hughes10c7ceb2011-04-13 19:01:11 -070072example, a thread started with <code>pthread_create</code> can be attached
73with the JNI <code>AttachCurrentThread</code> or
74<code>AttachCurrentThreadAsDaemon</code> functions. Until a thread is
Elliott Hughes868d74e2011-09-27 16:27:31 -070075attached, it has no JNIEnv, and <strong>cannot make JNI calls</strong>.</p>
Elliott Hughes10c7ceb2011-04-13 19:01:11 -070076
Elliott Hughes868d74e2011-09-27 16:27:31 -070077<p>Attaching a natively-created thread causes a <code>java.lang.Thread</code>
78object to be constructed and added to the "main" <code>ThreadGroup</code>,
79making it visible to the debugger. Calling <code>AttachCurrentThread</code>
80on an already-attached thread is a no-op.</p>
Elliott Hughes10c7ceb2011-04-13 19:01:11 -070081
Elliott Hughes868d74e2011-09-27 16:27:31 -070082<p>Android does not suspend threads executing native code. If
Elliott Hughes10c7ceb2011-04-13 19:01:11 -070083garbage collection is in progress, or the debugger has issued a suspend
Elliott Hughes868d74e2011-09-27 16:27:31 -070084request, Android will pause the thread the next time it makes a JNI call.</p>
Elliott Hughes10c7ceb2011-04-13 19:01:11 -070085
86<p>Threads attached through JNI <strong>must call
87<code>DetachCurrentThread</code> before they exit</strong>.
Elliott Hughes43873352011-07-20 15:02:35 -070088If coding this directly is awkward, in Android 2.0 (Eclair) and higher you
Elliott Hughes10c7ceb2011-04-13 19:01:11 -070089can use <code>pthread_key_create</code> to define a destructor
90function that will be called before the thread exits, and
91call <code>DetachCurrentThread</code> from there. (Use that
92key with <code>pthread_setspecific</code> to store the JNIEnv in
93thread-local-storage; that way it'll be passed into your destructor as
94the argument.)</p>
95
Elliott Hughesf2433432011-04-13 19:01:11 -070096
Elliott Hughes10c7ceb2011-04-13 19:01:11 -070097<a name="jclass_jmethodID_and_jfieldID" id="jclass_jmethodID_and_jfieldID"></a>
98<h2>jclass, jmethodID, and jfieldID</h2>
99
100<p>If you want to access an object's field from native code, you would do the following:</p>
101
102<ul>
103<li> Get the class object reference for the class with <code>FindClass</code></li>
104<li> Get the field ID for the field with <code>GetFieldID</code></li>
Elliott Hughes43873352011-07-20 15:02:35 -0700105<li> Get the contents of the field with something appropriate, such as
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700106<code>GetIntField</code></li>
107</ul>
108
109<p>Similarly, to call a method, you'd first get a class object reference and then a method ID. The IDs are often just
Elliott Hughes868d74e2011-09-27 16:27:31 -0700110pointers to internal runtime data structures. Looking them up may require several string
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700111comparisons, but once you have them the actual call to get the field or invoke the method
112is very quick.</p>
113
114<p>If performance is important, it's useful to look the values up once and cache the results
Elliott Hughes868d74e2011-09-27 16:27:31 -0700115in your native code. Because there is a limit of one JavaVM per process, it's reasonable
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700116to store this data in a static local structure.</p>
117
118<p>The class references, field IDs, and method IDs are guaranteed valid until the class is unloaded. Classes
119are only unloaded if all classes associated with a ClassLoader can be garbage collected,
Elliott Hughes43873352011-07-20 15:02:35 -0700120which is rare but will not be impossible in Android. Note however that
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700121the <code>jclass</code>
122is a class reference and <strong>must be protected</strong> with a call
123to <code>NewGlobalRef</code> (see the next section).</p>
124
125<p>If you would like to cache the IDs when a class is loaded, and automatically re-cache them
126if the class is ever unloaded and reloaded, the correct way to initialize
127the IDs is to add a piece of code that looks like this to the appropriate class:</p>
128
129<pre> /*
130 * We use a class initializer to allow the native code to cache some
Elliott Hughes43873352011-07-20 15:02:35 -0700131 * field offsets. This native function looks up and caches interesting
132 * class/field/method IDs. Throws on failure.
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700133 */
Elliott Hughes43873352011-07-20 15:02:35 -0700134 private static native void nativeInit();
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700135
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700136 static {
Elliott Hughes43873352011-07-20 15:02:35 -0700137 nativeInit();
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700138 }</pre>
Elliott Hughesf2433432011-04-13 19:01:11 -0700139
Elliott Hughes43873352011-07-20 15:02:35 -0700140<p>Create a <code>nativeClassInit</code> method in your C/C++ code that performs the ID lookups. The code
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700141will be executed once, when the class is initialized. If the class is ever unloaded and
Elliott Hughes43873352011-07-20 15:02:35 -0700142then reloaded, it will be executed again.</p>
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700143
144<a name="local_and_global_references" id="local_and_global_references"></a>
145<h2>Local and Global References</h2>
146
Elliott Hughes868d74e2011-09-27 16:27:31 -0700147<p>Every argument passed to a native method, and almost every object returned
148by a JNI function is a "local reference". This means that it's valid for the
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700149duration of the current native method in the current thread.
Elliott Hughes868d74e2011-09-27 16:27:31 -0700150<strong>Even if the object itself continues to live on after the native method
151returns, the reference is not valid.</strong>
152<p>This applies to all sub-classes of <code>jobject</code>, including
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700153<code>jclass</code>, <code>jstring</code>, and <code>jarray</code>.
Elliott Hughes868d74e2011-09-27 16:27:31 -0700154(The runtime will warn you about most reference mis-uses when extended JNI
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700155checks are enabled.)</p>
Elliott Hughes868d74e2011-09-27 16:27:31 -0700156<p>The only way to get non-local references is via the functions
157<code>NewGlobalRef</code> and <code>NewWeakGlobalRef</code>.
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700158
159<p>If you want to hold on to a reference for a longer period, you must use
160a "global" reference. The <code>NewGlobalRef</code> function takes the
161local reference as an argument and returns a global one.
162The global reference is guaranteed to be valid until you call
163<code>DeleteGlobalRef</code>.</p>
164
Elliott Hughes868d74e2011-09-27 16:27:31 -0700165<p>This pattern is commonly used when caching a jclass returned
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700166from <code>FindClass</code>, e.g.:</p>
Elliott Hughes13bac602011-07-19 12:05:04 -0700167<pre>jclass localClass = env-&gt;FindClass("MyClass");
168jclass globalClass = reinterpret_cast&lt;jclass&gt;(env-&gt;NewGlobalRef(localClass));</pre>
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700169
170<p>All JNI methods accept both local and global references as arguments.
Elliott Hughes43873352011-07-20 15:02:35 -0700171It's possible for references to the same object to have different values.
172For example, the return values from consecutive calls to
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700173<code>NewGlobalRef</code> on the same object may be different.
174<strong>To see if two references refer to the same object,
175you must use the <code>IsSameObject</code> function.</strong> Never compare
Elliott Hughes43873352011-07-20 15:02:35 -0700176references with <code>==</code> in native code.</p>
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700177
178<p>One consequence of this is that you
179<strong>must not assume object references are constant or unique</strong>
180in native code. The 32-bit value representing an object may be different
181from one invocation of a method to the next, and it's possible that two
182different objects could have the same 32-bit value on consecutive calls. Do
183not use <code>jobject</code> values as keys.</p>
184
185<p>Programmers are required to "not excessively allocate" local references. In practical terms this means
186that if you're creating large numbers of local references, perhaps while running through an array of
Elliott Hughes868d74e2011-09-27 16:27:31 -0700187objects, you should free them manually with
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700188<code>DeleteLocalRef</code> instead of letting JNI do it for you. The
Elliott Hughes868d74e2011-09-27 16:27:31 -0700189implementation is only required to reserve slots for
Elliott Hughes10c7ceb2011-04-13 19:01:11 -070019016 local references, so if you need more than that you should either delete as you go or use
Elliott Hughes868d74e2011-09-27 16:27:31 -0700191<code>EnsureLocalCapacity</code>/<code>PushLocalFrame</code> to reserve more.</p>
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700192
Elliott Hughes868d74e2011-09-27 16:27:31 -0700193<p>Note that <code>jfieldID</code>s and <code>jmethodID</code>s are opaque
194types, not object references, and should not be passed to
195<code>NewGlobalRef</code>. The raw data
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700196pointers returned by functions like <code>GetStringUTFChars</code>
Elliott Hughes868d74e2011-09-27 16:27:31 -0700197and <code>GetByteArrayElements</code> are also not objects. (They may be passed
198between threads, and are valid until the matching Release call.)</p>
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700199
200<p>One unusual case deserves separate mention. If you attach a native
Elliott Hughes868d74e2011-09-27 16:27:31 -0700201thread with <code>AttachCurrentThread</code>, the code you are running will
202never automatically free local references until the thread detaches. Any local
203references you create will have to be deleted manually. In general, any native
204code that creates local references in a loop probably needs to do some manual
205deletion.</p>
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700206
207<a name="UTF_8_and_UTF_16_strings" id="UTF_8_and_UTF_16_strings"></a>
208<h2>UTF-8 and UTF-16 Strings</h2>
209
Elliott Hughes13bac602011-07-19 12:05:04 -0700210<p>The Java programming language uses UTF-16. For convenience, JNI provides methods that work with <a href="http://en.wikipedia.org/wiki/UTF-8#Modified_UTF-8">Modified UTF-8</a> as well. The
211modified encoding is useful for C code because it encodes \u0000 as 0xc0 0x80 instead of 0x00.
212The nice thing about this is that you can count on having C-style zero-terminated strings,
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700213suitable for use with standard libc string functions. The down side is that you cannot pass
Elliott Hughes868d74e2011-09-27 16:27:31 -0700214arbitrary UTF-8 data to JNI and expect it to work correctly.</p>
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700215
Elliott Hughes868d74e2011-09-27 16:27:31 -0700216<p>If possible, it's usually faster to operate with UTF-16 strings. Android
217currently does not require a copy in <code>GetStringChars</code>, whereas
218<code>GetStringUTFChars</code> requires an allocation and a conversion to
219UTF-8. Note that
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700220<strong>UTF-16 strings are not zero-terminated</strong>, and \u0000 is allowed,
221so you need to hang on to the string length as well as
Elliott Hughes868d74e2011-09-27 16:27:31 -0700222the jchar pointer.</p>
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700223
Elliott Hughes43873352011-07-20 15:02:35 -0700224<p><strong>Don't forget to <code>Release</code> the strings you <code>Get</code></strong>. The
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700225string functions return <code>jchar*</code> or <code>jbyte*</code>, which
226are C-style pointers to primitive data rather than local references. They
Elliott Hughes43873352011-07-20 15:02:35 -0700227are guaranteed valid until <code>Release</code> is called, which means they are not
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700228released when the native method returns.</p>
229
Elliott Hughes13bac602011-07-19 12:05:04 -0700230<p><strong>Data passed to NewStringUTF must be in Modified UTF-8 format</strong>. A
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700231common mistake is reading character data from a file or network stream
232and handing it to <code>NewStringUTF</code> without filtering it.
233Unless you know the data is 7-bit ASCII, you need to strip out high-ASCII
Elliott Hughes13bac602011-07-19 12:05:04 -0700234characters or convert them to proper Modified UTF-8 form. If you don't,
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700235the UTF-16 conversion will likely not be what you expect. The extended
236JNI checks will scan strings and warn you about invalid data, but they
237won't catch everything.</p>
238
239<a name="arrays" id="arrays"></a>
240<h2>Primitive Arrays</h2>
241
242<p>JNI provides functions for accessing the contents of array objects.
243While arrays of objects must be accessed one entry at a time, arrays of
244primitives can be read and written directly as if they were declared in C.</p>
245
246<p>To make the interface as efficient as possible without constraining
Elliott Hughes868d74e2011-09-27 16:27:31 -0700247the VM implementation, the <code>Get&lt;PrimitiveType&gt;ArrayElements</code>
248family of calls allows the runtime to either return a pointer to the actual elements, or
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700249allocate some memory and make a copy. Either way, the raw pointer returned
250is guaranteed to be valid until the corresponding <code>Release</code> call
251is issued (which implies that, if the data wasn't copied, the array object
252will be pinned down and can't be relocated as part of compacting the heap).
Elliott Hughes43873352011-07-20 15:02:35 -0700253<strong>You must <code>Release</code> every array you <code>Get</code>.</strong> Also, if the <code>Get</code>
254call fails, you must ensure that your code doesn't try to <code>Release</code> a NULL
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700255pointer later.</p>
256
257<p>You can determine whether or not the data was copied by passing in a
258non-NULL pointer for the <code>isCopy</code> argument. This is rarely
259useful.</p>
260
261<p>The <code>Release</code> call takes a <code>mode</code> argument that can
Elliott Hughes868d74e2011-09-27 16:27:31 -0700262have one of three values. The actions performed by the runtime depend upon
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700263whether it returned a pointer to the actual data or a copy of it:</p>
264
265<ul>
266 <li><code>0</code>
267 <ul>
268 <li>Actual: the array object is un-pinned.
269 <li>Copy: data is copied back. The buffer with the copy is freed.
270 </ul>
271 <li><code>JNI_COMMIT</code>
272 <ul>
273 <li>Actual: does nothing.
274 <li>Copy: data is copied back. The buffer with the copy
275 <strong>is not freed</strong>.
276 </ul>
277 <li><code>JNI_ABORT</code>
278 <ul>
279 <li>Actual: the array object is un-pinned. Earlier
280 writes are <strong>not</strong> aborted.
281 <li>Copy: the buffer with the copy is freed; any changes to it are lost.
282 </ul>
283</ul>
284
285<p>One reason for checking the <code>isCopy</code> flag is to know if
286you need to call <code>Release</code> with <code>JNI_COMMIT</code>
287after making changes to an array &mdash; if you're alternating between making
288changes and executing code that uses the contents of the array, you may be
289able to
290skip the no-op commit. Another possible reason for checking the flag is for
291efficient handling of <code>JNI_ABORT</code>. For example, you might want
292to get an array, modify it in place, pass pieces to other functions, and
293then discard the changes. If you know that JNI is making a new copy for
294you, there's no need to create another "editable" copy. If JNI is passing
295you the original, then you do need to make your own copy.</p>
296
Elliott Hughes43873352011-07-20 15:02:35 -0700297<p>It is a common mistake (repeated in example code) to assume that you can skip the <code>Release</code> call if
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700298<code>*isCopy</code> is false. This is not the case. If no copy buffer was
299allocated, then the original memory must be pinned down and can't be moved by
300the garbage collector.</p>
301
Elliott Hughes43873352011-07-20 15:02:35 -0700302<p>Also note that the <code>JNI_COMMIT</code> flag does <strong>not</strong> release the array,
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700303and you will need to call <code>Release</code> again with a different flag
304eventually.</p>
305
306
307<a name="region_calls" id="region_calls"></a>
308<h2>Region Calls</h2>
309
310<p>There is an alternative to calls like <code>Get&lt;Type&gt;ArrayElements</code>
311and <code>GetStringChars</code> that may be very helpful when all you want
312to do is copy data in or out. Consider the following:</p>
313
Elliott Hughes43873352011-07-20 15:02:35 -0700314<pre> jbyte* data = env-&gt;GetByteArrayElements(array, NULL);
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700315 if (data != NULL) {
316 memcpy(buffer, data, len);
Elliott Hughes13bac602011-07-19 12:05:04 -0700317 env-&gt;ReleaseByteArrayElements(array, data, JNI_ABORT);
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700318 }</pre>
Elliott Hughesf2433432011-04-13 19:01:11 -0700319
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700320<p>This grabs the array, copies the first <code>len</code> byte
Elliott Hughes868d74e2011-09-27 16:27:31 -0700321elements out of it, and then releases the array. Depending upon the
322implementation, the <code>Get</code> call will either pin or copy the array
323contents.
Elliott Hughes43873352011-07-20 15:02:35 -0700324The code copies the data (for perhaps a second time), then calls <code>Release</code>; in this case
325<code>JNI_ABORT</code> ensures there's no chance of a third copy.</p>
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700326
Elliott Hughes43873352011-07-20 15:02:35 -0700327<p>One can accomplish the same thing more simply:</p>
328<pre> env-&gt;GetByteArrayRegion(array, 0, len, buffer);</pre>
Elliott Hughesf2433432011-04-13 19:01:11 -0700329
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700330<p>This has several advantages:</p>
331<ul>
332 <li>Requires one JNI call instead of 2, reducing overhead.
333 <li>Doesn't require pinning or extra data copies.
334 <li>Reduces the risk of programmer error &mdash; no risk of forgetting
335 to call <code>Release</code> after something fails.
336</ul>
337
338<p>Similarly, you can use the <code>Set&lt;Type&gt;ArrayRegion</code> call
339to copy data into an array, and <code>GetStringRegion</code> or
340<code>GetStringUTFRegion</code> to copy characters out of a
341<code>String</code>.
342
343
344<a name="exceptions" id="exceptions"></a>
Elliott Hughes868d74e2011-09-27 16:27:31 -0700345<h2>Exceptions</h2>
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700346
Elliott Hughes43873352011-07-20 15:02:35 -0700347<p><strong>You must not call most JNI functions while an exception is pending.</strong>
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700348Your code is expected to notice the exception (via the function's return value,
Elliott Hughes43873352011-07-20 15:02:35 -0700349<code>ExceptionCheck</code>, or <code>ExceptionOccurred</code>) and return,
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700350or clear the exception and handle it.</p>
351
352<p>The only JNI functions that you are allowed to call while an exception is
353pending are:</p>
354<ul>
Elliott Hughes43873352011-07-20 15:02:35 -0700355 <li><code>DeleteGlobalRef</code>
356 <li><code>DeleteLocalRef</code>
357 <li><code>DeleteWeakGlobalRef</code>
358 <li><code>ExceptionCheck</code>
359 <li><code>ExceptionClear</code>
360 <li><code>ExceptionDescribe</code>
361 <li><code>ExceptionOccurred</code>
362 <li><code>MonitorExit</code>
363 <li><code>PopLocalFrame</code>
364 <li><code>PushLocalFrame</code>
365 <li><code>Release&lt;PrimitiveType&gt;ArrayElements</code>
366 <li><code>ReleasePrimitiveArrayCritical</code>
367 <li><code>ReleaseStringChars</code>
368 <li><code>ReleaseStringCritical</code>
369 <li><code>ReleaseStringUTFChars</code>
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700370</ul>
371
372<p>Many JNI calls can throw an exception, but often provide a simpler way
373of checking for failure. For example, if <code>NewString</code> returns
374a non-NULL value, you don't need to check for an exception. However, if
375you call a method (using a function like <code>CallObjectMethod</code>),
376you must always check for an exception, because the return value is not
377going to be valid if an exception was thrown.</p>
378
Elliott Hughes868d74e2011-09-27 16:27:31 -0700379<p>Note that exceptions thrown by interpreted code do not unwind native stack
380frames, and Android does not yet support C++ exceptions.
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700381The JNI <code>Throw</code> and <code>ThrowNew</code> instructions just
Elliott Hughes868d74e2011-09-27 16:27:31 -0700382set an exception pointer in the current thread. Upon returning to managed
383from native code, the exception will be noted and handled appropriately.</p>
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700384
385<p>Native code can "catch" an exception by calling <code>ExceptionCheck</code> or
386<code>ExceptionOccurred</code>, and clear it with
387<code>ExceptionClear</code>. As usual,
388discarding exceptions without handling them can lead to problems.</p>
389
Elliott Hughes43873352011-07-20 15:02:35 -0700390<p>There are no built-in functions for manipulating the <code>Throwable</code> object
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700391itself, so if you want to (say) get the exception string you will need to
Elliott Hughes43873352011-07-20 15:02:35 -0700392find the <code>Throwable</code> class, look up the method ID for
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700393<code>getMessage "()Ljava/lang/String;"</code>, invoke it, and if the result
394is non-NULL use <code>GetStringUTFChars</code> to get something you can
Elliott Hughes43873352011-07-20 15:02:35 -0700395hand to <code>printf(3)</code> or equivalent.</p>
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700396
397
398<a name="extended_checking" id="extended_checking"></a>
399<h2>Extended Checking</h2>
400
Elliott Hughes43873352011-07-20 15:02:35 -0700401<p>JNI does very little error checking. Errors usually result in a crash. Android also offers a mode called CheckJNI, where the JavaVM and JNIEnv function table pointers are switched to tables of functions that perform an extended series of checks before calling the standard implementation.</p>
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700402
Elliott Hughes43873352011-07-20 15:02:35 -0700403<p>The additional checks include:</p>
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700404
405<ul>
Elliott Hughes43873352011-07-20 15:02:35 -0700406<li>Arrays: attempting to allocate a negative-sized array.</li>
407<li>Bad pointers: passing a bad jarray/jclass/jobject/jstring to a JNI call, or passing a NULL pointer to a JNI call with a non-nullable argument.</li>
408<li>Class names: passing anything but the “java/lang/String” style of class name to a JNI call.</li>
409<li>Critical calls: making a JNI call between a “critical” get and its corresponding release.</li>
410<li>Direct ByteBuffers: passing bad arguments to <code>NewDirectByteBuffer</code>.</li>
411<li>Exceptions: making a JNI call while there’s an exception pending.</li>
412<li>JNIEnv*s: using a JNIEnv* from the wrong thread.</li>
413<li>jfieldIDs: using a NULL jfieldID, or using a jfieldID to set a field to a value of the wrong type (trying to assign a StringBuilder to a String field, say), or using a jfieldID for a static field to set an instance field or vice versa, or using a jfieldID from one class with instances of another class.</li>
414<li>jmethodIDs: using the wrong kind of jmethodID when making a <code>Call*Method</code> JNI call: incorrect return type, static/non-static mismatch, wrong type for ‘this’ (for non-static calls) or wrong class (for static calls).</li>
415<li>References: using <code>DeleteGlobalRef</code>/<code>DeleteLocalRef</code> on the wrong kind of reference.</li>
416<li>Release modes: passing a bad release mode to a release call (something other than <code>0</code>, <code>JNI_ABORT</code>, or <code>JNI_COMMIT</code>).</li>
417<li>Type safety: returning an incompatible type from your native method (returning a StringBuilder from a method declared to return a String, say).</li>
418<li>UTF-8: passing an invalid <a href="http://en.wikipedia.org/wiki/UTF-8#Modified_UTF-8">Modified UTF-8</a> byte sequence to a JNI call.</li>
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700419</ul>
420
Elliott Hughes43873352011-07-20 15:02:35 -0700421<p>(Accessibility of methods and fields is still not checked: access restrictions don't apply to native code.)</p>
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700422
Elliott Hughes43873352011-07-20 15:02:35 -0700423<p>There are several ways to enable CheckJNI.</p>
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700424
Elliott Hughes43873352011-07-20 15:02:35 -0700425<p>If you’re using the emulator, CheckJNI is on by default.</p>
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700426
Elliott Hughes43873352011-07-20 15:02:35 -0700427<p>If you have a rooted device, you can use the following sequence of commands to restart the runtime with CheckJNI enabled:</p>
428
429<pre>adb shell stop
430adb shell setprop dalvik.vm.checkjni true
431adb shell start</pre>
432
433<p>In either of these cases, you’ll see something like this in your logcat output when the runtime starts:</p>
434
435<pre>D AndroidRuntime: CheckJNI is ON</pre>
436
437<p>If you have a regular device, you can use the following command:</p>
438
439<pre>adb shell setprop debug.checkjni 1</pre>
440
441<p>This won’t affect already-running apps, but any app launched from that point on will have CheckJNI enabled. (Change the property to any other value or simply rebooting will disable CheckJNI again.) In this case, you’ll see something like this in your logcat output the next time an app starts:</p>
442
443<pre>D Late-enabling CheckJNI</pre>
444
445
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700446
447
448<a name="native_libraries" id="native_libraries"></a>
449<h2>Native Libraries</h2>
450
451<p>You can load native code from shared libraries with the standard
Elliott Hughes43873352011-07-20 15:02:35 -0700452<code>System.loadLibrary</code> call. The
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700453preferred way to get at your native code is:</p>
454
455<ul>
Elliott Hughes43873352011-07-20 15:02:35 -0700456<li> Call <code>System.loadLibrary</code> from a static class
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700457initializer. (See the earlier example, where one is used to call
Elliott Hughes43873352011-07-20 15:02:35 -0700458<code>nativeClassInit</code>.) The argument is the "undecorated"
459library name, so to load "libfubar.so" you would pass in "fubar".</li>
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700460<li> Provide a native function: <code><strong>jint JNI_OnLoad(JavaVM* vm, void* reserved)</strong></code></li>
461<li>In <code>JNI_OnLoad</code>, register all of your native methods. You
462should declare
Elliott Hughes43873352011-07-20 15:02:35 -0700463the methods "static" so the names don't take up space in the symbol table
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700464on the device.</li>
465</ul>
466
467<p>The <code>JNI_OnLoad</code> function should look something like this if
Elliott Hughes13bac602011-07-19 12:05:04 -0700468written in C++:</p>
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700469<pre>jint JNI_OnLoad(JavaVM* vm, void* reserved)
470{
471 JNIEnv* env;
Elliott Hughes13bac602011-07-19 12:05:04 -0700472 if (vm-&gt;GetEnv(reinterpret_cast&lt;void**&gt;(&env), JNI_VERSION_1_6) != JNI_OK) {
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700473 return -1;
Elliott Hughes13bac602011-07-19 12:05:04 -0700474 }
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700475
Elliott Hughes13bac602011-07-19 12:05:04 -0700476 // Get jclass with env-&gt;FindClass.
477 // Register methods with env-&gt;RegisterNatives.
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700478
479 return JNI_VERSION_1_6;
480}</pre>
481
Elliott Hughes43873352011-07-20 15:02:35 -0700482<p>You can also call <code>System.load</code> with the full path name of the
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700483shared library. For Android apps, you may find it useful to get the full
484path to the application's private data storage area from the context object.</p>
485
Elliott Hughes868d74e2011-09-27 16:27:31 -0700486<p>This is the recommended approach, but not the only approach. Explicit
487registration is not required, nor is it necessary that you provide a
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700488<code>JNI_OnLoad</code> function.
489You can instead use "discovery" of native methods that are named in a
Elliott Hughes868d74e2011-09-27 16:27:31 -0700490specific way (see <a href="http://java.sun.com/javase/6/docs/technotes/guides/jni/spec/design.html#wp615">the JNI spec</a> for details), though this is less desirable because if a method signature is wrong you won't know
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700491about it until the first time the method is actually used.</p>
492
493<p>One other note about <code>JNI_OnLoad</code>: any <code>FindClass</code>
494calls you make from there will happen in the context of the class loader
495that was used to load the shared library. Normally <code>FindClass</code>
496uses the loader associated with the method at the top of the interpreted
Elliott Hughes868d74e2011-09-27 16:27:31 -0700497stack, or if there isn't one (because the thread was just attached) it uses
498the "system" class loader. This makes
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700499<code>JNI_OnLoad</code> a convenient place to look up and cache class
500object references.</p>
501
502
503<a name="64_bit" id="64_bit"></a>
504<h2>64-bit Considerations</h2>
505
506<p>Android is currently expected to run on 32-bit platforms. In theory it
507could be built for a 64-bit system, but that is not a goal at this time.
508For the most part this isn't something that you will need to worry about
509when interacting with native code,
510but it becomes significant if you plan to store pointers to native
511structures in integer fields in an object. To support architectures
512that use 64-bit pointers, <strong>you need to stash your native pointers in a
513<code>long</code> field rather than an <code>int</code></strong>.
514
515
516<a name="unsupported" id="unsupported"></a>
Elliott Hughes1890b872011-12-16 13:59:54 -0800517<h2>Unsupported Features/Backwards Compatibility</h2>
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700518
Elliott Hughes1890b872011-12-16 13:59:54 -0800519<p>All JNI 1.6 features are supported, with the following exception:</p>
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700520<ul>
Elliott Hughes868d74e2011-09-27 16:27:31 -0700521 <li><code>DefineClass</code> is not implemented. Android does not use
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700522 Java bytecodes or class files, so passing in binary class data
Elliott Hughes868d74e2011-09-27 16:27:31 -0700523 doesn't work.</li>
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700524</ul>
525
Elliott Hughes1890b872011-12-16 13:59:54 -0800526<p>For backward compatibility with older Android releases, you may need to
527be aware of:</p>
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700528<ul>
Elliott Hughes1890b872011-12-16 13:59:54 -0800529 <li><b>Dynamic lookup of native functions</b>
530 <p>Until Android 2.0 (Eclair), the '$' character was not properly
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700531 converted to "_00024" during searches for method names. Working
532 around this requires using explicit registration or moving the
533 native methods out of inner classes.
Elliott Hughes1890b872011-12-16 13:59:54 -0800534 <li><b>Detaching threads</b>
535 <p>Until Android 2.0 (Eclair), it was not possible to use a <code>pthread_key_create</code>
Elliott Hughes868d74e2011-09-27 16:27:31 -0700536 destructor function to avoid the "thread must be detached before
537 exit" check. (The runtime also uses a pthread key destructor function,
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700538 so it'd be a race to see which gets called first.)
Elliott Hughes1890b872011-12-16 13:59:54 -0800539 <li><b>Weak global references</b>
540 <p>Until Android 2.2 (Froyo), weak global references were not implemented.
Elliott Hughes868d74e2011-09-27 16:27:31 -0700541 Older versions will vigorously reject attempts to use them. You can use
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700542 the Android platform version constants to test for support.
Elliott Hughes1890b872011-12-16 13:59:54 -0800543 <p>Until Android 4.0 (Ice Cream Sandwich), weak global references could only
544 be passed to <code>NewLocalRef</code>, <code>NewGlobalRef</code>, and
545 <code>DeleteWeakGlobalRef</code>. (The spec strongly encourages
546 programmers to create hard references to weak globals before doing
547 anything with them, so this should not be at all limiting.)
548 <p>From Android 4.0 (Ice Cream Sandwich) on, weak global references can be
549 used like any other JNI references.</li>
550 <li><b>Local references</b>
551 <p>Until Android 4.0 (Ice Cream Sandwich), local references were
Elliott Hughes868d74e2011-09-27 16:27:31 -0700552 actually direct pointers. Ice Cream Sandwich added the indirection
553 necessary to support better garbage collectors, but this means that lots
Elliott Hughes1890b872011-12-16 13:59:54 -0800554 of JNI bugs are undetectable on older releases. See
555 <a href="http://android-developers.blogspot.com/2011/11/jni-local-reference-changes-in-ics.html">JNI Local Reference Changes in ICS</a> for more details.
556 <li><b>Determining reference type with <code>GetObjectRefType</code></b>
557 <p>Until Android 4.0 (Ice Cream Sandwich), as a consequence of the use of
558 direct pointers (see above), it was impossible to implement
559 <code>GetObjectRefType</code> correctly. Instead we used a heuristic
560 that looked through the weak globals table, the arguments, the locals
561 table, and the globals table in that order. The first time it found your
562 direct pointer, it would report that your reference was of the type it
563 happened to be examining. This meant, for example, that if
564 you called <code>GetObjectRefType</code> on a global jclass that happened
565 to be the same as the jclass passed as an implicit argument to your static
566 native method, you'd get <code>JNILocalRefType</code> rather than
567 <code>JNIGlobalRefType</code>.
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700568</ul>
569
570
571<a name="faq_ULE" id="faq_ULE"></a>
Elliott Hughes43873352011-07-20 15:02:35 -0700572<h2>FAQ: Why do I get <code>UnsatisfiedLinkError</code>?</h2>
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700573
574<p>When working on native code it's not uncommon to see a failure like this:</p>
575<pre>java.lang.UnsatisfiedLinkError: Library foo not found</pre>
576
577<p>In some cases it means what it says &mdash; the library wasn't found. In
Elliott Hughes43873352011-07-20 15:02:35 -0700578other cases the library exists but couldn't be opened by <code>dlopen(3)</code>, and
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700579the details of the failure can be found in the exception's detail message.</p>
580
581<p>Common reasons why you might encounter "library not found" exceptions:</p>
582<ul>
583 <li>The library doesn't exist or isn't accessible to the app. Use
584 <code>adb shell ls -l &lt;path&gt;</code> to check its presence
585 and permissions.
586 <li>The library wasn't built with the NDK. This can result in
587 dependencies on functions or libraries that don't exist on the device.
588</ul>
589
590<p>Another class of <code>UnsatisfiedLinkError</code> failures looks like:</p>
591<pre>java.lang.UnsatisfiedLinkError: myfunc
592 at Foo.myfunc(Native Method)
593 at Foo.main(Foo.java:10)</pre>
594
595<p>In logcat, you'll see:</p>
596<pre>W/dalvikvm( 880): No implementation found for native LFoo;.myfunc ()V</pre>
597
Elliott Hughes868d74e2011-09-27 16:27:31 -0700598<p>This means that the runtime tried to find a matching method but was
599unsuccessful. Some common reasons for this are:</p>
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700600<ul>
601 <li>The library isn't getting loaded. Check the logcat output for
602 messages about library loading.
603 <li>The method isn't being found due to a name or signature mismatch. This
604 is commonly caused by:
605 <ul>
606 <li>For lazy method lookup, failing to declare C++ functions
Elliott Hughes868d74e2011-09-27 16:27:31 -0700607 with <code>extern "C"</code> and appropriate
608 visibility (<code>JNIEXPORT</code>). Note that prior to Ice Cream
609 Sandwich, the JNIEXPORT macro was incorrect, so using a new GCC with
610 an old <code>jni.h</code> won't work.
611 You can use <code>arm-eabi-nm</code>
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700612 to see the symbols as they appear in the library; if they look
Elliott Hughes43873352011-07-20 15:02:35 -0700613 mangled (something like <code>_Z15Java_Foo_myfuncP7_JNIEnvP7_jclass</code>
Elliott Hughes868d74e2011-09-27 16:27:31 -0700614 rather than <code>Java_Foo_myfunc</code>), or if the symbol type is
615 a lowercase 't' rather than an uppercase 'T', then you need to
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700616 adjust the declaration.
617 <li>For explicit registration, minor errors when entering the
618 method signature. Make sure that what you're passing to the
619 registration call matches the signature in the log file.
620 Remember that 'B' is <code>byte</code> and 'Z' is <code>boolean</code>.
621 Class name components in signatures start with 'L', end with ';',
622 use '/' to separate package/class names, and use '$' to separate
Elliott Hughes43873352011-07-20 15:02:35 -0700623 inner-class names (<code>Ljava/util/Map$Entry;</code>, say).
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700624 </ul>
625</ul>
626
627<p>Using <code>javah</code> to automatically generate JNI headers may help
628avoid some problems.
629
630
631<a name="faq_FindClass" id="faq_FindClass"></a>
Elliott Hughes43873352011-07-20 15:02:35 -0700632<h2>FAQ: Why didn't <code>FindClass</code> find my class?</h2>
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700633
634<p>Make sure that the class name string has the correct format. JNI class
635names start with the package name and are separated with slashes,
Elliott Hughes43873352011-07-20 15:02:35 -0700636such as <code>java/lang/String</code>. If you're looking up an array class,
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700637you need to start with the appropriate number of square brackets and
638must also wrap the class with 'L' and ';', so a one-dimensional array of
639<code>String</code> would be <code>[Ljava/lang/String;</code>.</p>
640
641<p>If the class name looks right, you could be running into a class loader
642issue. <code>FindClass</code> wants to start the class search in the
Elliott Hughes868d74e2011-09-27 16:27:31 -0700643class loader associated with your code. It examines the call stack,
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700644which will look something like:
645<pre> Foo.myfunc(Native Method)
646 Foo.main(Foo.java:10)
647 dalvik.system.NativeStart.main(Native Method)</pre>
648
649<p>The topmost method is <code>Foo.myfunc</code>. <code>FindClass</code>
650finds the <code>ClassLoader</code> object associated with the <code>Foo</code>
651class and uses that.</p>
652
653<p>This usually does what you want. You can get into trouble if you
Elliott Hughes868d74e2011-09-27 16:27:31 -0700654create a thread yourself (perhaps by calling <code>pthread_create</code>
655and then attaching it with <code>AttachCurrentThread</code>).
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700656Now the stack trace looks like this:</p>
657<pre> dalvik.system.NativeStart.run(Native Method)</pre>
658
659<p>The topmost method is <code>NativeStart.run</code>, which isn't part of
660your application. If you call <code>FindClass</code> from this thread, the
Elliott Hughes868d74e2011-09-27 16:27:31 -0700661JavaVM will start in the "system" class loader instead of the one associated
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700662with your application, so attempts to find app-specific classes will fail.</p>
663
664<p>There are a few ways to work around this:</p>
665<ul>
666 <li>Do your <code>FindClass</code> lookups once, in
667 <code>JNI_OnLoad</code>, and cache the class references for later
668 use. Any <code>FindClass</code> calls made as part of executing
669 <code>JNI_OnLoad</code> will use the class loader associated with
670 the function that called <code>System.loadLibrary</code> (this is a
671 special rule, provided to make library initialization more convenient).
672 If your app code is loading the library, <code>FindClass</code>
673 will use the correct class loader.
674 <li>Pass an instance of the class into the functions that need
Elliott Hughes43873352011-07-20 15:02:35 -0700675 it, by declaring your native method to take a Class argument and
676 then passing <code>Foo.class</code> in.
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700677 <li>Cache a reference to the <code>ClassLoader</code> object somewhere
678 handy, and issue <code>loadClass</code> calls directly. This requires
679 some effort.
680</ul>
681
682
683<a name="faq_sharing" id="faq_sharing"></a>
Elliott Hughes43873352011-07-20 15:02:35 -0700684<h2>FAQ: How do I share raw data with native code?</h2>
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700685
686<p>You may find yourself in a situation where you need to access a large
Elliott Hughes868d74e2011-09-27 16:27:31 -0700687buffer of raw data from both managed and native code. Common examples
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700688include manipulation of bitmaps or sound samples. There are two
689basic approaches.</p>
690
691<p>You can store the data in a <code>byte[]</code>. This allows very fast
Elliott Hughes868d74e2011-09-27 16:27:31 -0700692access from managed code. On the native side, however, you're
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700693not guaranteed to be able to access the data without having to copy it. In
694some implementations, <code>GetByteArrayElements</code> and
695<code>GetPrimitiveArrayCritical</code> will return actual pointers to the
696raw data in the managed heap, but in others it will allocate a buffer
697on the native heap and copy the data over.</p>
698
699<p>The alternative is to store the data in a direct byte buffer. These
700can be created with <code>java.nio.ByteBuffer.allocateDirect</code>, or
701the JNI <code>NewDirectByteBuffer</code> function. Unlike regular
702byte buffers, the storage is not allocated on the managed heap, and can
703always be accessed directly from native code (get the address
704with <code>GetDirectBufferAddress</code>). Depending on how direct
Elliott Hughes868d74e2011-09-27 16:27:31 -0700705byte buffer access is implemented, accessing the data from managed code
706can be very slow.</p>
Elliott Hughes10c7ceb2011-04-13 19:01:11 -0700707
708<p>The choice of which to use depends on two factors:</p>
709<ol>
710 <li>Will most of the data accesses happen from code written in Java
711 or in C/C++?
712 <li>If the data is eventually being passed to a system API, what form
713 must it be in? (For example, if the data is eventually passed to a
714 function that takes a byte[], doing processing in a direct
715 <code>ByteBuffer</code> might be unwise.)
716</ol>
717
718<p>If there's no clear winner, use a direct byte buffer. Support for them
Elliott Hughes868d74e2011-09-27 16:27:31 -0700719is built directly into JNI, and performance should improve in future releases.</p>