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