JNI Functions

翻译自https://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/functions.html

Chapter   4

This chapter serves as the reference section for the JNI functions. It provides a complete listing of all the JNI functions. It also presents the exact layout of the JNI function table.

Note the use of the term “must” to describe restrictions on JNI programmers. For example, when you see that a certain JNI function must receive a non-NULL object, it is your responsibility to ensure that NULL is not passed to that JNI function. As a result, a JNI implementation does not need to perform NULL pointer checks in that JNI function.

A portion of this chapter is adapted from Netscape’s JRI documentation.

The reference material groups functions by their usage. The reference section is organized by the following functional areas:

本章用作JNI函数的参考部分。 它提供了所有JNI功能的完整列表。 它还提供了JNI函数表的确切布局。

注意,使用术语“must”来描述对JNI程序员的限制。 例如,当您看到某个JNI函数必须接收一个非NULL对象时,您有责任确保不将NULL传递给该JNI函数。 这样做的结果是,该JNI函数无需执行NULL指针检查。

本章的一部分改编自Netscape的JRI文档。

其用途。 参考部分由以下功能模块组成:

Interface Function Table

可通过JNIEnv参数以固定的偏移量来访问每个JNI函数。 JNIEnv类型是指向存储所有JNI函数指针的结构的指针。 定义如下:

typedef const struct JNINativeInterface* JNIEnv; 

VM初始化函数表,如Code Example 4-1所示。 请注意,前三个条目是保留的,以便将来与COM兼容。 此外,我们在函数表的开头附近保留了一些NULL条目,因此,例如,与将来的类相关的JNI操作,可以在FindClass之后被添加,而不是表的末尾添加。

注意,该功能表可以在所有JNI接口指针之间共享。

Code Example 4-1

const struct JNINativeInterface ... = {

    NULL,
    NULL,
    NULL,
    NULL,
    GetVersion,

    DefineClass,
    FindClass,

    FromReflectedMethod,
    FromReflectedField,
    ToReflectedMethod,

    GetSuperclass,
    IsAssignableFrom,

    ToReflectedField,

    Throw,
    ThrowNew,
    ExceptionOccurred,
    ExceptionDescribe,
    ExceptionClear,
    FatalError,

    PushLocalFrame,
    PopLocalFrame,

    NewGlobalRef,
    DeleteGlobalRef,
    DeleteLocalRef,
    IsSameObject,
    NewLocalRef,
    EnsureLocalCapacity,

    AllocObject,
    NewObject,
    NewObjectV,
    NewObjectA,

    GetObjectClass,
    IsInstanceOf,

    GetMethodID,

    CallObjectMethod,
    CallObjectMethodV,
    CallObjectMethodA,
    CallBooleanMethod,
    CallBooleanMethodV,
    CallBooleanMethodA,
    CallByteMethod,
    CallByteMethodV,
    CallByteMethodA,
    CallCharMethod,
    CallCharMethodV,
    CallCharMethodA,
    CallShortMethod,
    CallShortMethodV,
    CallShortMethodA,
    CallIntMethod,
    CallIntMethodV,
    CallIntMethodA,
    CallLongMethod,
    CallLongMethodV,
    CallLongMethodA,
    CallFloatMethod,
    CallFloatMethodV,
    CallFloatMethodA,
    CallDoubleMethod,
    CallDoubleMethodV,
    CallDoubleMethodA,
    CallVoidMethod,
    CallVoidMethodV,
    CallVoidMethodA,

    CallNonvirtualObjectMethod,
    CallNonvirtualObjectMethodV,
    CallNonvirtualObjectMethodA,
    CallNonvirtualBooleanMethod,
    CallNonvirtualBooleanMethodV,
    CallNonvirtualBooleanMethodA,
    CallNonvirtualByteMethod,
    CallNonvirtualByteMethodV,
    CallNonvirtualByteMethodA,
    CallNonvirtualCharMethod,
    CallNonvirtualCharMethodV,
    CallNonvirtualCharMethodA,
    CallNonvirtualShortMethod,
    CallNonvirtualShortMethodV,
    CallNonvirtualShortMethodA,
    CallNonvirtualIntMethod,
    CallNonvirtualIntMethodV,
    CallNonvirtualIntMethodA,
    CallNonvirtualLongMethod,
    CallNonvirtualLongMethodV,
    CallNonvirtualLongMethodA,
    CallNonvirtualFloatMethod,
    CallNonvirtualFloatMethodV,
    CallNonvirtualFloatMethodA,
    CallNonvirtualDoubleMethod,
    CallNonvirtualDoubleMethodV,
    CallNonvirtualDoubleMethodA,
    CallNonvirtualVoidMethod,
    CallNonvirtualVoidMethodV,
    CallNonvirtualVoidMethodA,

    GetFieldID,

    GetObjectField,
    GetBooleanField,
    GetByteField,
    GetCharField,
    GetShortField,
    GetIntField,
    GetLongField,
    GetFloatField,
    GetDoubleField,
    SetObjectField,
    SetBooleanField,
    SetByteField,
    SetCharField,
    SetShortField,
    SetIntField,
    SetLongField,
    SetFloatField,
    SetDoubleField,

    GetStaticMethodID,

    CallStaticObjectMethod,
    CallStaticObjectMethodV,
    CallStaticObjectMethodA,
    CallStaticBooleanMethod,
    CallStaticBooleanMethodV,
    CallStaticBooleanMethodA,
    CallStaticByteMethod,
    CallStaticByteMethodV,
    CallStaticByteMethodA,
    CallStaticCharMethod,
    CallStaticCharMethodV,
    CallStaticCharMethodA,
    CallStaticShortMethod,
    CallStaticShortMethodV,
    CallStaticShortMethodA,
    CallStaticIntMethod,
    CallStaticIntMethodV,
    CallStaticIntMethodA,
    CallStaticLongMethod,
    CallStaticLongMethodV,
    CallStaticLongMethodA,
    CallStaticFloatMethod,
    CallStaticFloatMethodV,
    CallStaticFloatMethodA,
    CallStaticDoubleMethod,
    CallStaticDoubleMethodV,
    CallStaticDoubleMethodA,
    CallStaticVoidMethod,
    CallStaticVoidMethodV,
    CallStaticVoidMethodA,

    GetStaticFieldID,

    GetStaticObjectField,
    GetStaticBooleanField,
    GetStaticByteField,
    GetStaticCharField,
    GetStaticShortField,
    GetStaticIntField,
    GetStaticLongField,
    GetStaticFloatField,
    GetStaticDoubleField,

    SetStaticObjectField,
    SetStaticBooleanField,
    SetStaticByteField,
    SetStaticCharField,
    SetStaticShortField,
    SetStaticIntField,
    SetStaticLongField,
    SetStaticFloatField,
    SetStaticDoubleField,

    NewString,

    GetStringLength,
    GetStringChars,
    ReleaseStringChars,

    NewStringUTF,
    GetStringUTFLength,
    GetStringUTFChars,
    ReleaseStringUTFChars,

    GetArrayLength,

    NewObjectArray,
    GetObjectArrayElement,
    SetObjectArrayElement,

    NewBooleanArray,
    NewByteArray,
    NewCharArray,
    NewShortArray,
    NewIntArray,
    NewLongArray,
    NewFloatArray,
    NewDoubleArray,

    GetBooleanArrayElements,
    GetByteArrayElements,
    GetCharArrayElements,
    GetShortArrayElements,
    GetIntArrayElements,
    GetLongArrayElements,
    GetFloatArrayElements,
    GetDoubleArrayElements,

    ReleaseBooleanArrayElements,
    ReleaseByteArrayElements,
    ReleaseCharArrayElements,
    ReleaseShortArrayElements,
    ReleaseIntArrayElements,
    ReleaseLongArrayElements,
    ReleaseFloatArrayElements,
    ReleaseDoubleArrayElements,

    GetBooleanArrayRegion,
    GetByteArrayRegion,
    GetCharArrayRegion,
    GetShortArrayRegion,
    GetIntArrayRegion,
    GetLongArrayRegion,
    GetFloatArrayRegion,
    GetDoubleArrayRegion,
    SetBooleanArrayRegion,
    SetByteArrayRegion,
    SetCharArrayRegion,
    SetShortArrayRegion,
    SetIntArrayRegion,
    SetLongArrayRegion,
    SetFloatArrayRegion,
    SetDoubleArrayRegion,

    RegisterNatives,
    UnregisterNatives,

    MonitorEnter,
    MonitorExit,

    GetJavaVM,

    GetStringRegion,
    GetStringUTFRegion,

    GetPrimitiveArrayCritical,
    ReleasePrimitiveArrayCritical,

    GetStringCritical,
    ReleaseStringCritical,

    NewWeakGlobalRef,
    DeleteWeakGlobalRef,

    ExceptionCheck,

    NewDirectByteBuffer,
    GetDirectBufferAddress,
    GetDirectBufferCapacity,

    GetObjectRefType
  };

 

Version Information

GetVersion

jint GetVersion(JNIEnv *env);

返回本地方法接口的版本。

LINKAGE:

Index 4 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

RETURNS:

Returns the major version number in the higher 16 bits and the minor version number in the lower 16 bits.

In JDK/JRE 1.1, GetVersion() returns 0x00010001.

In JDK/JRE 1.2, GetVersion() returns 0x00010002.

In JDK/JRE 1.4, GetVersion() returns 0x00010004.

In JDK/JRE 1.6, GetVersion() returns 0x00010006.

Constants

SINCE JDK/JRE 1.2:

 

#define JNI_VERSION_1_1 0x00010001
#define JNI_VERSION_1_2 0x00010002

/* Error codes */
#define JNI_EDETACHED    (-2)              /* thread detached from the VM */
#define JNI_EVERSION     (-3)              /* JNI version error */

SINCE JDK/JRE 1.4:

    #define JNI_VERSION_1_4 0x00010004

SINCE JDK/JRE 1.6:

    #define JNI_VERSION_1_6 0x00010006

 

Class Operations

DefineClass

jclass DefineClass(JNIEnv *env, const char *name, jobject loader,
const jbyte *buf, jsize bufLen);

 

从二进制类数据的缓冲区中加载类。 在DefineClass调用返回后,VM不会引用包含二进制类数据的缓冲区,如果需要,可以将其丢弃。

LINKAGE:

Index 5 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

name: the name of the class or interface to be defined. The string is encoded in modified UTF-8.

loader: a class loader assigned(分配) to the defined class.

buf: buffer containing the .class file data.

bufLen: buffer length.

RETURNS:

Returns a Java class object or NULL if an error occurs.

THROWS:

ClassFormatError: if the class data does not specify a valid class.

ClassCircularityError(类递归错误): if a class or interface would be its own superclass or superinterface.

OutOfMemoryError: if the system runs out of memory.

SecurityException: if the caller attempts to define a class in the "java" package tree.

FindClass

jclass FindClass(JNIEnv *env, const char *name);

 

在JDK版本1.1中,此函数加载本地定义的类。它在CLASSPATH环境变量指定的目录和zip文件中搜索具有指定名称的类。

从Java 2 SDK 1.2版开始,Java安全模型允许非系统类加载和调用本地方法。 FindClass查找与当前本地方法关联的类加载器;也就是说,声明了本地方法的类的类加载器。如果本地方法属于系统类,则不涉及任何类加载器。否则,将调用适当的类加载器以加载和链接指定名称的类。

从Java 2 SDK 1.2版开始,通过调用接口调用FindClass时,如果没有当前的本地方法或其关联的类加载器,在这种情况下,ClassLoader.getSystemClassLoader将被调用。这是虚拟机为应用程序创建的类加载器,并且能够在java.class.path属性指定的类中查找。

name参数是完全限定的类名或数组类型签名。例如,java.lang.String类的全限定类名是:

                   "java/lang/String"

数组类型java.lang.Object[]的类型签名为:

                   "[Ljava/lang/Object;"

LINKAGE:

Index 6 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

name: a fully-qualified class name (that is, a package name, delimited by “/”, followed by the class name). If the name begins with “[“ (the array signature character), it returns an array class. The string is encoded in modified UTF-8.

RETURNS:

Returns a class object from a fully-qualified name, or NULL if the class cannot be found.

THROWS:

ClassFormatError: if the class data does not specify a valid class.

ClassCircularityError: if a class or interface would be its own superclass or superinterface.

NoClassDefFoundError: if no definition for a requested class or interface can be found.

OutOfMemoryError: if the system runs out of memory.

GetSuperclass

jclass GetSuperclass(JNIEnv *env, jclass clazz);

If clazz represents any class other than the class Object, then this function returns the object that represents the superclass of the class specified by clazz.

If clazz specifies the class Object, or clazz represents an interface, this function returns NULL.

如果clazz表示除Object类之外的任何类,则此函数返回表示clazz指定的类的超类。

如果clazz表示Object类,或者clazz表示接口,则此函数返回NULL。

LINKAGE:

Index 10 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

clazz: a Java class object.

RETURNS:

Returns the superclass of the class represented by clazz, or NULL.

IsAssignableFrom

jboolean IsAssignableFrom(JNIEnv *env, jclass clazz1,
jclass clazz2);

判断clazz1的对象是否可以安全地转换到clazz2。

LINKAGE:

Index 11 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

clazz1: the first class argument.

clazz2: the second class argument.

RETURNS:

Returns JNI_TRUE if either of the following is true:

  • The first and second class arguments refer to the same Java class.

  • The first class is a subclass(子类) of the second class.

  • The first class has the second class as one of its interfaces.(第二个类作为接口,第一个为它的实现)

Exceptions

Throw

jint Throw(JNIEnv *env, jthrowable obj);

Causes a java.lang.Throwable object to be thrown.

LINKAGE:

Index 13 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

obj: a java.lang.Throwable object.

RETURNS:

Returns 0 on success; a negative value on failure.

THROWS:

the java.lang.Throwable object obj.

ThrowNew

jint ThrowNew(JNIEnv *env, jclass clazz,
const char *message);

Constructs an exception object from the specified class with the message specified by message and causes that exception to be thrown.

LINKAGE:

Index 14 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

clazz: a subclass of java.lang.Throwable.

message: the message used to construct the java.lang.Throwable object. The string is encoded in modified UTF-8.

RETURNS:

Returns 0 on success; a negative value on failure.

THROWS:

the newly constructed java.lang.Throwable object.

ExceptionOccurred

jthrowable ExceptionOccurred(JNIEnv *env);

Determines if an exception is being thrown. The exception stays being thrown until either the native code calls ExceptionClear(), or the Java code handles the exception.

LINKAGE:

Index 15 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

RETURNS:

Returns the exception object that is currently in the process of being thrown, or NULL if no exception is currently being thrown.

返回当前进程抛出的异常对象,如果没有异常抛出则返回NULL.

 

ExceptionDescribe

void ExceptionDescribe(JNIEnv *env);

Prints an exception and a backtrace of the stack to a system error-reporting channel, such as stderr. This is a convenience routine provided for debugging.

将异常和堆栈树打印到stderr。 这是为调试提供的便利例程。

LINKAGE:

Index 16 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

ExceptionClear

void ExceptionClear(JNIEnv *env);

Clears any exception that is currently being thrown. If no exception is currently being thrown, this routine has no effect.

LINKAGE:

Index 17 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

FatalError

void FatalError(JNIEnv *env, const char *msg);

Raises a fatal error and does not expect the VM to recover. This function does not return.

引发一个致命错误,且不希望VM恢复。 此函数无返回值。

LINKAGE:

Index 18 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

msg: an error message. The string is encoded in modified UTF-8.

ExceptionCheck

We introduce a convenience function to check for pending exceptions without creating a local reference to the exception object.

jboolean ExceptionCheck(JNIEnv *env);

Returns JNI_TRUE when there is a pending exception; otherwise, returns JNI_FALSE.

LINKAGE:

Index 228 in the JNIEnv interface function table.

SINCE:

JDK/JRE 1.2

Global and Local References

Global References

NewGlobalRef

jobject NewGlobalRef(JNIEnv *env, jobject obj);

Creates a new global reference to the object referred to by the obj argument. The obj argument may be a global or local reference. Global references must be explicitly disposed of by calling DeleteGlobalRef().

创建一个新的对由obj参数引用的对象的全局引用。 obj参数可以是全局或局部引用。 必须通过调用DeleteGlobalRef()显式删除全局引用。

LINKAGE:

Index 21 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

obj: a global or local reference.

RETURNS:

Returns a global reference, or NULL if the system runs out of memory.

DeleteGlobalRef

void DeleteGlobalRef(JNIEnv *env, jobject globalRef);

Deletes the global reference pointed to by globalRef.

LINKAGE:

Index 22 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

globalRef: a global reference.

Local References

本地引用在本地方法调用期间有效。 本机方法返回后,它们将自动释放。 每个本地引用都要花费Java虚拟机一些的资源。 程序员需要确保本地方法不会过度分配本地引用。 尽管在本地方法返回后会自动释放本地引用,但是过多分配本地引用可能会导致VM在执行本地方法期间耗尽内存。

DeleteLocalRef

void DeleteLocalRef(JNIEnv *env, jobject localRef);

Deletes the local reference pointed to by localRef.

LINKAGE:

Index 23 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

localRef: a local reference.

Note

JDK / JRE 1.1提供了上面的DeleteLocalRef函数,以便程序员可以手动删除本地引用。 例如,如果本地代码遍历一个潜在的大型对象数组并在每次迭代中使用一个元素,则良好的做法是在下一次迭代创建新的本地引用之前,删除不再使用的数组元素的本地引用。

从JDK / JRE 1.2开始,提供了一组附加功能,用于本地引用生命周期管理。 它们是下面列出的四个功能。

EnsureLocalCapacity

 jint EnsureLocalCapacity(JNIEnv *env, jint capacity);

 

确保在当前线程中至少可以创建给定数量的本地引用。 成功返回0; 否则返回负数并引发OutOfMemoryError。

执行本地方法前,VM会自动确保至少可以创建16个本地引用。

为了向后兼容,VM分配超出保证容量的本地引用。 (作为调试支持,VM可能向用户发出警告,提示正在创建太多的本地引用。在JDK中,程序员可以使用-verbose:jni命令行选项来打开这些消息。) 如果超出了保证的容量,VM将调用FatalError ,无法再创建本地引用。

LINKAGE:

Index 26 in the JNIEnv interface function table.

SINCE:

JDK/JRE 1.2

PushLocalFrame

 jint PushLocalFrame(JNIEnv *env, jint capacity);

Creates a new local reference frame, in which at least a given number of local references can be created. Returns 0 on success, a negative number and a pending OutOfMemoryError on failure.
请注意,在先前的本地引用frame中已经创建的本地引用在当前的本地引用frame中仍然有效。
LINKAGE:

Index 19 in the JNIEnv interface function table.

SINCE:

JDK/JRE 1.2

PopLocalFrame

 jobject PopLocalFrame(JNIEnv *env, jobject result);

Pops off the current local reference frame, frees all the local references, and returns a local reference in the previous local reference frame for the given result object.(并将给定对象result的上一个本地引用frame的一个局部引用返回。)

Pass NULL as result if you do not need to return a reference to the previous frame.

如果不需要返回上一个本地引用frame的引用,则result参数传递NULL。

LINKAGE:

Index 20 in the JNIEnv interface function table.

SINCE:

JDK/JRE 1.2

NewLocalRef

jobject NewLocalRef(JNIEnv *env, jobject ref);

Creates a new local reference that refers to the same object as ref. The given ref may be a global or local reference. Returns NULL if ref refers to null.

LINKAGE:

Index 25 in the JNIEnv interface function table.

SINCE:

JDK/JRE 1.2

Weak Global References

弱全局引用是一种特殊的全局引用。 与普通全局引用不同,弱全局引用允许对底层Java对象进行垃圾回收。  弱全局引用可以用在全局或局部引用都可以使用的情况下。 当垃圾收集器运行时,如果一个对象仅被弱引用引用,那么它将被释放。 指向一个已经释放了的对象的弱全局引用在功能上等效于NULL。 程序员可以通过使用IsSameObject将弱引用与NULL比较来检测弱全局引用是否指向已经释放了的对象。

JNI中的弱全局引用是Java弱引用的简化版本,可作为Java 2 Platform API(java.lang.ref包及其类)的一部分提供。

Clarification    (added June 2001)

由于在本地方法运行时可能会进行垃圾回收,因此一个仅被弱全局引用引用的对象可以随时被释放。 尽管可以在使用全局引用的地方使用弱全局引用,但是这样做通常是不合适的,因为也许没有任何通知,它们就可能在功能上效于NULL。

尽管IsSameObject可以用于确定弱全局引用是否指向已释放的对象,但是它不能阻止此后立即释放该对象。 因此,programmers may not rely on this check to determine whether a weak global reference may used (as a non-NULL reference) in any future JNI function call.(程序员可能不能依赖此检查来确定在将来的JNI调用中,这个弱全局引用作为非NULL引用来被使用 (就是说,现在不为NULL, 但将来可能为NULL))

为了克服此限制,建议使用JNI函数NewLocalRefNewGlobalRef获取对同一对象的标准(强)局部或全局引用,并建议使用该强引用来访问预期的对象。如果对象已释放,这些函数将返回NULL,否则将返回强引用(这将防止对象被释放)。当不再需要访问该对象时,应该显式删除新引用,从而允许该可以被释放。

The weak global reference is weaker than other types of weak references (Java objects of the SoftReference or WeakReference classes). A weak global reference to a specific object will not become functionally equivalent to NULL until after SoftReference or WeakReference objects referring to that same specific object have had their references cleared.

弱全局引用比其他类型的弱引用(SoftReference或WeakReference类的Java对象)弱。在引用同一特定对象的SoftReference或WeakReference被清除引用之后,该对象的弱全局引用将在功能上等于NULL。

The weak global reference is weaker than Java's internal references to objects requiring finalization. A weak global reference will not become functionally equivalent to NULL until after the completion of the finalizer for the referenced object, if present.
弱全局引用比Java内部需要finalizer的对象弱。当完成了所引用对象的终结(如果存在)之后,弱全局引用在功能上等同于NULL。

Interactions between weak global references and PhantomReferences are undefined. In particular, implementations of a Java VM may (or may not) process weak global references after PhantomReferences, and it may (or may not) be possible to use weak global references to hold on to objects which are also referred to by PhantomReference objects. This undefined use of weak global references should be avoided.

弱全局引用和PhantomReferences之间的交互是不确定的。特别地,Java VM的实现可以(或可以不)在PhantomReferences之后处理弱全局引用,并且可能(或不可能)使用弱全局引用来保留也由PhantomReference引用的对象。应避免对弱全局引用的未定义使用。

NewWeakGlobalRef

jweak NewWeakGlobalRef(JNIEnv *env, jobject obj);

Creates a new weak global reference. Returns NULL if obj refers to null, or if the VM runs out of memory. If the VM runs out of memory, an OutOfMemoryError will be thrown.

LINKAGE:

Index 226 in the JNIEnv interface function table.

SINCE:

JDK/JRE 1.2

DeleteWeakGlobalRef

void DeleteWeakGlobalRef(JNIEnv *env, jweak obj);

Delete the VM resources needed for the given weak global reference.

LINKAGE:

Index 227 in the JNIEnv interface function table.

SINCE:

JDK/JRE 1.2

Object Operations

AllocObject

jobject AllocObject(JNIEnv *env, jclass clazz);

Allocates a new Java object without invoking any of the constructors for the object. Returns a reference to the object

The clazz argument must not refer to an array class.

LINKAGE:

Index 27 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

clazz: a Java class object.

RETURNS:

Returns a Java object, or NULL if the object cannot be constructed.

THROWS:

InstantiationException: if the class is an interface or an abstract class.

OutOfMemoryError: if the system runs out of memory.

NewObject
NewObjectA
NewObjectV

jobject NewObject(JNIEnv *env, jclass clazz,
jmethodID methodID, ...);

jobject NewObjectA(JNIEnv *env, jclass clazz,
jmethodID methodID, const jvalue *args);

jobject NewObjectV(JNIEnv *env, jclass clazz,
jmethodID methodID, va_list args);

Constructs a new Java object. The method ID indicates which constructor method to invoke.

This ID must be obtained by calling GetMethodID() with <init> as the method name and void (V) as the return type

(此ID必须通过调用GetMethodID(),使用<init>作为方法名参数、void(V)作为返回值类型参数来调用GetMethodID()

The clazz argument must not refer to an array class.

NewObject

Programmers place all arguments that are to be passed to the constructor immediately following the methodID argument. NewObject() accepts these arguments and passes them to the Java method that the programmer wishes to invoke.

methodID参数之后的所有参数都将传递给构造函数。 NewObject()接受这些参数,并将它们传递给程序员希望调用的Java方法。

LINKAGE:

Index 28 in the JNIEnv interface function table.

NewObjectA

Programmers place all arguments that are to be passed to the constructor in an args array of jvalues that immediately follows the methodID argument. NewObjectA() accepts the arguments in this array, and, in turn, passes them to the Java method that the programmer wishes to invoke.

紧跟methodID参数后面的jvalue型的args数组中的将所有参数都会传递给构造函数。 NewObjectA()接受此数组中的参数,然后将其传递给程序员希望调用的Java方法。

LINKAGE:

Index 30 in the JNIEnv interface function table.

NewObjectV

Programmers place all arguments that are to be passed to the constructor in an args argument of type va_list that immediately follows the methodID argument. NewObjectV() accepts these arguments, and, in turn, passes them to the Java method that the programmer wishes to invoke.

紧跟mthodID参数之后的args类型的va_list中的所有参数都将传递给构造函数,NewObjectV()接受这些参数,然后将其传递给程序员希望调用的Java方法。

LINKAGE:

Index 29 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

clazz: a Java class object.

methodID: the method ID of the constructor.

Additional Parameter for NewObject:

arguments to the constructor.

Additional Parameter for NewObjectA:

args: an array of arguments to the constructor.

Additional Parameter for NewObjectV:

args: a va_list of arguments to the constructor.

RETURNS:

Returns a Java object, or NULL if the object cannot be constructed.

THROWS:

InstantiationException: if the class is an interface or an abstract class.

OutOfMemoryError: if the system runs out of memory.

Any exceptions thrown by the constructor.

GetObjectClass

jclass GetObjectClass(JNIEnv *env, jobject obj);

Returns the class of an object.

LINKAGE:

Index 31 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

obj: a Java object (must not be NULL).

RETURNS:

Returns a Java class object.

GetObjectRefType

jobjectRefType GetObjectRefType(JNIEnv* env, jobject obj);

Returns the type of the object referred to by the obj argument. The argument obj can either be a local, global or weak global reference.(返回obj参数引用的对象的类型。 参数obj可以是局部,全局或弱全局引用。)

LINKAGE:

Index 232 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

obj: a local, global or weak global reference.

vm: the virtual machine instance from which the interface will be retrieved.

env: pointer to the location where the JNI interface pointer for the current thread will be placed.

version: the requested JNI version.

RETURNS:

The function GetObjectRefType returns one of the following enumerated values defined as a jobjectRefType:

JNIInvalidRefType = 0,
JNILocalRefType = 1,
JNIGlobalRefType = 2,
JNIWeakGlobalRefType = 3

If the argument obj is a weak global reference type, the return will be JNIWeakGlobalRefType.

If the argument obj is a global reference type, the return value will be JNIGlobalRefType.

If the argument obj is a local reference type, the return will be JNILocalRefType.

If the obj argument is not a valid reference, the return value for this function will be JNIInvalidRefType.

An invalid reference is a reference which is not a valid handle. That is, the obj pointer address does not point to a location in memory which has been allocated from one of the Ref creation functions or returned from a JNI function.

无效引用是一个非有效句柄的引用。 也就是说,obj指针地址没有指向内存中被Ref创建函数分配或从JNI函数返回的位置。

As such, NULL would be an invalid reference and GetObjectRefType(env,NULL) would return JNIInvalidRefType.

NULL是无效的引用,而GetObjectRefType(env,NULL) 将返回JNIInvalidRefType。

On the other hand, a null reference, which is a reference that points to a null, would return the type of reference that the null reference was originally created as.

另一方面,空引用(即指向空值null的引用)将返回最初创建空引用时的引用类型。

GetObjectRefType cannot be used on deleted references.

GetObjectRefType不能用于已删除的引用。

Since references are typically implemented as pointers to memory data structures that can potentially be reused by any of the reference allocation services in the VM, once deleted, it is not specified what value the GetObjectRefType will return.

由于通常将引用被实现为指向内存数据结构的指针,该指针可能会被VM中的任何引用分配服务重用,因此一旦删除,就无法指定GetObjectRefType将返回什么值。

SINCE:

JDK/JRE 1.6

IsInstanceOf

jboolean IsInstanceOf(JNIEnv *env, jobject obj,
jclass clazz);

Tests whether an object is an instance of a class.

LINKAGE:

Index 32 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

obj: a Java object.

clazz: a Java class object.

RETURNS:

Returns JNI_TRUE if obj can be cast to clazz; otherwise, returns JNI_FALSE. A NULL object can be cast to any class.

IsSameObject

jboolean IsSameObject(JNIEnv *env, jobject ref1,
jobject ref2);

Tests whether two references refer to the same Java object.

LINKAGE:

Index 24 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

ref1: a Java object.

ref2: a Java object.

RETURNS:

Returns JNI_TRUE if ref1 and ref2 refer to the same Java object, or are both NULL; otherwise, returns JNI_FALSE.

Accessing Fields of Objects

GetFieldID

jfieldID GetFieldID(JNIEnv *env, jclass clazz,
const char *name, const char *sig);

Returns the field ID for an instance (nonstatic) field of a class. The field is specified by its name and signature. The Get<type>Field and Set<type>Field families of accessor functions use field IDs to retrieve object fields.

返回类的实例(非静态)字段的字段ID。 该字段由其名称和签名指定。Get <type> Field和Set <type> Field系列的访问器函数使用字段ID检索对象字段。

GetFieldID() causes an uninitialized class to be initialized.

GetFieldID() cannot be used to obtain the length field of an array. Use GetArrayLength() instead.

LINKAGE:

Index 94 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

clazz: a Java class object.

name: the field name in a 0-terminated modified UTF-8 string.

sig: the field signature in a 0-terminated modified UTF-8 string.

RETURNS:

Returns a field ID, or NULL if the operation fails.

THROWS:

NoSuchFieldError: if the specified field cannot be found.

ExceptionInInitializerError: if the class initializer fails due to an exception.

OutOfMemoryError: if the system runs out of memory.

Get<type>Field Routines

NativeType Get<type>Field(JNIEnv *env, jobject obj,
jfieldID fieldID);

This family of accessor routines returns the value of an instance (nonstatic) field of an object. The field to access is specified by a field ID obtained by calling GetFieldID().

The following table describes the Get<type>Field routine name and result type. You should replace type in Get<type>Field with the Java type of the field, or use one of the actual routine names from the table, and replace NativeType with the corresponding native type for that routine.

下表描述了Get <type> Field例程的名称和返回类型。 您应该用字段的Java类型替换Get <type> Field中的type,或者使用表中的实际例程名称之一,并用该例程的相应本地类型替换NativeType。

 

Table 4-1a Get<type>Field Family of Accessor Routines

 

Get<type>Field Routine Name

Native Type

GetObjectField()

jobject

GetBooleanField()

jboolean

GetByteField()

jbyte

GetCharField()

jchar

GetShortField()

jshort

GetIntField()

jint

GetLongField()

jlong

GetFloatField()

jfloat

GetDoubleField()

jdouble

LINKAGE:

Indices in the JNIEnv interface function table:

Table 4-1b Get<type>Field Family of Accessor Routines

Get<type>Field Routine Name

Index

GetObjectField()

95

GetBooleanField()

96

GetByteField()

97

GetCharField()

98

GetShortField()

99

GetIntField()

100

GetLongField()

101

GetFloatField()

102

GetDoubleField()

103

PARAMETERS:

env: the JNI interface pointer.

obj: a Java object (must not be NULL).

fieldID: a valid field ID.

RETURNS:

Returns the content of the field.

Set<type>Field Routines

void Set<type>Field(JNIEnv *env, jobject obj, jfieldID fieldID,
NativeType value);

This family of accessor routines sets the value of an instance (nonstatic) field of an object. The field to access is specified by a field ID obtained by calling GetFieldID().

The following table describes the Set<type>Field routine name and value type. You should replace type in Set<type>Field with the Java type of the field, or use one of the actual routine names from the table, and replace NativeType with the corresponding native type for that routine.

下表描述了Set <type> Field例程的名称和值类型。 您应该使用字段的Java类型替换Set <type> Field中的type,或者使用表中的实际例程名称之一,并使用该例程的对应本机类型替换NativeType。

Table 4-2a Set<type>Field Family of Accessor Routines

 

Set<type>Field Routine

Native Type

SetObjectField()

jobject

SetBooleanField()

jboolean

SetByteField()

jbyte

SetCharField()

jchar

SetShortField()

jshort

SetIntField()

jint

SetLongField()

jlong

SetFloatField()

jfloat

SetDoubleField()

jdouble

LINKAGE:

Indices in the JNIEnv interface function table.

Table 4-2b Set<type>Field Family of Accessor Routines

Set<type>Field Routine

Index

SetObjectField()

104

SetBooleanField()

105

SetByteField()

106

SetCharField()

107

SetShortField()

108

SetIntField()

109

SetLongField()

110

SetFloatField()

111

SetDoubleField()

112

PARAMETERS:

env: the JNI interface pointer.

obj: a Java object (must not be NULL).

fieldID: a valid field ID.

value: the new value of the field.

Calling Instance Methods

GetMethodID

jmethodID GetMethodID(JNIEnv *env, jclass clazz,
const char *name, const char *sig);

Returns the method ID for an instance (nonstatic) method of a class or interface. The method may be defined in one of the clazz’s superclasses and inherited by clazz. The method is determined by its name and signature.

返回类或接口的实例(非静态)方法的方法ID。 该方法可以在clazz的超类之一中定义,并由clazz继承。 该方法由其名称和签名确定。

GetMethodID() causes an uninitialized class to be initialized.

To obtain the method ID of a constructor, supply <init> as the method name and void (V) as the return type.

为了得到构造函数的方法ID,需要使用<init>作为方法名、void(V)作为返回类型。

LINKAGE:

Index 33 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

clazz: a Java class object.

name: the method name in a 0-terminated modified UTF-8 string.

sig: the method signature in 0-terminated modified UTF-8 string.

RETURNS:

Returns a method ID, or NULL if the specified method cannot be found.

THROWS:

NoSuchMethodError: if the specified method cannot be found.

ExceptionInInitializerError: if the class initializer fails due to an exception.

OutOfMemoryError: if the system runs out of memory.

Call<type>Method Routines
Call<type>MethodA Routines
Call<type>MethodV Routines

NativeType Call<type>Method(JNIEnv *env, jobject obj,
jmethodID methodID, ...);

NativeType Call<type>MethodA(JNIEnv *env, jobject obj,
jmethodID methodID, const jvalue *args);

NativeType Call<type>MethodV(JNIEnv *env, jobject obj,
jmethodID methodID, va_list args);

Methods from these three families of operations are used to call a Java instance method from a native method.They only differ in their mechanism for passing parameters to the methods that they call.

这三个操作族中的方法用于从本地方法调用Java实例方法,它们的区别仅在于将参数传递给所调用方法的机制不同。

These families of operations invoke an instance (nonstatic) method on a Java object, according to the specified method ID. The methodID argument must be obtained by calling GetMethodID().

这些操作族根据指定的方法ID调用Java对象上的实例(非静态)方法。 methodID参数必须通过调用GetMethodID()获得。

When these functions are used to call private methods and constructors, the method ID must be derived from the real class of obj, not from one of its superclasses.

当这些函数用于调用私有方法和构造函数时,方法ID必须从obj的真实类派生,而不是从其超类之一派生。

 

Call<type>Method Routines

Programmers place all arguments that are to be passed to the method immediately following the methodID argument. The Call<type>Method routine accepts these arguments and passes them to the Java method that the programmer wishes to invoke.

Call<type>MethodA Routines

Programmers place all arguments to the method in an args array of jvalues that immediately follows the methodID argument. The Call<type>MethodA routine accepts the arguments in this array, and, in turn, passes them to the Java method that the programmer wishes to invoke.

Call<type>MethodV Routines

Programmers place all arguments to the method in an args argument of type va_list that immediately follows the methodID argument. The Call<type>MethodV routine accepts the arguments, and, in turn, passes them to the Java method that the programmer wishes to invoke.

The following table describes each of the method calling routines according to their result type. You should replace type in Call<type>Method with the Java type of the method you are calling (or use one of the actual method calling routine names from the table) and replace NativeType with the corresponding native type for that routine.

下表根据结果类型描述了每个方法调用例程。 您应将Call <type> Method中的type替换为正在调用的方法的Java类型(或使用表中调用例程名称的实际方法之一),并将NativeType替换为该例程的相应本地类型。

 

Table 4-3a Instance Method Calling Routines

 

Call<type>Method Routine Name

Native Type

CallVoidMethod()

CallVoidMethodA()

CallVoidMethodV()

void

CallObjectMethod()

CallObjectMethodA()

CallObjectMethodV()

jobject

CallBooleanMethod()

CallBooleanMethodA()

CallBooleanMethodV()

jboolean

CallByteMethod()

CallByteMethodA()

CallByteMethodV()

jbyte

CallCharMethod()

CallCharMethodA()

CallCharMethodV()

jchar

CallShortMethod()

CallShortMethodA()

CallShortMethodV()

jshort

CallIntMethod()

CallIntMethodA()

CallIntMethodV()

jint

CallLongMethod()

CallLongMethodA()

CallLongMethodV()

jlong

CallFloatMethod()

CallFloatMethodA()

CallFloatMethodV()

jfloat

CallDoubleMethod()

CallDoubleMethodA()

CallDoubleMethodV()

jdouble

LINKAGE:

Indices in the JNIEnv interface function table:

Table 4-3b Instance Method Calling Routines

Call<type>Method Routine Name

Index

CallVoidMethod()

CallVoidMethodA()

CallVoidMethodV()

61
63
62

CallObjectMethod()

CallObjectMethodA()

CallObjectMethodV()

34
36
35

CallBooleanMethod()

CallBooleanMethodA()

CallBooleanMethodV()

37
39
38

CallByteMethod()

CallByteMethodA()

CallByteMethodV()

40
42
41

CallCharMethod()

CallCharMethodA()

CallCharMethodV()

43
45
44

CallShortMethod()

CallShortMethodA()

CallShortMethodV()

46
48
47

CallIntMethod()

CallIntMethodA()

CallIntMethodV()

49
51
50

CallLongMethod()

CallLongMethodA()

CallLongMethodV()

52
54
53

CallFloatMethod()

CallFloatMethodA()

CallFloatMethodV()

55
57
56

CallDoubleMethod()

CallDoubleMethodA()

CallDoubleMethodV()

58
60
59

PARAMETERS:

env: the JNI interface pointer.

obj: a Java object.

methodID: a method ID.

Additional Parameter for Call<type>Method Routines:

arguments to the Java method.

Additional Parameter for Call<type>MethodA Routines:

args: an array of arguments.

Additional Parameter for Call<type>MethodV Routines:

args: a va_list of arguments.

RETURNS:

Returns the result of calling the Java method.

THROWS:

Exceptions raised during the execution of the Java method.

CallNonvirtual<type>Method Routines
CallNonvirtual<type>MethodA Routines
CallNonvirtual<type>MethodV Routines

NativeType CallNonvirtual<type>Method(JNIEnv *env, jobject obj,
jclass clazz, jmethodID methodID, ...);

NativeType CallNonvirtual<type>MethodA(JNIEnv *env, jobject obj,
jclass clazz, jmethodID methodID, const jvalue *args);

NativeType CallNonvirtual<type>MethodV(JNIEnv *env, jobject obj,
jclass clazz, jmethodID methodID, va_list args);

These families of operations invoke an instance (nonstatic) method on a Java object, according to the specified class and method ID. The methodID argument must be obtained by calling GetMethodID() on the class clazz.

这些操作簇根据指定的类和方法ID调用Java对象上的实例(非静态)方法。 methodID参数必须通过在clazz类上调用GetMethodID()获得

The CallNonvirtual<type>Method families of routines and the Call<type>Method families of routines are different. Call<type>Method routines invoke the method based on the class of the object, while CallNonvirtual<type>Method routines invoke the method based on the class, designated by the clazz parameter, from which the method ID is obtained. The method ID must be obtained from the real class of the object or from one of its superclasses.

CallNonvirtual <type> Method 簇类和Call <type> Method簇类是不同的。 Call <type> Method根据对象的类来调用方法,而CallNonvirtual <type> Method根据由clazz参数指定的类来调用方法,并从中获取方法ID。 方法ID必须从对象的真实类或其超类之一获得。

CallNonvirtual<type>Method Routines

Programmers place all arguments that are to be passed to the method immediately following the methodID argument. The CallNonvirtual<type>Method routine accepts these arguments and passes them to the Java method that the programmer wishes to invoke.

CallNonvirtual<type>MethodA Routines

Programmers place all arguments to the method in an args array of jvalues that immediately follows the methodID argument. The CallNonvirtual<type>MethodA routine accepts the arguments in this array, and, in turn, passes them to the Java method that the programmer wishes to invoke.

CallNonvirtual<type>MethodV Routines

Programmers place all arguments to the method in an args argument of type va_list that immediately follows the methodID argument. The CallNonvirtualMethodV routine accepts the arguments, and, in turn, passes them to the Java method that the programmer wishes to invoke.

The following table describes each of the method calling routines according to their result type. You should replace type in CallNonvirtual<type>Method with the Java type of the method, or use one of the actual method calling routine names from the table, and replace NativeType with the corresponding native type for that routine.

下表根据结果类型描述了每个方法调用例程。 您应该用该方法的Java类型替换CallNonvirtual <type> Method中的type,或者使用表中实际的调用例程名称的方法之一,并用该例程的相应本地类型替换NativeType。

Table 4-4a CallNonvirtual<type>Method Routines

 

CallNonvirtual<type>Method Routine Name

Native Type

CallNonvirtualVoidMethod()

CallNonvirtualVoidMethodA()

CallNonvirtualVoidMethodV()

void

CallNonvirtualObjectMethod()

CallNonvirtualObjectMethodA()

CallNonvirtualObjectMethodV()

jobject

CallNonvirtualBooleanMethod()

CallNonvirtualBooleanMethodA()

CallNonvirtualBooleanMethodV()

jboolean

CallNonvirtualByteMethod()

CallNonvirtualByteMethodA()

CallNonvirtualByteMethodV()

jbyte

CallNonvirtualCharMethod()

CallNonvirtualCharMethodA()

CallNonvirtualCharMethodV()

jchar

CallNonvirtualShortMethod()

CallNonvirtualShortMethodA()

CallNonvirtualShortMethodV()

jshort

CallNonvirtualIntMethod()

CallNonvirtualIntMethodA()

CallNonvirtualIntMethodV()

jint

CallNonvirtualLongMethod()

CallNonvirtualLongMethodA()

CallNonvirtualLongMethodV()

jlong

CallNonvirtualFloatMethod()

CallNonvirtualFloatMethodA()

CallNonvirtualFloatMethodV()

jfloat

CallNonvirtualDoubleMethod()

CallNonvirtualDoubleMethodA()

CallNonvirtualDoubleMethodV()

jdouble

LINKAGE:

Indices in the JNIEnv interface function table.

Table 4-4b CallNonvirtual<type>Method Routines

CallNonvirtual<type>Method Routine Name

Index

CallNonvirtualVoidMethod()

CallNonvirtualVoidMethodA()

CallNonvirtualVoidMethodV()

91
93
92

CallNonvirtualObjectMethod()

CallNonvirtualObjectMethodA()

CallNonvirtualObjectMethodV()

64
66
65

CallNonvirtualBooleanMethod()

CallNonvirtualBooleanMethodA()

CallNonvirtualBooleanMethodV()

67
69
68

CallNonvirtualByteMethod()

CallNonvirtualByteMethodA()

CallNonvirtualByteMethodV()

70
72
71

CallNonvirtualCharMethod()

CallNonvirtualCharMethodA()

CallNonvirtualCharMethodV()

73
75
74

CallNonvirtualShortMethod()

CallNonvirtualShortMethodA()

CallNonvirtualShortMethodV()

76
78
77

CallNonvirtualIntMethod()

CallNonvirtualIntMethodA()

CallNonvirtualIntMethodV()

79
81
80

CallNonvirtualLongMethod()

CallNonvirtualLongMethodA()

CallNonvirtualLongMethodV()

82
84
83

CallNonvirtualFloatMethod()

CallNonvirtualFloatMethodA()

CallNonvirtualFloatMethodV()

85
87
86

CallNonvirtualDoubleMethod()

CallNonvirtualDoubleMethodA()

CallNonvirtualDoubleMethodV()

88
90
89

PARAMETERS:

env: the JNI interface pointer.

clazz: a Java class.

obj: a Java object.

methodID: a method ID.

Additional Parameter for CallNonvirtual<type>Method Routines:

arguments to the Java method.

Additional Parameter for CallNonvirtual<type>MethodA Routines:

args: an array of arguments.

Additional Parameter for CallNonvirtual<type>MethodV Routines:

args: a va_list of arguments.

RETURNS:

Returns the result of calling the Java method.

THROWS:

Exceptions raised during the execution of the Java method.

Accessing Static Fields

GetStaticFieldID

jfieldID GetStaticFieldID(JNIEnv *env, jclass clazz,
const char *name, const char *sig);

Returns the field ID for a static field of a class. The field is specified by its name and signature. The GetStatic<type>Field and SetStatic<type>Field families of accessor functions use field IDs to retrieve static fields.

GetStaticFieldID() causes an uninitialized class to be initialized.

LINKAGE:

Index 144 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

clazz: a Java class object.

name: the static field name in a 0-terminated modified UTF-8 string.

sig: the field signature in a 0-terminated modified UTF-8 string.

RETURNS:

Returns a field ID, or NULL if the specified static field cannot be found.

THROWS:

NoSuchFieldError: if the specified static field cannot be found.

ExceptionInInitializerError: if the class initializer fails due to an exception.

OutOfMemoryError: if the system runs out of memory.

GetStatic<type>Field Routines

NativeType GetStatic<type>Field(JNIEnv *env, jclass clazz,
jfieldID fieldID);

This family of accessor routines returns the value of a static field of an object. The field to access is specified by a field ID, which is obtained by calling GetStaticFieldID().

The following table describes the family of get routine names and result types. You should replace type in GetStatic<type>Field with the Java type of the field, or one of the actual static field accessor routine names from the table, and replace NativeType with the corresponding native type for that routine.

Table 4-5a GetStatic<type>Field Family of Accessor Routines

 

GetStatic<type>Field Routine Name

Native Type

GetStaticObjectField()

jobject

GetStaticBooleanField()

jboolean

GetStaticByteField()

jbyte

GetStaticCharField()

jchar

GetStaticShortField()

jshort

GetStaticIntField()

jint

GetStaticLongField()

jlong

GetStaticFloatField()

jfloat

GetStaticDoubleField()

jdoubl

LINKAGE:

Indices in the JNIEnv interface function table.

Table 4-5b GetStatic<type>Field Family of Accessor Routines

GetStatic<type>Field Routine Name

Index

GetStaticObjectField()

145

GetStaticBooleanField()

146

GetStaticByteField()

147

GetStaticCharField()

148

GetStaticShortField()

149

GetStaticIntField()

150

GetStaticLongField()

151

GetStaticFloatField()

152

GetStaticDoubleField()

153

PARAMETERS:

env: the JNI interface pointer.

clazz: a Java class object.

fieldID: a static field ID.

RETURNS:

Returns the content of the static field.

SetStatic<type>Field Routines

void SetStatic<type>Field(JNIEnv *env, jclass clazz,
jfieldID fieldID, NativeType value);

This family of accessor routines sets the value of a static field of an object. The field to access is specified by a field ID, which is obtained by calling GetStaticFieldID().

The following table describes the set routine name and value types. You should replace type in SetStatic<type>Field with the Java type of the field, or one of the actual set static field routine names from the table, and replace NativeType with the corresponding native type for that routine.

Table 4-6a SetStatic<type>Field Family of Accessor Routines

 

SetStatic<type>Field Routine Name

NativeType

SetStaticObjectField()

jobject

SetStaticBooleanField()

jboolean

SetStaticByteField()

jbyte

SetStaticCharField()

jchar

SetStaticShortField()

jshort

SetStaticIntField()

jint

SetStaticLongField()

jlong

SetStaticFloatField()

jfloat

SetStaticDoubleField()

jdoubl

LINKAGE:

Indices in the JNIEnv interface function table.

Table 4-6b SetStatic<type>Field Family of Accessor Routines

SetStatic<type>Field Routine Name

Index

SetStaticObjectField()

154

SetStaticBooleanField()

155

SetStaticByteField()

156

SetStaticCharField()

157

SetStaticShortField()

158

SetStaticIntField()

159

SetStaticLongField()

160

SetStaticFloatField()

161

SetStaticDoubleField()

162

PARAMETERS:

env: the JNI interface pointer.

clazz: a Java class object.

fieldID: a static field ID.

value: the new value of the field.

Calling Static Methods

GetStaticMethodID

jmethodID GetStaticMethodID(JNIEnv *env, jclass clazz,
const char *name, const char *sig);

Returns the method ID for a static method of a class. The method is specified by its name and signature.

GetStaticMethodID() causes an uninitialized class to be initialized.

LINKAGE:

Index 113 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

clazz: a Java class object.

name: the static method name in a 0-terminated modified UTF-8 string.

sig: the method signature in a 0-terminated modified UTF-8 string.

RETURNS:

Returns a method ID, or NULL if the operation fails.

THROWS:

NoSuchMethodError: if the specified static method cannot be found.

ExceptionInInitializerError: if the class initializer fails due to an exception.

OutOfMemoryError: if the system runs out of memory.

CallStatic<type>Method Routines
CallStatic<type>MethodA Routines
CallStatic<type>MethodV Routines

NativeType CallStatic<type>Method(JNIEnv *env, jclass clazz,
jmethodID methodID, ...);

NativeType CallStatic<type>MethodA(JNIEnv *env, jclass clazz,
jmethodID methodID, jvalue *args);

NativeType CallStatic<type>MethodV(JNIEnv *env, jclass clazz,
jmethodID methodID, va_list args);

This family of operations invokes a static method on a Java object, according to the specified method ID. The methodID argument must be obtained by calling GetStaticMethodID().

The method ID must be derived from clazz, not from one of its superclasses.

CallStatic<type>Method Routines

Programmers should place all arguments that are to be passed to the method immediately following the methodID argument. The CallStatic<type>Method routine accepts these arguments and passes them to the Java method that the programmer wishes to invoke.

CallStatic<type>MethodA Routines

Programmers should place all arguments to the method in an args array of jvalues that immediately follows the methodID argument. The CallStaticMethodA routine accepts the arguments in this array, and, in turn, passes them to the Java method that the programmer wishes to invoke.

CallStatic<type>MethodV Routines

Programmers should place all arguments to the method in an args argument of type va_list that immediately follows the methodID argument. The CallStaticMethodV routine accepts the arguments, and, in turn, passes them to the Java method that the programmer wishes to invoke.

The following table describes each of the method calling routines according to their result types. You should replace type in CallStatic<type>Method with the Java type of the method, or one of the actual method calling routine names from the table, and replace NativeType with the corresponding native type for that routine.

Table 4-7a CallStatic<type>Method Calling Routines

 

CallStatic<type>Method Routine Name

Native Type

CallStaticVoidMethod()

CallStaticVoidMethodA()

CallStaticVoidMethodV()

void

CallStaticObjectMethod()

CallStaticObjectMethodA()

CallStaticObjectMethodV()

jobject

CallStaticBooleanMethod()

CallStaticBooleanMethodA()

CallStaticBooleanMethodV()

jboolean

CallStaticByteMethod()

CallStaticByteMethodA()

CallStaticByteMethodV()

jbyte

CallStaticCharMethod()

CallStaticCharMethodA()

CallStaticCharMethodV()

jchar

CallStaticShortMethod()

CallStaticShortMethodA()

CallStaticShortMethodV()

jshort

CallStaticIntMethod()

CallStaticIntMethodA()

CallStaticIntMethodV()

jint

CallStaticLongMethod()

CallStaticLongMethodA()

CallStaticLongMethodV()

jlong

CallStaticFloatMethod()

CallStaticFloatMethodA()

CallStaticFloatMethodV()

jfloat

CallStaticDoubleMethod()

CallStaticDoubleMethodA()

CallStaticDoubleMethodV()

jdouble

LINKAGE:

Indices in the JNIEnv interface function table.

Table 4-7b CallStatic<type>Method Calling Routines

CallStatic<type>Method Routine Name

Index

CallStaticVoidMethod()

CallStaticVoidMethodA()

CallStaticVoidMethodV()

141
143
142

CallStaticObjectMethod()

CallStaticObjectMethodA()

CallStaticObjectMethodV()

114
116
115

CallStaticBooleanMethod()

CallStaticBooleanMethodA()

CallStaticBooleanMethodV()

117
119
118

CallStaticByteMethod()

CallStaticByteMethodA()

CallStaticByteMethodV()

120
122
121

CallStaticCharMethod()

CallStaticCharMethodA()

CallStaticCharMethodV()

123
125
124

CallStaticShortMethod()

CallStaticShortMethodA()

CallStaticShortMethodV()

126
128
127

CallStaticIntMethod()

CallStaticIntMethodA()

CallStaticIntMethodV()

129
131
130

CallStaticLongMethod()

CallStaticLongMethodA()

CallStaticLongMethodV()

132
134
133

CallStaticFloatMethod()

CallStaticFloatMethodA()

CallStaticFloatMethodV()

135
137
136

CallStaticDoubleMethod()

CallStaticDoubleMethodA()

CallStaticDoubleMethodV()

138
140
139

PARAMETERS:

env: the JNI interface pointer.

clazz: a Java class object.

methodID: a static method ID.

Additional Parameter for CallStatic<type>Method Routines:

arguments to the static method.

Additional Parameter for CallStatic<type>MethodA Routines:

args: an array of arguments.

Additional Parameter for CallStatic<type>MethodV Routines:

args: a va_list of arguments.

RETURNS:

Returns the result of calling the static Java method.

THROWS:

Exceptions raised during the execution of the Java method.

 

String Operations

NewString

jstring NewString(JNIEnv *env, const jchar *unicodeChars,
jsize len);

Constructs a new java.lang.String object from an array of Unicode characters.

LINKAGE:

Index 163 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

unicodeChars: pointer to a Unicode string.

len: length of the Unicode string.

RETURNS:

Returns a Java string object, or NULL if the string cannot be constructed.

THROWS:

OutOfMemoryError: if the system runs out of memory.

GetStringLength

jsize GetStringLength(JNIEnv *env, jstring string);

Returns the length (the count of Unicode characters) of a Java string.

LINKAGE:

Index 164 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

string: a Java string object.

RETURNS:

Returns the length of the Java string.

GetStringChars

const jchar * GetStringChars(JNIEnv *env, jstring string,
jboolean *isCopy);

Returns a pointer to the array of Unicode characters of the string. This pointer is valid until ReleaseStringchars() is called.

返回一个指向字符串string的Unicode字符数组的指针。 该指针在调用ReleaseStringchars()之前一直有效。

If isCopy is not NULL, then *isCopy is set to JNI_TRUE if a copy is made; or it is set to JNI_FALSE if no copy is made.

如果不关心是否发生了拷贝,则可将isCopy设为NULL。

如果isCopy不为NULL,则如果发生了拷贝,则* isCopy被设置为JNI_TRUE; 没发生拷贝,将其被设置为JNI_FALSE,即返回的是java字符串string的原始指针。

LINKAGE:

Index 165 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

string: a Java string object.

isCopy: a pointer to a boolean.

RETURNS:

Returns a pointer to a Unicode string, or NULL if the operation fails.

ReleaseStringChars

void ReleaseStringChars(JNIEnv *env, jstring string,
const jchar *chars);

Informs the VM that the native code no longer needs access to chars. The chars argument is a pointer obtained from string using GetStringChars().

通知VM本地代码不再需要访问字符串chars。 chars参数是使用GetStringChars()从字符串获取的指针。

LINKAGE:

Index 166 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

string: a Java string object.

chars: a pointer to a Unicode string.

NewStringUTF

jstring NewStringUTF(JNIEnv *env, const char *bytes);

Constructs a new java.lang.String object from an array of characters in modified UTF-8 encoding.

根据编辑后的UTF-8编码的字符数组构造一个新的java.lang.String对象。

LINKAGE:

Index 167 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

bytes: the pointer to a modified UTF-8 string.

RETURNS:

Returns a Java string object, or NULL if the string cannot be constructed.

THROWS:

OutOfMemoryError: if the system runs out of memory.

GetStringUTFLength

jsize GetStringUTFLength(JNIEnv *env, jstring string);

Returns the length in bytes of the modified UTF-8 representation of a string.

返回编辑后的UTF-8形式的字符串的字节长度。

LINKAGE:

Index 168 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

string: a Java string object.

RETURNS:

Returns the UTF-8 length of the string.

GetStringUTFChars

const char * GetStringUTFChars(JNIEnv *env, jstring string,
jboolean *isCopy);

Returns a pointer to an array of bytes representing the string in modified UTF-8 encoding. This array is valid until it is released by ReleaseStringUTFChars().

返回一个编辑后的代表字符串string的UTF-8编码的字节数组的指针。该数组在被ReleaseStringUTFChars()释放之前,一直有效。

If isCopy is not NULL, then *isCopy is set to JNI_TRUE if a copy is made; or it is set to JNI_FALSE if no copy is made.

如果不关心是否发生了拷贝,则可将isCopy设为NULL。

如果isCopy不为NULL,则如果发生了拷贝,则* isCopy被设置为JNI_TRUE; 没发生拷贝,将其被设置为JNI_FALSE,即返回的是java字符串string的原始指针。

LINKAGE:

Index 169 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

string: a Java string object.

isCopy: a pointer to a boolean.

RETURNS:

Returns a pointer to a modified UTF-8 string, or NULL if the operation fails.

ReleaseStringUTFChars

void ReleaseStringUTFChars(JNIEnv *env, jstring string,
const char *utf);

Informs the VM that the native code no longer needs access to utf. The utf argument is a pointer derived from string using GetStringUTFChars().

通知VM本地代码不再需要访问字符串utfutf参数是使用GetStringChars()从字符串string获取的指针。

LINKAGE:

Index 170 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

string: a Java string object.

utf: a pointer to a modified UTF-8 string.

Note

In JDK/JRE 1.1, programmers can get primitive array elements in a user-supplied buffer. As of JDK/JRE 1.2 additional set of functions are provided allowing native code to obtain characters in Unicode (UTF-16) or modified UTF-8 encoding in a user-supplied buffer. See the functions below.

在JDK / JRE 1.1中,程序员可以在用户提供的缓冲区中获取原始数组元素。 从JDK / JRE 1.2开始,提供了其他功能集,允许本地代码在用户提供的缓冲区中获取Unicode(UTF-16)或修改后的UTF-8编码的字符。 请参阅下面的功能。

GetStringRegion

void GetStringRegion(JNIEnv *env, jstring str, jsize start, jsize len, jchar *buf);

Copies len number of Unicode characters beginning at offset start to the given buffer buf.

将从偏移位置start开始的len个Unicode字符复制到给定的缓冲区buf。

Throws StringIndexOutOfBoundsException on index overflow.

LINKAGE:

Index 220 in the JNIEnv interface function table.

SINCE:

JDK/JRE 1.2

GetStringUTFRegion

void GetStringUTFRegion(JNIEnv *env, jstring str, jsize start, jsize len, char *buf);

Translates len number of Unicode characters beginning at offset start into modified UTF-8 encoding and place the result in the given buffer buf.

将从偏移量start开始的len个Unicode字符转换为编辑后的UTF-8编码,并将结果放入给定的缓冲区buf中。

Throws StringIndexOutOfBoundsException on index overflow.

LINKAGE:

Index 221 in the JNIEnv interface function table.

SINCE:

JDK/JRE 1.2

GetStringCritical
ReleaseStringCritical

const jchar * GetStringCritical(JNIEnv *env, jstring string, jboolean *isCopy);
void ReleaseStringCritical(JNIEnv *env, jstring string, const jchar *carray);

The semantics of these two functions are similar to the existing Get/ReleaseStringChars functions. If possible, the VM returns a pointer to string elements; otherwise, a copy is made. However, there are significant restrictions on how these functions can be used. In a code segment enclosed by Get/ReleaseStringCritical calls, the native code must not issue arbitrary JNI calls, or cause the current thread to block.

这两个函数的语义类似于Get / ReleaseStringChars函数。 如果可能,VM返回指向字符串元素的指针; 否则,将进行复制。 但是,如何使用这些功能存在很大的限制。 在由Get / ReleaseStringCritical调用括起来的代码段中,本机代码不得发出任意JNI调用,否则会导致当前线程被阻塞。

The restrictions on Get/ReleaseStringCritical are similar to those on Get/ReleasePrimitiveArrayCritical.
对Get / ReleaseStringCritical的限制与对Get / ReleasePrimitiveArrayCritical的限制相似。

 

LINKAGE (GetStringCritical):

Index 224 in the JNIEnv interface function table.

LINKAGE (ReleaseStingCritical):

Index 225 in the JNIEnv interface function table.

SINCE:

JDK/JRE 1.2

Array Operations

GetArrayLength

jsize GetArrayLength(JNIEnv *env, jarray array);

Returns the number of elements in the array.

LINKAGE:

Index 171 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

array: a Java array object.

RETURNS:

Returns the length of the array.

NewObjectArray

jobjectArray NewObjectArray(JNIEnv *env, jsize length,
jclass elementClass, jobject initialElement);

Constructs a new array holding objects in class elementClass. All elements are initially set to initialElement.

构造一个新数组,其中包含类elementClass中的对象。 所有元素最初都设置为initialElement。

LINKAGE:

Index 172 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

length: array size.

elementClass: array element class.

initialElement: initialization value.

RETURNS:

Returns a Java array object, or NULL if the array cannot be constructed.

THROWS:

OutOfMemoryError: if the system runs out of memory.

GetObjectArrayElement

jobject GetObjectArrayElement(JNIEnv *env,
jobjectArray array, jsize index);

Returns an element of an Object array.

LINKAGE:

Index 173 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

array: a Java array.

index: array index.

RETURNS:

Returns a Java object.

THROWS:

ArrayIndexOutOfBoundsException: if index does not specify a valid index in the array.

SetObjectArrayElement

void SetObjectArrayElement(JNIEnv *env, jobjectArray array,
jsize index, jobject value);

Sets an element of an Object array.

LINKAGE:

Index 174 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

array: a Java array.

index: array index.

value: the new value.

THROWS:

ArrayIndexOutOfBoundsException: if index does not specify a valid index in the array.

ArrayStoreException: if the class of value is not a subclass of the element class of the array.

New<PrimitiveType>Array Routines

ArrayType New<PrimitiveType>Array(JNIEnv *env, jsize length);

A family of operations used to construct a new primitive array object. Table 4-8 describes the specific primitive array constructors. You should replace New<PrimitiveType>Array with one of the actual primitive array constructor routine names from the following table, and replace ArrayType with the corresponding array type for that routine.

用于构造新的基本类型数组的操作簇。 表4-8描述了特定的基本数组构造函数。 您应该用下表中的实际原始数组构造函数例程名称之一替换New <PrimitiveType> Array,并用该例程的对应数组类型替换ArrayType。

Table 4-8a New<PrimitiveType>Array Family of Array Constructors

 

New<PrimitiveType>Array Routines

Array Type

NewBooleanArray()

jbooleanArray

NewByteArray()

jbyteArray

NewCharArray()

jcharArray

NewShortArray()

jshortArray

NewIntArray()

jintArray

NewLongArray()

jlongArray

NewFloatArray()

jfloatArray

NewDoubleArray()

jdoubleArray

LINKAGE:

Indices in the JNIEnv interface function table.

Table 4-8b New<PrimitiveType>Array Family of Array Constructors

 

New<PrimitiveType>Array Routines

Index

NewBooleanArray()

175

NewByteArray()

176

NewCharArray()

177

NewShortArray()

178

NewIntArray()

179

NewLongArray()

180

NewFloatArray()

181

NewDoubleArray()

182

PARAMETERS:

env: the JNI interface pointer.

length: the array length.

RETURNS:

Returns a Java array, or NULL if the array cannot be constructed.

Get<PrimitiveType>ArrayElements Routines

NativeType *Get<PrimitiveType>ArrayElements(JNIEnv *env,
ArrayType array, jboolean *isCopy);

A family of functions that returns the body of the primitive array. The result is valid until the corresponding Release<PrimitiveType>ArrayElements() function is called. Since the returned array may be a copy of the Java array, changes made to the returned array will not necessarily be reflected in the original array until Release<PrimitiveType>ArrayElements() is called.

返回基本类型数组的指针的函数系列。 该结果在调用相应的Release <PrimitiveType> ArrayElements()函数之前一直有效。 由于返回的数组可能是Java数组的副本,因此在调用Release <PrimitiveType> ArrayElements()之前,对返回的数组所做的更改不一定会反映在原始数组中。

If isCopy is not NULL, then *isCopy is set to JNI_TRUE if a copy is made; or it is set to JNI_FALSE if no copy is made.

如果不关心是否发生了拷贝,则可将isCopy设为NULL。

如果isCopy不为NULL,则如果发生了拷贝,则* isCopy被设置为JNI_TRUE; 没发生拷贝,将其被设置为JNI_FALSE,即返回的是java数组array的原始指针。

The following table describes the specific primitive array element accessors. You should make the following substitutions:

  • Replace Get<PrimitiveType>ArrayElements with one of the actual primitive element accessor routine names from the table.
  • Replace ArrayType with the corresponding array type.
  • Replace NativeType with the corresponding native type for that routine.

Regardless of how boolean arrays are represented in the Java VM, GetBooleanArrayElements() always returns a pointer to jbooleans, with each byte denoting an element (the unpacked representation). All arrays of other types are guaranteed to be contiguous in memory.

不管Java VM中如何表示布尔数组,GetBooleanArrayElements()始终返回指向jboolean的指针,每个字节表示一个元素(解压缩的表示形式)(注: typedef uint8_t jboolean; /* unsigned 8 bits */) 。

其他类型的所有数组都保证在内存中是连续的。

Table 4-9a Get<PrimitiveType>ArrayElements Family of Accessor Routines

 

Get<PrimitiveType>ArrayElements Routines

Array Type

Native Type

GetBooleanArrayElements()

jbooleanArray

jboolean

GetByteArrayElements()

jbyteArray

jbyte

GetCharArrayElements()

jcharArray

jchar

GetShortArrayElements()

jshortArray

jshort

GetIntArrayElements()

jintArray

jint

GetLongArrayElements()

jlongArray

jlong

GetFloatArrayElements()

jfloatArray

jfloat

GetDoubleArrayElements()

jdoubleArray

jdouble

 

LINKAGE:

Indices in the JNIEnv interface function table.

Table 4-9b Get<PrimitiveType>ArrayElements Family of Accessor Routines

Get<PrimitiveType>ArrayElements Routines

Index

GetBooleanArrayElements()

183

GetByteArrayElements()

184

GetCharArrayElements()

185

GetShortArrayElements()

186

GetIntArrayElements()

187

GetLongArrayElements()

188

GetFloatArrayElements()

189

GetDoubleArrayElements()

190

PARAMETERS:

env: the JNI interface pointer.

array: a Java array object.

isCopy: a pointer to a boolean.

RETURNS:

Returns a pointer to the array elements, or NULL if the operation fails.

Release<PrimitiveType>ArrayElements Routines

void Release<PrimitiveType>ArrayElements(JNIEnv *env,
ArrayType array, NativeType *elems, jint mode);

A family of functions that informs the VM that the native code no longer needs access to elems. The elems argument is a pointer derived from array using the corresponding Get<PrimitiveType>ArrayElements() function. If necessary, this function copies back all changes made to elems to the original array.

通知VM 本地代码不再需要访问elems的函数簇。 elems参数是使用相应的Get <PrimitiveType> ArrayElements()函数从参数array派生的指针。 如有必要,此函数将对elems所做的所有更改复制回原始数组。

The mode argument provides information on how the array buffer should be released. mode has no effect if elems is not a copy of the elements in array. Otherwise, mode has the following impact, as shown in the following table:

mode参数提供有关应如何释放数组缓冲区的信息。 如果elems不是数组array中元素的副本,则mode无效。 否则,mode会产生以下影响,如下表所示:

 

Table 4-10 Primitive Array Release Modes

 

mode

actions

0

copy back the content and free the elems buffer

JNI_COMMIT

copy back the content but do not free the elems buffer

JNI_ABORT

free the buffer without copying back the possible changes

In most cases, programmers pass “0” to the mode argument to ensure consistent behavior for both pinned and copied arrays. The other options give the programmer more control over memory management and should be used with extreme care.

在大多数情况下,程序员将“ 0”传递给mode参数以确保原始的和复制数组的行为一致。 其他选项使程序员可以更好地控制内存管理,因此应格外小心。

The next table describes the specific routines that comprise the family of primitive array disposers. You should make the following substitutions:

下表描述了处置基本数组元素的程序系列。 您应该进行以下替换:

  • Replace Release<PrimitiveType>ArrayElements with one of the actual primitive array disposer routine names from Table 4-11.
  • Replace ArrayType with the corresponding array type.
  • Replace NativeType with the corresponding native type for that routine.

Table 4-11a Release<PrimitiveType>ArrayElements Family of Array Routines

 

Release<PrimitiveType>ArrayElements Routines

Array Type

Native Type

ReleaseBooleanArrayElements()

jbooleanArray

jboolean

ReleaseByteArrayElements()

jbyteArray

jbyte

ReleaseCharArrayElements()

jcharArray

jchar

ReleaseShortArrayElements()

jshortArray

jshort

ReleaseIntArrayElements()

jintArray

jint

ReleaseLongArrayElements()

jlongArray

jlong

ReleaseFloatArrayElements()

jfloatArray

jfloat

ReleaseDoubleArrayElements()

jdoubleArray

jdouble

 

LINKAGE:

Indices in the JNIEnv interface function table.

Table 4-11b Release<PrimitiveType>ArrayElements Family of Array Routines

 

Release<PrimitiveType>ArrayElements Routines

Index

ReleaseBooleanArrayElements()

191

ReleaseByteArrayElements()

192

ReleaseCharArrayElements()

193

ReleaseShortArrayElements()

194

ReleaseIntArrayElements()

195

ReleaseLongArrayElements()

196

ReleaseFloatArrayElements()

197

ReleaseDoubleArrayElements()

198

PARAMETERS:

env: the JNI interface pointer.

array: a Java array object.

elems: a pointer to array elements.

mode: the release mode.

Get<PrimitiveType>ArrayRegion Routines

void Get<PrimitiveType>ArrayRegion(JNIEnv *env, ArrayType array,
jsize start, jsize len, NativeType *buf);

A family of functions that copies a region of a primitive array into a buffer.

将基本数组的一个区域复制到缓冲区中的函数系列。

The following table describes the specific primitive array element accessors. You should do the following substitutions:

  • Replace Get<PrimitiveType>ArrayRegion with one of the actual primitive element accessor routine names from Table 4-12.
  • Replace ArrayType with the corresponding array type.
  • Replace NativeType with the corresponding native type for that routine.

Table 4-12a Get<PrimitiveType>ArrayRegion Family of Array Accessor Routines

 

Get<PrimitiveType>ArrayRegion Routine

Array Type

Native Type

GetBooleanArrayRegion()

jbooleanArray

jboolean

GetByteArrayRegion()

jbyteArray

jbyte

GetCharArrayRegion()

jcharArray

jchar

GetShortArrayRegion()

jshortArray

jhort

GetIntArrayRegion()

jintArray

jint

GetLongArrayRegion()

jlongArray

jlong

GetFloatArrayRegion()

jfloatArray

jloat

GetDoubleArrayRegion()

jdoubleArray

jdouble

LINKAGE:

Indices in the JNIEnv interface function table.

Table 4-12b Get<PrimitiveType>ArrayRegion Family of Array Accessor Routines

 

Get<PrimitiveType>ArrayRegion Routine

Index

GetBooleanArrayRegion()

199

GetByteArrayRegion()

200

GetCharArrayRegion()

201

GetShortArrayRegion()

202

GetIntArrayRegion()

203

GetLongArrayRegion()

204

GetFloatArrayRegion()

205

GetDoubleArrayRegion()

206

PARAMETERS:

env: the JNI interface pointer.

array: a Java array.

start: the starting index.

len: the number of elements to be copied.

buf: the destination buffer.

THROWS:

ArrayIndexOutOfBoundsException: if one of the indexes in the region is not valid.

Set<PrimitiveType>ArrayRegion Routines

void Set<PrimitiveType>ArrayRegion(JNIEnv *env, ArrayType array,
jsize start, jsize len, const NativeType *buf);

A family of functions that copies back a region of a primitive array from a buffer.

从缓冲区复制回基本数组的区域的函数簇。

The following table describes the specific primitive array element accessors. You should make the following replacements:

  • Replace Set<PrimitiveType>ArrayRegion with one of the actual primitive element accessor routine names from the table.
  • Replace ArrayType with the corresponding array type.
  • Replace NativeType with the corresponding native type for that routine.

    Table 4-13a Set<PrimitiveType>ArrayRegion Family of Array Accessor Routines

     

    Set<PrimitiveType>ArrayRegion Routine

    Array Type

    Native Type

    SetBooleanArrayRegion()

    jbooleanArray

    jboolean

    SetByteArrayRegion()

    jbyteArray

    jbyte

    SetCharArrayRegion()

    jcharArray

    jchar

    SetShortArrayRegion()

    jshortArray

    jshort

    SetIntArrayRegion()

    jintArray

    jint

    SetLongArrayRegion()

    jlongArray

    jlong

    SetFloatArrayRegion()

    jfloatArray

    jfloat

    SetDoubleArrayRegion()

    jdoubleArray

    jdouble

LINKAGE:

Indices in the JNIEnv interface function table.

Table 4-13b Set<PrimitiveType>ArrayRegion Family of Array Accessor Routines

 

Set<PrimitiveType>ArrayRegion Routine

Index

SetBooleanArrayRegion()

207

SetByteArrayRegion()

208

SetCharArrayRegion()

209

SetShortArrayRegion()

210

SetIntArrayRegion()

211

SetLongArrayRegion()

212

SetFloatArrayRegion()

213

SetDoubleArrayRegion()

214

PARAMETERS:

env: the JNI interface pointer.

array: a Java array.

start: the starting index.

len: the number of elements to be copied.

buf: the source buffer.

THROWS:

ArrayIndexOutOfBoundsException: if one of the indexes in the region is not valid.

Note

As of JDK/JRE 1.1, programmers can use Get/Release<primitivetype>ArrayElements functions to obtain a pointer to primitive array elements. If the VM supports pinning, the pointer to the original data is returned; otherwise, a copy is made.

New functions introduced as of JDK/JRE 1.3 allow native code to obtain a direct pointer to array elements even if the VM does not support pinning.

从JDK / JRE 1.1开始,程序员可以使用Get / Release <primitivetype> ArrayElements函数获取指向基本类型数组元素的指针。 如果VM支持固定,则返回原始数据的指针;否则将返回拷贝数据。

从JDK / JRE 1.3开始引入的新功能允许本地代码获得指向数组元素的直接指针,即使VM不支持固定也是如此。

GetPrimitiveArrayCritical
ReleasePrimitiveArrayCritical

void * GetPrimitiveArrayCritical(JNIEnv *env, jarray array, jboolean *isCopy);
void ReleasePrimitiveArrayCritical(JNIEnv *env, jarray array, void *carray, jint mode);

The semantics of these two functions are very similar to the existing Get/Release<primitivetype>ArrayElements functions. If possible, the VM returns a pointer to the primitive array; otherwise, a copy is made. However, there are significant restrictions on how these functions can be used.

这两个函数的语义与现有的Get / Release <primitivetype> ArrayElements函数非常相似。如果可能,VM返回指向基元数组的指针;否则,返回的是拷贝。但是,如何使用这些功能存在很大的限制。
 

After calling GetPrimitiveArrayCritical, the native code should not run for an extended period of time before it calls ReleasePrimitiveArrayCritical. We must treat the code inside this pair of functions as running in a "critical region." Inside a critical region, native code must not call other JNI functions, or any system call that may cause the current thread to block and wait for another Java thread. (For example, the current thread must not call read on a stream being written by another Java thread.)

调用GetPrimitiveArrayCritical之后,本地代码在调用ReleasePrimitiveArrayCritical之前不应运行很长时间。我们必须将这对函数中的代码视为在“关键区域”中运行。在关键区域内,本地代码不得调用其他JNI函数或任何可能导致当前线程阻塞并等待另一个Java线程的系统调用。 (例如,当前线程不得在被另一个Java线程正在写入的流上调用read。)
 

These restrictions make it more likely that the native code will obtain an uncopied version of the array, even if the VM does not support pinning. For example, a VM may temporarily disable garbage collection when the native code is holding a pointer to an array obtained via GetPrimitiveArrayCritical.

这些限制使本地代码更有可能获得数组的原始数据指针,即使VM不支持固定也是如此。例如,当本地代码持有通过GetPrimitiveArrayCritical获得的数组的指针时,VM可暂时禁用垃圾收集。

Multiple pairs of GetPrimtiveArrayCritical and ReleasePrimitiveArrayCritical may be nested. For example:

  jint len = (*env)->GetArrayLength(env, arr1);
  jbyte *a1 = (*env)->GetPrimitiveArrayCritical(env, arr1, 0);
  jbyte *a2 = (*env)->GetPrimitiveArrayCritical(env, arr2, 0);
  /* We need to check in case the VM tried to make a copy. */
  if (a1 == NULL || a2 == NULL) {
    ... /* out of memory exception thrown */
  }
  memcpy(a1, a2, len);
  (*env)->ReleasePrimitiveArrayCritical(env, arr2, a2, 0);
  (*env)->ReleasePrimitiveArrayCritical(env, arr1, a1, 0);

Note that GetPrimitiveArrayCritical might still make a copy of the array if the VM internally represents arrays in a different format. Therefore we need to check its return value against NULL for possible out of memory situations.

请注意,如果VM内部以其他格式表示数组,则GetPrimitiveArrayCritical可能仍会拷贝数组。 因此,对于可能的内存不足情况,我们需要检查其返回值是否为NULL。

LINKAGE (GetPrimitiveArrayCritical):

Linkage Index 222 in the JNIEnv interface function table.

LINKAGE (ReleasePrimitiveArrayCritical):

Linkage Index 223 in the JNIEnv interface function table.

SINCE:

JDK/JRE 1.2

 

Registering Native Methods

RegisterNatives

jint RegisterNatives(JNIEnv *env, jclass clazz,const JNINativeMethod *methods, 
jint nMethods);

Registers native methods with the class specified by the clazz argument. The methods parameter specifies an array of JNINativeMethod structures that contain the names, signatures, and function pointers of the native methods. The name and signature fields of the JNINativeMethod structure are pointers to modified UTF-8 strings. The nMethods parameter specifies the number of native methods in the array. The JNINativeMethod structure is defined as follows:

用参数clazz指定的类注册本地方法。 Methods参数指定一个JNINativeMethod结构数组,其中包含本地方法的名称,签名和函数指针。 JNINativeMethod结构的名称和签名字段是指向编辑后的UTF-8字符串的指针。 nMethods参数指定数组中本地方法的数量。 JNINativeMethod结构定义如下:

typedef struct { 
    char *name; 
    char *signature; 
    void *fnPtr; 

} JNINativeMethod; 

The function pointers nominally must have the following signature:

ReturnType (*fnPtr)(JNIEnv *env, jobject objectOrClass, ...);
LINKAGE:

Index 215 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

clazz: a Java class object.

methods: the native methods in the class.

nMethods: the number of native methods in the class.

RETURNS:

Returns “0” on success; returns a negative value on failure.

THROWS:

NoSuchMethodError: if a specified method cannot be found or if the method is not native.

UnregisterNatives

jint UnregisterNatives(JNIEnv *env, jclass clazz);

Unregisters native methods of a class. The class goes back to the state before it was linked or registered with its native method functions.

注销类的本地方法。 该类返回到其本地方法函数进行链接或注册之前的状态。

This function should not be used in normal native code. Instead, it provides special programs a way to reload and relink native libraries.

正常的本机代码中不应使用此函数。 相反,它为特殊程序提供了一种重新加载和重新链接本地库的方法。

LINKAGE:

Index 216 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

clazz: a Java class object.

RETURNS:

Returns “0” on success; returns a negative value on failure.

Monitor Operations

MonitorEnter

jint MonitorEnter(JNIEnv *env, jobject obj);

Enters the monitor associated with the underlying Java object referred to by obj.

进入与obj引用的底层Java对象关联的监视器。

Enters the monitor associated with the object referred to by obj. The obj reference must not be NULL.
进入与obj引用的对象关联的监视器。 obj引用不能为NULL。

Each Java object has a monitor associated with it. If the current thread already owns the monitor associated with obj, it increments a counter in the monitor indicating the number of times this thread has entered the monitor. If the monitor associated with obj is not owned by any thread, the current thread becomes the owner of the monitor, setting the entry count of this monitor to 1. If another thread already owns the monitor associated with obj, the current thread waits until the monitor is released, then tries again to gain ownership.

每个Java对象都有一个与其关联的监视器。如果当前线程已经拥有与obj相关联的监视器,则它将在监视器中增加一个计数器,以指示该线程进入监视器的次数。如果与obj相关联的监视器不属于任何线程,则当前线程将成为该监视器的所有者,并将此监视器的条目计数设置为1。如果另一个线程已经拥有与obj相关联的监视器,则当前线程将等待直到监视器被释放,然后再次尝试获得所有权。

A monitor entered through a MonitorEnter JNI function call cannot be exited using the monitorexit Java virtual machine instruction or a synchronized method return. A MonitorEnter JNI function call and a monitorenter Java virtual machine instruction may race to enter the monitor associated with the same object.

使用monitorexit Java虚拟机指令或返回同步方法无法退出通过MonitorEnter JNI函数调用输入的监视器。 MonitorEnter JNI函数调用和monitorenter Java虚拟机指令可能会争先进入与同一对象关联的监视器。

To avoid deadlocks, a monitor entered through a MonitorEnter JNI function call must be exited using the MonitorExit JNI call, unless the DetachCurrentThread call is used to implicitly release JNI monitors.

为避免死锁,除非使用DetachCurrentThread调用隐式释放JNI监视器,否则必须使用MonitorExit JNI调用退出通过MonitorEnter JNI函数调用输入的监视器。

LINKAGE:

Index 217 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

obj: a normal Java object or class object.

RETURNS:

Returns “0” on success; returns a negative value on failure.

MonitorExit

jint MonitorExit(JNIEnv *env, jobject obj);

The current thread must be the owner of the monitor associated with the underlying Java object referred to by obj. The thread decrements the counter indicating the number of times it has entered this monitor. If the value of the counter becomes zero, the current thread releases the monitor.

当前线程必须是与obj引用的底层Java对象关联的监视器的所有者。 线程递减计数器,以指示其进入此监视器的次数。 如果计数器的值变为零,则当前线程释放监视器。

Native code must not use MonitorExit to exit a monitor entered through a synchronized method or a monitorenter Java virtual machine instruction.

本机代码不得使用MonitorExit退出通过同步方法或monitorenter Java虚拟机指令输入的监视器。

LINKAGE:

Index 218 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

obj: a normal Java object or class object.

RETURNS:

Returns “0” on success; returns a negative value on failure.

EXCEPTIONS:

IllegalMonitorStateException: if the current thread does not own the monitor.

NIO Support

The NIO-related entry points allow native code to access java.nio direct buffers. The contents of a direct buffer can, potentially, reside in native memory outside of the ordinary garbage-collected heap. For information about direct buffers, please see New I/O APIs and the specification of the java.nio.ByteBuffer class.

与NIO相关的入口点允许本地代码访问java.nio直接缓冲区。 直接缓冲区的内容可以驻留在普通垃圾收集堆之外的本地内存中。 有关直接缓冲区的信息,请参见New I / O API和java.nio.ByteBuffer类的规范。

Three new functions introduced in JDK/JRE 1.4 allow JNI code to create, examine, and manipulate direct buffers:

JDK / JRE 1.4中引入的三个新功能允许JNI代码创建,检查和操作直接缓冲区:

Every implementation of the Java virtual machine must support these functions, but not every implementation is required to support JNI access to direct buffers. If a JVM does not support such access then the NewDirectByteBuffer and GetDirectBufferAddress functions must always return NULL, and the GetDirectBufferCapacity function must always return -1. If a JVM does support such access then these three functions must be implemented to return the appropriate values.

Java虚拟机的每个实现都必须支持这些功能,但是并非所有实现都支持JNI访问直接缓冲区。 如果JVM不支持这种访问,则NewDirectByteBuffer和GetDirectBufferAddress函数必须始终返回NULL,而GetDirectBufferCapacity函数必须始终返回-1。 如果JVM支持这种访问,则必须实现这三个函数以返回适当的值。

NewDirectByteBuffer

jobject NewDirectByteBuffer(JNIEnv* env, void* address, jlong capacity);

Allocates and returns a direct java.nio.ByteBuffer referring to the block of memory starting at the memory address address and extending capacity bytes.

分配并返回一个直接的java.nio.ByteBuffer,它引用从内存地址address 开始并扩展capacity 字节的内存块。

Native code that calls this function and returns the resulting byte-buffer object to Java-level code should ensure that the buffer refers to a valid region of memory that is accessible for reading and, if appropriate, writing. An attempt to access an invalid memory location from Java code will either return an arbitrary value, have no visible effect, or cause an unspecified exception to be thrown.

调用此函数并将返回的字节缓冲区对象返回给Java级代码的本地代码应确保该缓冲区引用的内存有效区域可读写。 尝试从Java代码访问无效的内存位置将返回一个任意值,没有可见的效果,或者导致引发未指定的异常。

LINKAGE:

Index 229 in the JNIEnv interface function table.

PARAMETERS:

env: the JNIEnv interface pointer

address: the starting address of the memory region (must not be NULL)

capacity: the size in bytes of the memory region (must be positive)

RETURNS:

Returns a local reference to the newly-instantiated java.nio.ByteBuffer object. Returns NULL if an exception occurs, or if JNI access to direct buffers is not supported by this virtual machine.

返回对新实例化的java.nio.ByteBuffer对象的本地引用。 如果发生异常,或者此虚拟机不支持JNI对直接缓冲区的访问,则返回NULL。

EXCEPTIONS:

OutOfMemoryError: if allocation of the ByteBuffer object fails

SINCE:

JDK/JRE 1.4

GetDirectBufferAddress

void* GetDirectBufferAddress(JNIEnv* env, jobject buf);

Fetches and returns the starting address of the memory region referenced by the given direct java.nio.Buffer.

获取并返回给定直接java.nio.Buffer引用的内存区域的起始地址。

This function allows native code to access the same memory region that is accessible to Java code via the buffer object.

此功能允许本地代码通过缓冲区对象访问Java代码可访问的同一内存区域。

LINKAGE:

Index 230 in the JNIEnv interface function table.

PARAMETERS:

env: the JNIEnv interface pointer

buf: a direct java.nio.Buffer object (must not be NULL)

RETURNS:

Returns the starting address of the memory region referenced by the buffer. Returns NULL if the memory region is undefined, if the given object is not a direct java.nio.Buffer, or if JNI access to direct buffers is not supported by this virtual machine.

返回缓冲区引用的内存区域的起始地址。 如果未定义内存区域,给定对象不是直接java.nio.Buffer或此虚拟机不支持JNI对直接缓冲区的访问,则返回NULL。

SINCE:

JDK/JRE 1.4

GetDirectBufferCapacity

jlong GetDirectBufferCapacity(JNIEnv* env, jobject buf);

Fetches and returns the capacity of the memory region referenced by the given direct java.nio.Buffer. The capacity is the number of elements that the memory region contains.

获取并返回给定直接java.nio.Buffer引用的内存区域的容量。 容量是存储区域包含的元素数。

LINKAGE:

Index 231 in the JNIEnv interface function table.

PARAMETERS:

env: the JNIEnv interface pointer

buf: a direct java.nio.Buffer object (must not be NULL)

RETURNS:

Returns the capacity of the memory region associated with the buffer. Returns -1 if the given object is not a direct java.nio.Buffer, if the object is an unaligned view buffer and the processor architecture does not support unaligned access, or if JNI access to direct buffers is not supported by this virtual machine.

返回与缓冲区关联的内存区域的容量。 如果给定的对象不是直接的java.nio.Buffer,或者该对象是未对齐的视图缓冲区,并且处理器体系结构不支持未对齐的访问,或者此虚拟机不支持对直接缓冲区的JNI访问,则返回-1。

SINCE:

JDK/JRE 1.4

Reflection Support

Programmers can use the JNI to call Java methods or access Java fields if they know the name and type of the methods or fields. The Java Core Reflection API allows programmers to introspect Java classes at runtime. JNI provides a set of conversion functions between field and method IDs used in the JNI to field and method objects used in the Java Core Reflection API.

如果程序员知道方法或字段的名称和类型,则可以使用JNI来调用Java方法或访问Java字段。 Java Core Reflection API允许程序员在运行时内省Java类。 JNI提供了一组在JNI中使用从字段和方法ID到Java Core Reflection API中使用的字段和方法对象之间的转换函数。

FromReflectedMethod

 jmethodID FromReflectedMethod(JNIEnv *env, jobject method);

Converts a java.lang.reflect.Method or java.lang.reflect.Constructor object to a method ID.

将java.lang.reflect.Method或java.lang.reflect.Constructor对象转换为方法ID。

LINKAGE:

Index 7 in the JNIEnv interface function table.

SINCE:

JDK/JRE 1.2

FromReflectedField

jfieldID FromReflectedField(JNIEnv *env, jobject field);

Converts a java.lang.reflect.Field to a field ID.

LINKAGE:

Index 8 in the JNIEnv interface function table.

SINCE:

JDK/JRE 1.2

ToReflectedMethod

jobject ToReflectedMethod(JNIEnv *env, jclass cls,
   jmethodID methodID, jboolean isStatic);

Converts a method ID derived from cls to a java.lang.reflect.Method or java.lang.reflect.Constructor object. isStatic must be set to JNI_TRUE if the method ID refers to a static field, and JNI_FALSE otherwise.

将从cls派生的方法ID转换为java.lang.reflect.Method或java.lang.reflect.Constructor对象。 如果方法ID引用静态字段,则必须将isStatic设置为JNI_TRUE,否则将JNI_FALSE设置为JNI_FALSE。

Throws OutOfMemoryError and returns 0 if fails.
抛出OutOfMemoryError,如果失败则返回0。

LINKAGE:

Index 9 in the JNIEnv interface function table.

SINCE:

JDK/JRE 1.2

ToReflectedField

jobject ToReflectedField(JNIEnv *env, jclass cls,
   jfieldID fieldID, jboolean isStatic);

Converts a field ID derived from cls to a java.lang.reflect.Field object. isStatic must be set to JNI_TRUE if fieldID refers to a static field, and JNI_FALSE otherwise.

将从cls派生的字段ID转换为java.lang.reflect.Field对象。 如果fieldID引用静态字段,则必须将isStatic设置为JNI_TRUE,否则将JNI_FALSE设置为JNI_FALSE。

Throws OutOfMemoryError and returns 0 if fails.
抛出OutOfMemoryError,如果失败则返回0。

LINKAGE:

Index 12 in the JNIEnv interface function table.

SINCE:

JDK/JRE 1.2

Java VM Interface

GetJavaVM

jint GetJavaVM(JNIEnv *env, JavaVM **vm);

Returns the Java VM interface (used in the Invocation API) associated with the current thread. The result is placed at the location pointed to by the second argument, vm.

返回与当前线程关联的Java VM接口(在Invocation API中使用)。 结果放置在第二个参数vm指向的位置。

LINKAGE:

Index 219 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

vm: a pointer to where the result should be placed.

RETURNS:

Returns “0” on success; returns a negative value on failure.

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值