JNI—java native interface
官方文档
JNI is the Java Native Interface. It defines a way for managed code (written in the Java programming language) to interact with native code (written in C/C++). It's vendor-neutral, has support for loading code from dynamic shared libraries, and while cumbersome at times is reasonably efficient.
JNI 即java 本地接口,它定义了一种方法(用java语言写)管理代码和本地代码(用C语言或者C++语言)交互。它是中立,它支持动态地从分享库中加载代码,虽然操作会麻烦些,但有时候它是必须的,有效的。
If you're not already familiar with it, read through the Java Native Interface Specification to get a sense for how JNI works and what features are available. Some aspects of the interface aren't immediately obvious on first reading, so you may find the next few sections handy.
如果你之前并不熟悉它,通过阅读这java 本地接口规范去了解JNI是如何工作的和一些有用的功能特性。第一次阅读接口的某些方面不能立刻明白,然而你会在后面几个部分中发现它。
JNI defines two key data structures, "JavaVM" and "JNIEnv". Both of these are essentially pointers to pointers to function tables. (In the C++ version, they're classes with a pointer to a function table and a member function for each JNI function that indirects through the table.) The JavaVM provides the "invocation interface" functions, which allow you to create and destroy a JavaVM. In theory you can have multiple JavaVMs per process, but Android only allows one.
JNI定义了两个重要的数据结构,javavm和JNIEnv。这两者本质上就是指向函数的指针构成的表。(在C++版本,该段实在翻译不出来),javaVM(java虚拟机) 提供了调用接口的功能函数。这些接口功能函数允许你去创建和销毁一个java虚拟机,理论上每个进程你可以有多个虚拟机,但是android只允许你有一个。
The JNIEnv provides most of the JNI functions. Your native functions all receive a JNIEnv as the first argument.
JNI(JNINativeInterface)
提供了很多java 本地接口函数,你的所有的本地方法都接收一个JNIEnv作为第一个参数
The JNIEnv is used for thread-local storage. For this reason, you cannot share a JNIEnv between threads. If a piece of code has no other way to get its JNIEnv, you should share the JavaVM, and use GetEnv
to discover the thread's JNIEnv. (Assuming it has one; see AttachCurrentThread
below.)
JNIEnv是使用本地线程存储的,出于这个原因,你不能在线程间共享JNIEnv。如果一段代码没有其他的方法去得到JNIEnv,你应该共享java虚拟机然后使用GetEnv查找这线程中的JNIEnv
The C declarations of JNIEnv and JavaVM are different from the C++ declarations. The "jni.h"
include file provides different typedefs depending on whether it's included into C or C++. For this reason it's a bad idea to include JNIEnv arguments in header files included by both languages. (Put another way: if your header file requires #ifdef __cplusplus
, you may have to do some extra work if anything in that header refers to JNIEnv.)
JNIEnv 和JAVA虚拟机在C中的声明与在C++中声明是不同的。这个jni.h所包含的文件提供了不同的类型取决于是否包含C或者C++。出于这个原因,在两种语言的头文件中包含JNIEnv参数是非常不可取的。(换句话说:如果你的具有JNIEnv的头文件引用需要#ifdef __cplusplus标签,你可能不得不多做一些 额外的工作
All threads are Linux threads, scheduled by the kernel. They're usually started from managed code (usingThread.start
), but they can also be created elsewhere and then attached to the JavaVM. For example, a thread started with pthread_create
can be attached with the JNI AttachCurrentThread
orAttachCurrentThreadAsDaemon
functions. Until a thread is attached, it has no JNIEnv, and cannot make JNI calls.
所有的线程都是linux线程,这些线程被kernet(内核)调度。线程通常从托管代码开启(使用 thread.start),但是他们也可以在其他地方被创建然后与java虚拟机相连接。例如,一个从pthread_create开始的线程可以和JNI函数连接在一起(通过AttachCurrentThread
orAttachCurrentThreadAsDaemon
)。直到一个可连接的线程因为没有JNIEnv不能被JNI调用。
Attaching a natively-created thread causes a java.lang.Thread
object to be constructed and added to the "main" ThreadGroup
, making it visible to the debugger. Calling AttachCurrentThread
on an already-attached thread is a no-op.
一个了连接的本地线程被创建引起一个java.lang.Thread
对象呗构造出阿里并增加到主线程组中,打开可视化的调试,在一个早已连接的线程中调用AttachCurrentThread会等待。
Android does not suspend threads executing native code. If garbage collection is in progress, or the debugger has issued a suspend request, Android will pause the thread the next time it makes a JNI call.
Android 不支持线程执行不低代码,如果垃圾回收器正在处理垃圾,或者调试已经发出了一个调试请求,Android将会暂停下次调用JNI的线程
Threads attached through JNI must call DetachCurrentThread
before they exit. If coding this directly is awkward, in Android 2.0 (Eclair) and higher you can use pthread_key_create
to define a destructor function that will be called before the thread exits, and call DetachCurrentThread
from there. (Use that key withpthread_setspecific
to store the JNIEnv in thread-local-storage; that way it'll be passed into your destructor as the argument.)
通过JNI连接的线程在他们退出之前必须滴啊用DetachCurrentThread方法。如果直接编译困在,再ANdroid2.0或者更高版本的系统上你可以使用pthread_key_create
去定义一个在线程退出时被调用的析构函数。使用用pthread_setspecific键
在本地线程中去保存JNIEnv;它将能被你的析构函数作为参数调用
If you want to access an object's field from native code, you would do the following:
如果你想从本地代码中去接受一个对象字段。需要做如下操作
FindClass
使用findClass得到类对象的引用
GetFieldID
GetIntField
GetIntField
得到字段中某些内容信息Similarly, to call a method, you'd first get a class object reference and then a method ID. The IDs are often just pointers to internal runtime data structures. Looking them up may require several string comparisons, but once you have them the actual call to get the field or invoke the method is very quick.
类似的,你要去调用一个方法,首先要获得一个类的对象的引用和这个方法的ID。ID常常只是内部运行的结构体的指针。查看他们可能需要比较几个字符串。但是一旦你得到了他们本身再去得到字段或者调用方法是非常容易的。
If performance is important, it's useful to look the values up once and cache the results in your native code. Because there is a limit of one JavaVM per process, it's reasonable to store this data in a static local structure.
如果要求高性能,在你的本地代码中常常查看一次这个值并缓存起来。因为这是java虚拟机的一个限制,将这些数据用静态局部结构体存储起来是很有用的。
The class references, field IDs, and method IDs are guaranteed valid until the class is unloaded. Classes are only unloaded if all classes associated with a ClassLoader can be garbage collected, which is rare but will not be impossible in Android. Note however that the jclass
is a class reference and must be protected with a call toNewGlobalRef
(see the next section).
知道类被卸载之前,这个类的引用,字段的ID,方法的ID都是被保证有效的。发生与类加载器所加载的类中只有被卸载的类才能被垃圾回收器回收的概率,这在android中是不可能的。注意不管这么样这jclass作为一个类的引用且必须调用NewGlobalRef去保护它。
If you would like to cache the IDs when a class is loaded, and automatically re-cache them if the class is ever unloaded and reloaded, the correct way to initialize the IDs is to add a piece of code that looks like this to the appropriate class:
如果你想在一个类被加载的时候缓存它的ID并且在类被卸载后再次加载时自动缓存他们的ID,正确初始化ID的方法是去增加一段代码到合适的类中
/*
* We use a class initializer to allow the native code to cache some
* field offsets. This native function looks up and caches interesting
* class/field/method IDs. Throws on failure.
*/
private static native void nativeInit();
static {
nativeInit();
}
Create a nativeClassInit
method in your C/C++ code that performs the ID lookups. The code will be executed once, when the class is initialized. If the class is ever unloaded and then reloaded, it will be executed again.
在你的C或者C++代码中创建一个ntiveClassInit方法
去执行ID的查找工作,在类初始化的时候,这方法将被执行一次。如果这类
曾经被卸载然后重新加载,这个方法将再次被执行。
局部和全局引用
Every argument passed to a native method, and almost every object returned by a JNI function is a "local reference". This means that it's valid for the duration of the current native method in the current thread. Even if the object itself continues to live on after the native method returns, the reference is not valid.
几乎将每一个参数传递给本地方法然后都通过一个局部引用的JNI函数返回给对象。这意味着在当前线程中的当前的本地方法在这段期间是有效的。过了这段时间,即使这个对象本身在本地方法返回后仍然活着,它也是无效的。
This applies to all sub-classes of jobject
, including jclass
, jstring
, and jarray
. (The runtime will warn you about most reference mis-uses when extended JNI checks are enabled.)
这适用于所有的jobject的子类包括jclass
, jstring
, 和 jarray
. (当启用扩展的JNI检测时,在运行时将给出你过多的引用被滥用的警告)
The only way to get non-local references is via the functions NewGlobalRef
and NewWeakGlobalRef
.
这得到非局部引用的唯一的方法是通过NewGlobalRef
和NewWeakGlobalRef功能函数,
If you want to hold on to a reference for a longer period, you must use a "global" reference. The NewGlobalRef
function takes the local reference as an argument and returns a global one. The global reference is guaranteed to be valid until you call DeleteGlobalRef
.
如果你想在很长一段时间内持有一个引用,你必须适用global应用。NewGlobalRef函数适用一个局部引用作为参数返回一个全局引用,这全局在你调用
DeleteGlobalRef方法前都被保证是有效的
This pattern is commonly used when caching a jclass returned from FindClass
, e.g.:
在缓存一个来自FindClass方法返回的jclass对象时,这种模式通常是有用的。
jclass localClass = env->FindClass("MyClass");
jclass globalClass = reinterpret_cast<jclass>(env->NewGlobalRef(localClass));
All JNI methods accept both local and global references as arguments. It's possible for references to the same object to have different values. For example, the return values from consecutive calls to NewGlobalRef
on the same object may be different. To see if two references refer to the same object, you must use theIsSameObject
function. Never compare references with ==
in native code.
所有的JNI方法都接收两个局部和者全局引用作为参数。通过一样的对象去得到不同的值这是合适的。例如,用一样的对象连续的去调用NewGlobalRef
方法返回的值可能是不同的。要看是否两个引用引用一样的对象,你必须适用theIsSameObject
方法去判断。在本地代码中绝对不要适用==去比较。
One consequence of this is that you must not assume object references are constant or unique in native code. The 32-bit value representing an object may be different from one invocation of a method to the next, and it's possible that two different objects could have the same 32-bit value on consecutive calls. Do not use jobject
values as keys.
作为结论在本地代码中你不能假设对象的引用是一个常数或者唯一的。一个用32位表示的对象从一个方法调用下一个方法可能是不同的,它可能是两个不同的32位对象在连续的调用。不要适用jobject值作为键
Programmers are required to "not excessively allocate" local references. In practical terms this means that if you're creating large numbers of local references, perhaps while running through an array of objects, you should free them manually with DeleteLocalRef
instead of letting JNI do it for you. The implementation is only required to reserve slots for 16 local references, so if you need more than that you should either delete as you go or use EnsureLocalCapacity
/PushLocalFrame
to reserve more.
程序员需要适当的分配本地引用。在实践中这表示是否你创建了大量的局部引用,或者当通过一个数组对象运行时,你应该手动的用DeleteLocalRef
释放他们而不是让JNI去做这些事。实现只需要你去保存16个局部引用,所以你需要更多的区删除或者使用EnsureLocalCapacity
/PushLocalFrame
去储备更多。
Note that jfieldID
s and jmethodID
s are opaque types, not object references, and should not be passed toNewGlobalRef
. The raw data pointers returned by functions like GetStringUTFChars
andGetByteArrayElements
are also not objects. (They may be passed between threads, and are valid until the matching Release call.)
注意jfieldIDs 和jmethodIDs是空类型,不是对象引用,不应该传递给NewGlobalRef方法。通过像
GetStringUTFChars
和andGetByteArrayElements
返回的原始数据也不是对象(在被析构之前他们通过在两个线程间传递是有效的。)
One unusual case deserves separate mention. If you attach a native thread with AttachCurrentThread
, the code you are running will never automatically free local references until the thread detaches. Any local references you create will have to be deleted manually. In general, any native code that creates local references in a loop probably needs to do some manual deletion.
一个特别的案例值得单独说:如果你用AttachCurrentThread附加一个本地线程,你运行的代码将不会自动的清除局部引用,直到线程死去。你创建的任何局部引用必须手动的删除。一般来说,在循环中任何本地菜吗创建的局部引用可能需做一些手动删除
,(持续更新中)
The Java programming language uses UTF-16. For convenience, JNI provides methods that work with Modified UTF-8 as well. The modified encoding is useful for C code because it encodes \u0000 as 0xc0 0x80 instead of 0x00. The nice thing about this is that you can count on having C-style zero-terminated strings, suitable for use with standard libc string functions. The down side is that you cannot pass arbitrary UTF-8 data to JNI and expect it to work correctly.
If possible, it's usually faster to operate with UTF-16 strings. Android currently does not require a copy inGetStringChars
, whereas GetStringUTFChars
requires an allocation and a conversion to UTF-8. Note thatUTF-16 strings are not zero-terminated, and \u0000 is allowed, so you need to hang on to the string length as well as the jchar pointer.
Don't forget to Release
the strings you Get
. The string functions return jchar*
or jbyte*
, which are C-style pointers to primitive data rather than local references. They are guaranteed valid until Release
is called, which means they are not released when the native method returns.
Data passed to NewStringUTF must be in Modified UTF-8 format. A common mistake is reading character data from a file or network stream and handing it to NewStringUTF
without filtering it. Unless you know the data is 7-bit ASCII, you need to strip out high-ASCII characters or convert them to proper Modified UTF-8 form. If you don't, the UTF-16 conversion will likely not be what you expect. The extended JNI checks will scan strings and warn you about invalid data, but they won't catch everything.
JNI provides functions for accessing the contents of array objects. While arrays of objects must be accessed one entry at a time, arrays of primitives can be read and written directly as if they were declared in C.
To make the interface as efficient as possible without constraining the VM implementation, theGet<PrimitiveType>ArrayElements
family of calls allows the runtime to either return a pointer to the actual elements, or allocate some memory and make a copy. Either way, the raw pointer returned is guaranteed to be valid until the corresponding Release
call is issued (which implies that, if the data wasn't copied, the array object will be pinned down and can't be relocated as part of compacting the heap). You must Release
every array you Get
. Also, if the Get
call fails, you must ensure that your code doesn't try to Release
a NULL pointer later.
You can determine whether or not the data was copied by passing in a non-NULL pointer for the isCopy
argument. This is rarely useful.
The Release
call takes a mode
argument that can have one of three values. The actions performed by the runtime depend upon whether it returned a pointer to the actual data or a copy of it:
0
JNI_COMMIT
JNI_ABORT
One reason for checking the isCopy
flag is to know if you need to call Release
with JNI_COMMIT
after making changes to an array — if you're alternating between making changes and executing code that uses the contents of the array, you may be able to skip the no-op commit. Another possible reason for checking the flag is for efficient handling of JNI_ABORT
. For example, you might want to get an array, modify it in place, pass pieces to other functions, and then discard the changes. If you know that JNI is making a new copy for you, there's no need to create another "editable" copy. If JNI is passing you the original, then you do need to make your own copy.
It is a common mistake (repeated in example code) to assume that you can skip the Release
call if *isCopy
is false. This is not the case. If no copy buffer was allocated, then the original memory must be pinned down and can't be moved by the garbage collector.
Also note that the JNI_COMMIT
flag does not release the array, and you will need to call Release
again with a different flag eventually.
There is an alternative to calls like Get<Type>ArrayElements
and GetStringChars
that may be very helpful when all you want to do is copy data in or out. Consider the following:
jbyte* data = env->GetByteArrayElements(array, NULL);
if (data != NULL) {
memcpy(buffer, data, len);
env->ReleaseByteArrayElements(array, data, JNI_ABORT);
}
This grabs the array, copies the first len
byte elements out of it, and then releases the array. Depending upon the implementation, the Get
call will either pin or copy the array contents. The code copies the data (for perhaps a second time), then calls Release
; in this case JNI_ABORT
ensures there's no chance of a third copy.
One can accomplish the same thing more simply:
env->GetByteArrayRegion(array, 0, len, buffer);
This has several advantages:
Release
after something fails. Similarly, you can use the Set<Type>ArrayRegion
call to copy data into an array, and GetStringRegion
orGetStringUTFRegion
to copy characters out of a String
.
You must not call most JNI functions while an exception is pending. Your code is expected to notice the exception (via the function's return value, ExceptionCheck
, or ExceptionOccurred
) and return, or clear the exception and handle it.
The only JNI functions that you are allowed to call while an exception is pending are:
DeleteGlobalRef
DeleteLocalRef
DeleteWeakGlobalRef
ExceptionCheck
ExceptionClear
ExceptionDescribe
ExceptionOccurred
MonitorExit
PopLocalFrame
PushLocalFrame
Release<PrimitiveType>ArrayElements
ReleasePrimitiveArrayCritical
ReleaseStringChars
ReleaseStringCritical
ReleaseStringUTFChars
Many JNI calls can throw an exception, but often provide a simpler way of checking for failure. For example, ifNewString
returns a non-NULL value, you don't need to check for an exception. However, if you call a method (using a function like CallObjectMethod
), you must always check for an exception, because the return value is not going to be valid if an exception was thrown.
Note that exceptions thrown by interpreted code do not unwind native stack frames, and Android does not yet support C++ exceptions. The JNI Throw
and ThrowNew
instructions just set an exception pointer in the current thread. Upon returning to managed from native code, the exception will be noted and handled appropriately.
Native code can "catch" an exception by calling ExceptionCheck
or ExceptionOccurred
, and clear it withExceptionClear
. As usual, discarding exceptions without handling them can lead to problems.
There are no built-in functions for manipulating the Throwable
object itself, so if you want to (say) get the exception string you will need to find the Throwable
class, look up the method ID for getMessage "()Ljava/lang/String;"
, invoke it, and if the result is non-NULL use GetStringUTFChars
to get something you can hand to printf(3)
or equivalent.
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.
The additional checks include:
NewDirectByteBuffer
. Call*Method
JNI call: incorrect return type, static/non-static mismatch, wrong type for ‘this’ (for non-static calls) or wrong class (for static calls). DeleteGlobalRef
/DeleteLocalRef
on the wrong kind of reference. 0
, JNI_ABORT
, orJNI_COMMIT
). (Accessibility of methods and fields is still not checked: access restrictions don't apply to native code.)
There are several ways to enable CheckJNI.
If you’re using the emulator, CheckJNI is on by default.
If you have a rooted device, you can use the following sequence of commands to restart the runtime with CheckJNI enabled:
adb shell stop
adb shell setprop dalvik.vm.checkjni true
adb shell start
In either of these cases, you’ll see something like this in your logcat output when the runtime starts:
D AndroidRuntime: CheckJNI is ON
If you have a regular device, you can use the following command:
adb shell setprop debug.checkjni 1
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:
D Late-enabling CheckJNI
You can also set the android:debuggable
attribute in your application's manifest to turn on CheckJNI just for your app. Note that the Android build tools will do this automatically for certain build types.