Java Native Interface(JNI)从零开始详细教程

简述JNI开发 JNI全称为Java Native Interface,主要用于实现Java和C/C++的通信。 阅读详情
AI摘要

本文详细介绍了如何使用Java Native Interface (JNI) 进行Java与C/C++代码的交互,包括基本类型的处理、字符串与数组的转换、对象变量访问及方法回调等核心技术要点。

====================================================================================
首先声明:这边文章是我翻译的文章(看了很多关于JNI的介绍,只有这篇个人认为最好,因此忍不住想要翻译给国内的各位),请勿随意转载,尊重文章原作者。
文章原始链接:https://www3.ntu.edu.sg/home/ehchua/programming/java/JavaNativeInterface.html
这是南洋理工大学的在线学习note,有兴趣的同学可以直接看原文。如果你对E文比较头疼的话,可以直接看下面我翻译的,我会尽量使用平实的语言去翻译这篇文章,另外本人水平有限,如有翻译不当之处还请各位赐教。===================================================================================

引言

有的时候我们需要使用本地代码(C/C++)来克服Java中的内存管理和性能问题,Java通过JNI机制来支持内地代码的使用。
想要比较好地理解JNI是比较难的,因为它包含了两种语言和运行时机制。
在继续之前,我应该假设你具备以下知识点和技能:
1. java
2. C/C++和gcc编译器
3. 对于windows而言,熟悉Gygwin或者MinGW
4. 对于IDE而言,熟悉Eclipse C/C++ Development Tool (CDT)

开始

使用C来实现JNI

步骤1,编写一个使用C实现函数的java类,HelloJNI.java:

public class HelloJNI {
   static {
      System.loadLibrary("hello"); // Load native library at runtime
                                   // hello.dll (Windows) or libhello.so (Unixes)
   }

   // Declare a native method sayHello() that receives nothing and returns void
   private native void sayHello();

   // Test Driver
   public static void main(String[] args) {
      new HelloJNI().sayHello();  // invoke the native method
   }
}

上面代码的静态代码块在这个类被类加载器加载的时候调用了System.loadLibrary()方法来加载一个native库“hello”(这个库中实现了sayHello函数)。这个库在windows品台上对应了“hello.dll”,而在类UNIX平台上对应了“libhello.so”。这个库应该包含在Java的库路径(使用java.library.path系统变量表示)上,否则这个上面的程序会抛出UnsatisfiedLinkError错误。你应该使用VM的参数-Djava.library.path=path_to_lib来指定包含native库的路径。
接下来,我们使用native关键字将sayHello()方法声明为本地实例方法,这就很明显地告诉JVM:这个方法实现在另外一个语言中(C/C++),请去那里寻找他的实现。注意,一个native方法不包含方法体,只有声明。上面代码中的main方法实例化了一个HelloJJNI类的实例,然后调用了本地方法sayHello()。
下面,我们编译HelloJNI.java成HelloJNI.class

javac HelloJNI.java

接下来,我们利用上面生成的class文件生成用于编写C/C++代码的头文件,使用jdk中的javah工具完成:

javah HelloJNI

上面的命令执行完之后生成了HelloJNI.h:

/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class HelloJNI */

#ifndef _Included_HelloJNI
#define _Included_HelloJNI
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     HelloJNI
 * Method:    sayHello
 * Signature: ()V
 */
JNIEXPORT void JNICALL Java_HelloJNI_sayHello(JNIEnv *, jobject);

#ifdef __cplusplus
}
#endif
#endif

我们看到,上面的头文件中生成了一个Java_HelloJNI_sayHello的C函数:

JNIEXPORT void JNICALL Java_HelloJNI_sayHello(JNIEnv *, jobject);

将java的native方法转换成C函数声明的规则是这样的:Java_{package_and_classname}_{function_name}(JNI arguments)。包名中的点换成单下划线。需要说明的是生成函数中的两个参数:
1. JNIEnv *:这是一个指向JNI运行环境的指针,后面我们会看到,我们通过这个指针访问JNI函数
2. jobject:这里指代java中的this对象
下面我们给出的例子中没有使用上面的两个参数,不过后面我们的例子会使用的。到目前为止,你可以先忽略JNIEXPORT和JNICALL这两个玩意。
上面头文件中有一个extern “C”,同时上面还有C++的条件编译语句,这么一来大家就明白了,这里的函数声明是要告诉C++编译器:这个函数是C函数,请使用C函数的签名协议规则去编译!因为我们知道C++的函数签名协议规则和C的是不一样的,因为C++支持重写和重载等面向对象的函数语法。
接下来,我们给出C语言的实现,以实现上面的函数:
C语言实现:

#include <jni.h>
#include <stdio.h>
#include "HelloJNI.h"

// Implementation of native method sayHello() of HelloJNI class
JNIEXPORT void JNICALL Java_HelloJNI_sayHello(JNIEnv *env, jobject thisObj) {
   printf("Hello World!\n");
   return;
}

将上面的代码保存为HelloJNI.c。jni.h头文件在 “\include” 和 “\include\win32”目录下,这里的JAVA_HOME是指你的JDK安装目录。
这段C代码的作用很简单,就是在终端上打印Hello Word!这句话。
下面我们编译这段代码,使用GCC编译器:
对于windows上的MinGW:

> set JAVA_HOME=C:\Program Files\Java\jdk1.7.0_{xx}
      // Define and Set environment variable JAVA_HOME to JDK installed directory
      // I recommend that you set JAVA_HOME permanently, via "Control Panel" ⇒ "System" ⇒ "Environment Variables"
> echo %JAVA_HOME%
      // In Windows, you can refer a environment variable by adding % prefix and suffix 
> gcc -Wl,--add-stdcall-alias -I"%JAVA_HOME%\include" -I"%JAVA_HOME%\include\win32" -shared -o hello.dll HelloJNI.c
      // Compile HellJNI.c into shared library hello.dll

也可以分步编译:

// Compile-only with -c flag. Output is HElloJNI.o
> gcc -c -I"%JAVA_HOME%\include" -I"%JAVA_HOME%\include\win32" HelloJNI.c

// Link into shared library "hello.dll"
> gcc -Wl,--add-stdcall-alias -shared -o hello.dll HelloJNI.o

下面,我们使用nm命令来查看生成hello.dll中的函数:

> nm hello.dll | grep say
624011d8 T _Java_HelloJNI_sayHello@8

对于windows上的Cygwin:
首先,你需要讲__int64定义成“long long”类型,通过-D _int64=”long long选项实现。
对于gcc-3,请包含选项-nmo -cygwin来编译dll库,这些库是不依赖于Cygwin dll的。

> gcc-3 -D __int64="long long" -mno-cygwin -Wl,--add-stdcall-alias 
  -I"<JAVA_HOME>\include" -I"<JAVA_HOME>\include\win32" -shared -o hello.dll HelloJNI.c

对于gcc-4,我目前还没有找到正确的编译选项。
==================================这部分是笔者添加的==================================
原文中只给出了windows平台上编译方法,下面我给出Linux等类UNIX上编译方法:

gcc -fPIC --shared HelloJNI.c -o libhello.so -I /usr/lib/jvm/java-7-openjdk-amd64/include/

上面的命令编译生成一个libhello.so共享库在当前目录下
==================================这部分是笔者添加的==================================
接下来,让我们运行一下上面的代码吧:

> java HelloJNI
or
> java -Djava.library.path=. HelloJNI

有的时候,你可能需要使用-Djava.library.path来指定加载库的位置,因为可能报出java.lang.UnsatisfiedLinkError错误.
==================================这部分是笔者添加的==================================
我们首先使用nm命令(关于nm请自行Google或者man)查看libhello.so中都有那些函数:
这里写图片描述
可以看到我们的sayHello函数已经在这个里面,这说明我们编译的基本没有问题。
下面,我给出在我电脑上运行的效果(原文作者没有给出):
首先我们执行java HelloJNI,看看能不能运行:
这里写图片描述
果然,出现了UnsatisfiedLinkError错误,原因是VM去标准路径下查找这个库,发现找不到,然后就挂了。因此我们还是需要使用-Djava.library.path来明确告诉VM我们的库在哪里(当然,你也可以将你编译出来的库放到系统标准路径中,比如/usr/lib目录下):
这里写图片描述
现在OK了,因为我们明确告诉VM,我们的libhello.so就在当前目录下,不用傻傻地去系统中找啦!!
==================================这部分是笔者添加的==================================

使用C/C++混合实现JNI

第一步:编写一个使用本地代码的java类:HelloJNICpp.java

public class HelloJNICpp {
   static {
      System.loadLibrary("hello"); // hello.dll (Windows) or libhello.so (Unixes)
   }

   // Native method declaration
   private native void sayHello();

   // Test Driver
   public static void main(String[] args) {
      new HelloJNICpp().sayHello();  // Invoke native method
   }
}

同样地,我们使用javac来编译这个代码:

> javac HelloJNICpp.java

步骤2:生成C/C++的头文件

> javah HelloJNICpp

上面命令会生成一个HelloJNICpp.h的文件,并且这个文件中声明了这个本地函数:

JNIEXPORT void JNICALL Java_HelloJNICpp_sayHello(JNIEnv *, jobject);

步骤3:C/C++编码实现,HelloJNICppImpl.h, HelloJNICppImpl.cpp, 和 HelloJNICpp.c
这里,我们使用C++来实现真正的函数(”HelloJNICppImpl.h” 和 “HelloJNICppImpl.cpp”),而使用C来和java进行交互。(译者注:这样就可以把JNI的代码逻辑和我们真正的业务逻辑分离开了!)
C++头文件:”HelloJNICppImpl.h”

#ifndef _HELLO_JNI_CPP_IMPL_H
#define _HELLO_JNI_CPP_IMPL_H

#ifdef __cplusplus
        extern "C" {
#endif
        void sayHello ();
#ifdef __cplusplus
        }
#endif

#endif

C++的代码实现:”HelloJNICppImpl.cpp”

#include "HelloJNICppImpl.h"
#include  <iostream>

using namespace std;

void sayHello () {
    cout << "Hello World from C++!" << endl;
    return;
}

C代码实现和Java的交互:”HelloJNICpp.c”

#include <jni.h>
#include "HelloJNICpp.h"
#include "HelloJNICppImpl.h"

JNIEXPORT void JNICALL Java_HelloJNICpp_sayHello (JNIEnv *env, jobject thisObj) {
    sayHello();  // invoke C++ function
    return;
}

讲上面的代码编译成一个共享库(在windows上是hello.dll)。
使用windows上的MinGW GCC:

> set JAVA_HOME=C:\Program Files\Java\jdk1.7.0_{xx}
> g++ -Wl,--add-stdcall-alias -I"%JAVA_HOME%\include" -I"%JAVA_HOME%\include\win32" 
      -shared -o hello.dll HelloJNICpp.c HelloJNICppImpl.cpp

步骤4:运行java代码

> java HelloJNICpp
or
> java -Djava.library.path=. HelloJNICpp

java package中的JNI

在真正的产品化中,所有的java类都是有自己的包的,而不是一个默认的没有名字的包。下面我们说明一下java中的package怎么在JNI中使用。
步骤1:使用JNI的程序, myjni\HelloJNI.java

package myjni; // 多了包名定义

public class HelloJNI {
   static {
      System.loadLibrary("hello"); // hello.dll (Windows) or libhello.so (Unixes)
   }
   // A native method that receives nothing and returns void
   private native void sayHello();

   public static void main(String[] args) {
      new HelloJNI().sayHello();  // invoke the native method
   }
}

上面的这个类应该放在myjni目录下。然后我们编译这个代码:

// change directory to package base directory
> javac myjni\HelloJNI.java

步骤2:生成C/C++头文件
如果你的java代码是放在一个包中的,那么你需要使用完全限定名称来生成C/C++头文件的。你可能会需要使用-classpath选项来指定JNI程序的classpath路径,并且可能会使用-d选项来指定生成头文件的目标文件夹。

> javah --help
......

// Change directory to package base directory
> javah -d include myini.HelloJNI

在上面的例子中,我们选择将生层的头文件放在include目录下,因此,我们输出的就是:”include\myjni_HelloJNI.h”.这个头文件声明了这样的本地函数:

JNIEXPORT void JNICALL Java_myjni_HelloJNI_sayHello(JNIEnv *, jobject);

我们看到,和上面的例子相比,这里的名字规则是这样的:Java__methodName,同时,点号换成单下划线。
步骤3:C代码实现:HelloJNI.c

#include <jni.h>
#include <stdio.h>
#include "include\myjni_HelloJNI.h"

JNIEXPORT void JNICALL Java_myjni_HelloJNI_sayHello(JNIEnv *env, jobject thisObj) {
   printf("Hello World!\n");
   return;
}

编译C代码:

> gcc -Wl,--add-stdcall-alias -I<JAVA_HOME>\include -I<JAVA_HOME>\include\win32 -shared -o hello.dll HelloJNI.c

运行代码:

> java myjni.HelloJNI

在Eclipse中开发JNI

这部分作者写的非常易懂,由于个人时间问题,就不翻译了,大家看看就明白(其实就是一些Eclipse的设置问题,没有什么复杂的),或者百度看国内的也行。(抱歉了!)
原文链接:https://www3.ntu.edu.sg/home/ehchua/programming/java/JavaNativeInterface.html

JNI基础知识

上面我们简单演示了怎么使用JNI,现在我们来系统梳理一下JNI中涉及的基本知识。
JNI定义了以下数据类型,这些类型和Java中的数据类型是一致的:
1. Java原始类型:jint, jbyte, jshort, jlong, jfloat, jdouble, jchar, jboolean这些分别对应这java的int, byte, short, long, float, double, char and boolean。
2. Java引用类型:jobject用来指代java.lang.Object,除此之外,还定义了以下子类型:
a. jclass for java.lang.Class.
b. jstring for java.lang.String.
c. jthrowable for java.lang.Throwable.
d. jarray对java的array。java的array是一个指向8个基本类型array的引用类型。于是,JNI中就有8个基本类型的array:jintArray, jbyteArray, jshortArray, jlongArray, jfloatArray, jdoubleArray, jcharArray 和 jbooleanArray,还有一个就是指向Object的jobjectarray。
Native函数会接受上面类型的参数,并且也会返回上面类型的返回值。然而,本地函数(C/C++)是需要按照它们自己的方式处理类型的(比如C中的string,就是char *)。因此,需要在JNI类型和本地类型之间进行转换。通常来讲,本地函数需要:
1. 加收JNI类型的参数(从java代码中传来)
2. 对于JNI类型参数,需要讲这些数据转换或者拷贝成本地数据类型,比如讲jstring转成char *, jintArray转成C的int[]。需要注意的是,原始的JNI类型,诸如jint,jdouble之类的不用进行转换,可以直接使用,参与计算。
3. 进行数据操作,以本地的方式
4. 创建一个JNI的返回类型,然后讲结果数据拷贝到这个JNI数据中
5. returnJNI类型数据
这其中最麻烦的事莫过于在JNI类型(如jstring, jobject, jintArray, jobjectArray)和本地类型(如C-string, int[])之间进行转换这件事情了。不过所幸的是,JNI环境已经为我们定义了很多的接口函数来做这种烦人的转换。(译者注:这里就需要使用上面我们提到的JNIEnv*那个参数了!)

在Java和Native代码之间传递参数和返回值

传递基本类型

传递java的基本类型是非常简单而直接的,一个jxxx之类的类型已经定义在本地系统中了,比如:jint, jbyte, jshort, jlong, jfloat, jdouble, jchar 和 jboolean分别对应java的int, byte, short, long, float, double, char 和 boolean基本类型。
Java JNI 程序:TestJNIPrimitive.java

public class TestJNIPrimitive {
   static {
      System.loadLibrary("myjni"); // myjni.dll (Windows) or libmyjni.so (Unixes)
   }

   // Declare a native method average() that receives two ints and return a double containing the average
   private native double average(int n1, int n2);

   // Test Driver
   public static void main(String args[]) {
      System.out.println("In Java, the average is " + new TestJNIPrimitive().average(3, 2));
   }
}

这个JNI程序加载了myjni.dll(windows)库或者libmyjni.so(类UNIX)库。并且声明了一个native方法,这个方法接受两个int类型的参数,并且返回一个double类型的返回值,这个值是两个int型数的平均值。mian方法调用了average函数。
下面,我们将上面的java代码编译成TestJNIPrimitive.class,进而生成C/C++头文件TestJNIPrimitive.h:

> javac TestJNIPrimitive.java
> javah TestJNIPrimitive       // Output is TestJNIPrimitive.h

C实现:TestJNIPrimitive.c

头文件TestJNIPrimitive.h中包含了一个函数声明:

JNIEXPORT jdouble JNICALL Java_TestJNIPrimitive_average(JNIEnv *, jobject, jint, jint);

可以看到,这里的jint和jdouble分别表示java中的int和double。
jni.h(windows上是win32/jni_mh.h)头文件包含了这些数据类型的定义,同时多了一个jsize的定义:

// In "win\jni_mh.h" - machine header which is machine dependent
typedef long            jint;
typedef __int64         jlong;
typedef signed char     jbyte;

// In "jni.h"
typedef unsigned char   jboolean;
typedef unsigned short  jchar;
typedef short           jshort;
typedef float           jfloat;
typedef double          jdouble;
typedef jint            jsize;

有趣的是,jint对应到C的long类型(至少是32bit的),而不是C的int类型(至少是16bit的)。于是,在C代码中要使用jint而不是int是很重要的。同时,CygWin不支持__int64类型。
TestJNIPrimitive.c的实现如下:

#include <jni.h>
#include <stdio.h>
#include "TestJNIPrimitive.h"

JNIEXPORT jdouble JNICALL Java_TestJNIPrimitive_average
          (JNIEnv *env, jobject thisObj, jint n1, jint n2) {
   jdouble result;
   printf("In C, the numbers are %d and %d\n", n1, n2);
   result = ((jdouble)n1 + n2) / 2.0;
   // jint is mapped to int, jdouble is mapped to double
   return result;
}

然后,我们编译代码成一个共享库:

// MinGW GCC under Windows
> set JAVA_HOME={jdk-installed-directory}
> gcc -Wl,--add-stdcall-alias -I"%JAVA_HOME%\include" -I"%JAVA_HOME%\include\win32" -shared -o myjni.dll TestJNIPrimitive.c

最后,我们运行这个java代码:

> java TestJNIPrimitive

C++实现 TestJNIPrimitive.cpp

代码如下:

#include <jni.h>
#include <iostream>
#include "TestJNIPrimitive.h"
using namespace std;

JNIEXPORT jdouble JNICALL Java_TestJNIPrimitive_average
          (JNIEnv *env, jobject obj, jint n1, jint n2) {
   jdouble result;
   cout << "In C++, the numbers are " << n1 << " and " << n2 << endl;
   result = ((jdouble)n1 + n2) / 2.0;
   // jint is mapped to int, jdouble is mapped to double
   return result;
}

使用g++来编译上面的代码:

// MinGW GCC under Windows
> g++ -Wl,--add-stdcall-alias -I"%JAVA_HOME%\include" -I"%JAVA_HOME%\include\win32" -shared -o myjni.dll TestJNIPrimitive.cpp

传递字符串

Java JNI 程序:TestJNIString.java

public class TestJNIString {
   static {
      System.loadLibrary("myjni"); // myjni.dll (Windows) or libmyjni.so (Unixes)
   }
   // Native method that receives a Java String and return a Java String
   private native String sayHello(String msg);

   public static void main(String args[]) {
      String result = new TestJNIString().sayHello("Hello from Java");
      System.out.println("In Java, the returned string is: " + result);
   }
}

上面的代码声明了一个native函数sayHello,这个函数接受一个java的String,然后返回一个Java string,main方法调用了sayHello函数。
然后,我们编译上面的代码,并且生成C/C++的头文件:

> javac TestJNIString.java
> javah TestJNIString

C代码实现:TestJNIString.c

上面的头文件TestJNIString.h声明了这样的一个函数:

JNIEXPORT jstring JNICALL Java_TestJNIString_sayHello(JNIEnv *, jobject, jstring);

JNI定义了jstring类型应对java的String类型。上面声明中的最后一个参数jstring就是来自Java代码中的String参数,同时,返回值也是一个jstring类型。
传递一个字符串比传递基本类型要复杂的多,因为java的String是一个对象,而C的string是一个NULL结尾的char数组。因此,我们需要将Java的String对象转换成C的字符串表示形式:char *。
前面我们提到,JNI环境指针JNIEnv *已经为我们定义了非常丰富的接口函数用来处理数据的转换:
1. 调用const char* GetStringUTFChars(JNIEnv*, jstring, jboolean*)来将JNI的jstring转换成C的char *
2. 调用jstring NewStringUTF(JNIEnv*, char*)来将C的char *转换成JNI的jstring
因此我们的C程序基本过程如下:
1. 使用GetStringUTFChars()函数来将jstring转换成char *
2. 然后进行需要的数据处理
3. 使用NewStringUTF()函数来将char *转换成jstring,并且返回

#include <jni.h>
#include <stdio.h>
#include "TestJNIString.h"

JNIEXPORT jstring JNICALL Java_TestJNIString_sayHello(JNIEnv *env, jobject thisObj, jstring inJNIStr) {
   // Step 1: Convert the JNI String (jstring) into C-String (char*)
   const char *inCStr = (*env)->GetStringUTFChars(env, inJNIStr, NULL);
   if (NULL == inCSt) return NULL;

   // Step 2: Perform its intended operations
   printf("In C, the received string is: %s\n", inCStr);
   (*env)->ReleaseStringUTFChars(env, inJNIStr, inCStr);  // release resources

   // Prompt user for a C-string
   char outCStr[128];
   printf("Enter a String: ");
   scanf("%s", outCStr);    // not more than 127 characters

   // Step 3: Convert the C-string (char*) into JNI String (jstring) and return
   return (*env)->NewStringUTF(env, outCStr);
}

将上面的代码编译成共享库:

// MinGW GCC under Windows
> gcc -Wl,--add-stdcall-alias -I"<JAVA_HOME>\include" -I"<JAVA_HOME>\include\win32" -shared -o myjni.dll TestJNIString.c

最后,运行代码:

> java TestJNIString
In C, the received string is: Hello from Java
Enter a String: test
In Java, the returned string is: test

JNI中的string转换函数

上面我们展示了两个函数,现在我们全面梳理下JNI为我们提供的函数。JNI支持Unicode(16bit字符)和UTF-8(使用1~3字节的编码)转化。一般而言,我们应该在C/C++中使用UTF-8的编码方式。
JNI系统提供了如下关于字符串处理的函数(一共两组,UTF8和Unicode):

// UTF-8 String (encoded to 1-3 byte, backward compatible with 7-bit ASCII)
// Can be mapped to null-terminated char-array C-string
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.
void ReleaseStringUTFChars(JNIEnv *env, jstring string, const char *utf);
   // Informs the VM that the native code no longer needs access to utf.
jstring NewStringUTF(JNIEnv *env, const char *bytes);
   // Constructs a new java.lang.String object from an array of characters in modified UTF-8 encoding.
jsize GetStringUTFLength(JNIEnv *env, jstring string);
   // Returns the length in bytes of the modified UTF-8 representation of a string.
void GetStringUTFRegion(JNIEnv *env, jstring str, jsize start, jsize length, 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.

// Unicode Strings (16-bit character)
const jchar * GetStringChars(JNIEnv *env, jstring string, jboolean *isCopy);
   // Returns a pointer to the array of Unicode characters
void ReleaseStringChars(JNIEnv *env, jstring string, const jchar *chars);
   // Informs the VM that the native code no longer needs access to chars.
jstring NewString(JNIEnv *env, const jchar *unicodeChars, jsize length);
   // Constructs a new java.lang.String object from an array of Unicode characters.
jsize GetStringLength(JNIEnv *env, jstring string);
   // Returns the length (the count of Unicode characters) of a Java string.
void GetStringRegion(JNIEnv *env, jstring str, jsize start, jsize length, jchar *buf);
   // Copies len number of Unicode characters beginning at offset start to the given buffer buf

GetStringUTFChars()函数可以将jstring转成char *,这个函数会返回NULL,如果系统的内容分配失败的话。因此,好的做法是检查这个函数的返回是不是NULL。第三个参数是isCopy,这个参数是一个in-out参数,传进去的是一个指针,函数结束的时候指针的内容会被修改。如果内容是JNI_TRUE的话,那么代表返回的数据是jstring数据的一个拷贝,反之,如果是JNI_FALSE的话,就说明返回的字符串就是直接指向那个String对象实例的。在这种情况下,本地代码不应该随意修改string中的内容,因为修改会代码Java中的修改。JNI系统会尽量保证返回的是直接引用,如果不能的话,那就返回一个拷贝。通常,我们很少关心修改这些string ,因此我们这里一般传递NULL给isCopy参数。
必须要注意的是,当你不在需要GetStringUTFChars返回的字符串的时候,一定记得调用ReleaseStringUTFChars()函数来将内存资源释放!否则会内存泄露!并且上层java中的GC也不能进行!
另外,在GetStringUTFChars和ReleaseStringUTFChars不能block!
NewStringUTF()函数可以从char *字符串得到jstring。
关于更详细的描述,请参考Java Native Interface Specification:http://docs.oracle.com/javase/7/docs/technotes/guides/jni/index.html

C++实现:TestJNIString.cpp

#include <jni.h>
#include <iostream>
#include <string>
#include "TestJNIString.h"
using namespace std;

JNIEXPORT jstring JNICALL Java_TestJNIString_sayHello(JNIEnv *env, jobject thisObj, jstring inJNIStr) {
   // Step 1: Convert the JNI String (jstring) into C-String (char*)
   const char *inCStr = env->GetStringUTFChars(inJNIStr, NULL);
   if (NULL == inCStr) return NULL;

   // Step 2: Perform its intended operations
   cout << "In C++, the received string is: " << inCStr << endl;
   env->ReleaseStringUTFChars(inJNIStr, inCStr);  // release resources

   // Prompt user for a C++ string
   string outCppStr;
   cout << "Enter a String: ";
   cin >> outCppStr;

   // Step 3: Convert the C++ string to C-string, then to JNI String (jstring) and return
   return env->NewStringUTF(outCppStr.c_str());
}

使用g++编译上面的代码:

// MinGW GCC under Windows
> g++ -Wl,--add-stdcall-alias -I"<JAVA_HOME>\include" -I"<JAVA_HOME>\include\win32" -shared -o myjni.dll TestJNIString.cpp

需要注意的是,在C++中,本地string类的函数调用语法不一样。在C++中,我们使用env->来调用,而不是(env*)->。同时,在C++函数中不需要JNIEnv*这个参数了。

传递基本类型的数组

JNI 代码:TestJNIPrimitiveArray.java

public class TestJNIPrimitiveArray {
   static {
      System.loadLibrary("myjni"); // myjni.dll (Windows) or libmyjni.so (Unixes)
   }

   // Declare a native method sumAndAverage() that receives an int[] and
   //  return a double[2] array with [0] as sum and [1] as average
   private native double[] sumAndAverage(int[] numbers);

   // Test Driver
   public static void main(String args[]) {
      int[] numbers = {22, 33, 33};
      double[] results = new TestJNIPrimitiveArray().sumAndAverage(numbers);
      System.out.println("In Java, the sum is " + results[0]);
      System.out.println("In Java, the average is " + results[1]);
   }
}

C语言实现:TestJNIPrimitiveArray.c

头文件TestJNIPrimitiveArray.h包含以下函数声明:

JNIEXPORT jdoubleArray JNICALL Java_TestJNIPrimitiveArray_average (JNIEnv *, jobject, jintArray);

在Java中,array是指一种类型,类似于类。一共有9种java的array,8个基本类型的array和一个object的array。JNI针对java的基本类型都定义了相应的array:jintArray, jbyteArray, jshortArray, jlongArray, jfloatArray, jdoubleArray, jcharArray, jbooleanArray,并且也有面向object的jobjectArray。
同样地,你需要在JNI array和Native array之间进行转换,JNI系统已经为我们提供了一系列的接口函数:
1. 使用jint* GetIntArrayElements(JNIEnv *env, jintArray a, jboolean *iscopy)将jintarray转换成C的jint[]
2. 使用jintArray NewIntArray(JNIEnv *env, jsize len)函数来分配一个len字节大小的空间,然后再使用void SetIntArrayRegion(JNIEnv *env, jintArray a, jsize start, jsize len, const jint *buf)函数讲jint[]中的数据拷贝到jintArray中去。
一共有8对类似上面的函数,分别对应java的8个基本数据类型。
因此,native程序需要:
1. 接受来自java的JNI array,然后转换成本地array
2. 进行需要的数据操作
3. 将需要返回的数据转换成jni的array,然后返回
下面是C代码实现的TestJNIPrimitiveArray.c:

#include <jni.h>
#include <stdio.h>
#include "TestJNIPrimitiveArray.h"

JNIEXPORT jdoubleArray JNICALL Java_TestJNIPrimitiveArray_sumAndAverage
          (JNIEnv *env, jobject thisObj, jintArray inJNIArray) {
   // Step 1: Convert the incoming JNI jintarray to C's jint[]
   jint *inCArray = (*env)->GetIntArrayElements(env, inJNIArray, NULL);
   if (NULL == inCArray) return NULL;
   jsize length = (*env)->GetArrayLength(env, inJNIArray);

   // Step 2: Perform its intended operations
   jint sum = 0;
   int i;
   for (i = 0; i < length; i++) {
      sum += inCArray[i];
   }
   jdouble average = (jdouble)sum / length;
   (*env)->ReleaseIntArrayElements(env, inJNIArray, inCArray, 0); // release resources

   jdouble outCArray[] = {sum, average};

   // Step 3: Convert the C's Native jdouble[] to JNI jdoublearray, and return
   jdoubleArray outJNIArray = (*env)->NewDoubleArray(env, 2);  // allocate
   if (NULL == outJNIArray) return NULL;
   (*env)->SetDoubleArrayRegion(env, outJNIArray, 0 , 2, outCArray);  // copy
   return outJNIArray;
}

JNI基本类型的array函数

JNI基本类型的array(jintArray, jbyteArray, jshortArray, jlongArray, jfloatArray, jdoubleArray, jcharArray 和 jbooleanArray)函数如下:

// ArrayType: jintArray, jbyteArray, jshortArray, jlongArray, jfloatArray, jdoubleArray, jcharArray, jbooleanArray
// PrimitiveType: int, byte, short, long, float, double, char, boolean
// NativeType: jint, jbyte, jshort, jlong, jfloat, jdouble, jchar, jboolean
NativeType * Get<PrimitiveType>ArrayElements(JNIEnv *env, ArrayType array, jboolean *isCopy);
void Release<PrimitiveType>ArrayElements(JNIEnv *env, ArrayType array, NativeType *elems, jint mode);
void Get<PrimitiveType>ArrayRegion(JNIEnv *env, ArrayType array, jsize start, jsize length, NativeType *buffer);
void Set<PrimitiveType>ArrayRegion(JNIEnv *env, ArrayType array, jsize start, jsize length, const NativeType *buffer);
ArrayType New<PrimitiveType>Array(JNIEnv *env, jsize length);
void * GetPrimitiveArrayCritical(JNIEnv *env, jarray array, jboolean *isCopy);
void ReleasePrimitiveArrayCritical(JNIEnv *env, jarray array, void *carray, jint mode);

同样地,在get函数和release函数之间也不能always block。

访问Java对象变量和回调Java方法

访问Java对象实例的变量

JNI程序:TestJNIInstanceVariable.java

public class TestJNIInstanceVariable {
   static {
      System.loadLibrary("myjni"); // myjni.dll (Windows) or libmyjni.so (Unixes)
   }

   // Instance variables
   private int number = 88;
   private String message = "Hello from Java";

   // Declare a native method that modifies the instance variables
   private native void modifyInstanceVariable();

   // Test Driver   
   public static void main(String args[]) {
      TestJNIInstanceVariable test = new TestJNIInstanceVariable();
      test.modifyInstanceVariable();
      System.out.println("In Java, int is " + test.number);
      System.out.println("In Java, String is " + test.message);
   }
}

这个类包含了两个private实例变量,一个int,一个String对象。然后我们在main中调用本地函数modifyInstanceVariable来修改这两个变量。
C代码实现:TestJNIInstanceVariable.c

#include <jni.h>
#include <stdio.h>
#include "TestJNIInstanceVariable.h"

JNIEXPORT void JNICALL Java_TestJNIInstanceVariable_modifyInstanceVariable
          (JNIEnv *env, jobject thisObj) {
   // Get a reference to this object's class
   jclass thisClass = (*env)->GetObjectClass(env, thisObj);

   // int
   // Get the Field ID of the instance variables "number"
   jfieldID fidNumber = (*env)->GetFieldID(env, thisClass, "number", "I");
   if (NULL == fidNumber) return;

   // Get the int given the Field ID
   jint number = (*env)->GetIntField(env, thisObj, fidNumber);
   printf("In C, the int is %d\n", number);

   // Change the variable
   number = 99;
   (*env)->SetIntField(env, thisObj, fidNumber, number);

   // Get the Field ID of the instance variables "message"
   jfieldID fidMessage = (*env)->GetFieldID(env, thisClass, "message", "Ljava/lang/String;");
   if (NULL == fidMessage) return;

   // String
   // Get the object given the Field ID
   jstring message = (*env)->GetObjectField(env, thisObj, fidMessage);

   // Create a C-string with the JNI String
   const char *cStr = (*env)->GetStringUTFChars(env, message, NULL);
   if (NULL == cStr) return;

   printf("In C, the string is %s\n", cStr);
   (*env)->ReleaseStringUTFChars(env, message, cStr);

   // Create a new C-string and assign to the JNI string
   message = (*env)->NewStringUTF(env, "Hello from C");
   if (NULL == message) return;

   // modify the instance variables
   (*env)->SetObjectField(env, thisObj, fidMessage, message);
}

为了访问对象中的变量,我们需要:
1. 调用GetObjectClass()获得目标对象的类引用
2. 从上面获得的类引用中获得Field ID来访问变量,你需要提供这个变量的名字,变量的描述符(也称为签名)。对于java类而言,描述符是这样的形式:“Lfully-qualified-name;”(注意最后有一个英文半角分号),其中的包名点号换成斜杠(/),比如java的Stirng类的描述符就是“Ljava/lang/String;”。对于基本类型而言,I代表int,B代表byte,S代表short,J代表long,F代表float,D代表double,C代表char,Z代表boolean。对于array而言,使用左中括号”[“来表示,比如“[Ljava/lang/Object;”表示Object的array,“[I”表示int型的array。
3. 基于上面获得的Field ID,使用GetObjectField() 或者 Get_primitive-type_Field()函数来从中解析出我们想要的数据
4. 使用SetObjectField() 或者 Set_primitive-type_Field()函数来修改变量
JNI中用来访问实例变量的函数有:

jclass GetObjectClass(JNIEnv *env, jobject obj);
   // Returns the class of an object.

jfieldID GetFieldID(JNIEnv *env, jclass cls, const char *name, const char *sig);
  // Returns the field ID for an instance variable of a class.

NativeType Get<type>Field(JNIEnv *env, jobject obj, jfieldID fieldID);
void Set<type>Field(JNIEnv *env, jobject obj, jfieldID fieldID, NativeType value);
  // Get/Set the value of an instance variable of an object
  // <type> includes each of the eight primitive types plus Object.

访问类中的static变量

访问类中的static变量类似于上面访问普通的实例变量,只是我们这里使用的函数是GetStaticFieldID(), Get|SetStaticObjectField(), Get|SetStatic_Primitive-type_Field()。
JNI 程序: TestJNIStaticVariable.java

public class TestJNIStaticVariable {
   static {
      System.loadLibrary("myjni"); // nyjni.dll (Windows) or libmyjni.so (Unixes)
   }

   // Static variables
   private static double number = 55.66;

   // Declare a native method that modifies the static variable
   private native void modifyStaticVariable();

   // Test Driver
   public static void main(String args[]) {
      TestJNIStaticVariable test = new TestJNIStaticVariable();
      test.modifyStaticVariable();
      System.out.println("In Java, the double is " + number);
   }
}

C语言实现:C Implementation - TestJNIStaticVariable.c

#include <jni.h>
#include <stdio.h>
#include "TestJNIStaticVariable.h"

JNIEXPORT void JNICALL Java_TestJNIStaticVariable_modifyStaticVariable
          (JNIEnv *env, jobject thisObj) {
   // Get a reference to this object's class
   jclass cls = (*env)->GetObjectClass(env, thisObj);

   // Read the int static variable and modify its value
   jfieldID fidNumber = (*env)->GetStaticFieldID(env, cls, "number", "D");
   if (NULL == fidNumber) return;
   jdouble number = (*env)->GetStaticDoubleField(env, cls, fidNumber);
   printf("In C, the double is %f\n", number);
   number = 77.88;
   (*env)->SetStaticDoubleField(env, cls, fidNumber, number);
}

JNI中用来访问类中的static变量的函数如下:

jfieldID GetStaticFieldID(JNIEnv *env, jclass cls, const char *name, const char *sig);
  // Returns the field ID for a static variable of a class.

NativeType GetStatic<type>Field(JNIEnv *env, jclass clazz, jfieldID fieldID);
void SetStatic<type>Field(JNIEnv *env, jclass clazz, jfieldID fieldID, NativeType value);
  // Get/Set the value of a static variable of a class.
  // <type> includes each of the eight primitive types plus Object.

回调实例的普通和static方法

你可以在native代码中回调java中的普通或者static的方法。下面是实例:
JNI程序:TestJNICallBackMethod.java

public class TestJNICallBackMethod {
   static {
      System.loadLibrary("myjni"); // myjni.dll (Windows) or libmyjni.so (Unixes)
   }

   // Declare a native method that calls back the Java methods below
   private native void nativeMethod();

   // To be called back by the native code
   private void callback() {
      System.out.println("In Java");
   }

   private void callback(String message) {
      System.out.println("In Java with " + message);
   }

   private double callbackAverage(int n1, int n2) {
      return ((double)n1 + n2) / 2.0;
   }

   // Static method to be called back
   private static String callbackStatic() {
      return "From static Java method";
   }

   // Test Driver 
   public static void main(String args[]) {
      new TestJNICallBackMethod().nativeMethod();
   }
}

这个类中声明了一个native函数nativeMethod(),并且在main方法中调用了这个函数。nativeMethod()这个函数会回调这个类中定义的各种方法。
C语言实现:TestJNICallBackMethod.c

#include <jni.h>
#include <stdio.h>
#include "TestJNICallBackMethod.h"

JNIEXPORT void JNICALL Java_TestJNICallBackMethod_nativeMethod
          (JNIEnv *env, jobject thisObj) {

   // Get a class reference for this object
   jclass thisClass = (*env)->GetObjectClass(env, thisObj);

   // Get the Method ID for method "callback", which takes no arg and return void
   jmethodID midCallBack = (*env)->GetMethodID(env, thisClass, "callback", "()V");
   if (NULL == midCallBack) return;
   printf("In C, call back Java's callback()\n");
   // Call back the method (which returns void), baed on the Method ID
   (*env)->CallVoidMethod(env, thisObj, midCallBack);

   jmethodID midCallBackStr = (*env)->GetMethodID(env, thisClass,
                               "callback", "(Ljava/lang/String;)V");
   if (NULL == midCallBackStr) return;
   printf("In C, call back Java's called(String)\n");
   jstring message = (*env)->NewStringUTF(env, "Hello from C");
   (*env)->CallVoidMethod(env, thisObj, midCallBackStr, message);

   jmethodID midCallBackAverage = (*env)->GetMethodID(env, thisClass,
                                  "callbackAverage", "(II)D");
   if (NULL == midCallBackAverage) return;
   jdouble average = (*env)->CallDoubleMethod(env, thisObj, midCallBackAverage, 2, 3);
   printf("In C, the average is %f\n", average);

   jmethodID midCallBackStatic = (*env)->GetStaticMethodID(env, thisClass,
                                 "callbackStatic", "()Ljava/lang/String;");
   if (NULL == midCallBackStatic) return;
   jstring resultJNIStr = (*env)->CallStaticObjectMethod(env, thisClass, midCallBackStatic);
   const char *resultCStr = (*env)->GetStringUTFChars(env, resultJNIStr, NULL);
   if (NULL == resultCStr) return;
   printf("In C, the returned string is %s\n", resultCStr);
   (*env)->ReleaseStringUTFChars(env, resultJNIStr, resultCStr);
}

为了能够回调实例中的方法,我们需要:
1. 通过GetObjectClass()函数获得这个实例的类对象
2. 从上面获得类对象中,调用GetMethodID()函数来获得Method ID,Method ID表示了实例中的某个方法的抽象。你需要提供这个方法的名字和签名信息,签名规则和变量类似。签名的格式是这样的:(parameters)return-type。如果我们实在觉得jni的签名不好记忆的话,我们可以是用JDK为我们提供的工具javap来获得某个class类中的所有方法的签名,使用-s选项表示打印签名,-p表示显示private成员:

> javap --help
> javap -s -p TestJNICallBackMethod
  .......
  private void callback();
    Signature: ()V

  private void callback(java.lang.String);
    Signature: (Ljava/lang/String;)V

  private double callbackAverage(int, int);
    Signature: (II)D

  private static java.lang.String callbackStatic();
    Signature: ()Ljava/lang/String;
  .......

从上面的输出我们可以清楚地看到类中每一个方法的签名。
3. 基于上面我们获得的Method ID,我们可以调用_Primitive-type_Method() 或者 CallVoidMethod() 或者 CallObjectMethod()来调用这个方法。如果某个方法需要参数的话,就在后面跟上参数即可。
4. 如果想要调用一个static方法的话,使用GetMethodID(), CallStatic_Primitive-type_Method(), CallStaticVoidMethod() 或者 CallStaticObjectMethod()。
JNI中用来回调实例和static方法的所有函数(两类,普通的和static的):

jmethodID GetMethodID(JNIEnv *env, jclass cls, const char *name, const char *sig);
   // Returns the method ID for an instance method of a class or interface.

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);
   // Invoke an instance method of the object.
   // The <type> includes each of the eight primitive and Object.

jmethodID GetStaticMethodID(JNIEnv *env, jclass cls, const char *name, const char *sig);
   // Returns the method ID for an instance method of a class or interface.

NativeType CallStatic<type>Method(JNIEnv *env, jclass clazz, jmethodID methodID, ...);
NativeType CallStatic<type>MethodA(JNIEnv *env, jclass clazz, jmethodID methodID, const jvalue *args);
NativeType CallStatic<type>MethodV(JNIEnv *env, jclass clazz, jmethodID methodID, va_list args);
   // Invoke an instance method of the object.
   // The <type> includes each of the eight primitive and Object.

回调复写的父类实例方法

JNI提供了一系列的形如 CallNonvirtual_Type_Method()之类的函数来调用父类实例的方法:
1. 首先获得Method ID,使用GetMethodID()
2. 基于上获得的Method ID,通过调用 CallNonvirtual_Type_Method()函数来调用相应的方法,并且在参数中给出object,父类和参数列表。
JNI中用来访问父类方法的函数:

NativeType CallNonvirtual<type>Method(JNIEnv *env, jobject obj, jclass cls, jmethodID methodID, ...);
NativeType CallNonvirtual<type>MethodA(JNIEnv *env, jobject obj, jclass cls, jmethodID methodID, const jvalue *args);
NativeType CallNonvirtual<type>MethodV(JNIEnv *env, jobject obj, jclass cls, jmethodID methodID, va_list args);

创建Object和Object arrays

你可以在native代码中构造jobject和jobjectarray,通过调用NewObject() 和 newObjectArray()函数,然后讲它们返回给java代码。

回调Java构造器来创建一个新的java对象

回调一个构造器和回调其他的方法是类似的,首先通过init作为方法名,V作为返回值来获得Method ID,然后通过NewObject()函数来构建一个java类对象。
JNI程序:TestJavaConstructor.java

public class TestJNIConstructor {
   static {
      System.loadLibrary("myjni"); // myjni.dll (Windows) or libmyjni.so (Unixes)
   }

   // Native method that calls back the constructor and return the constructed object.
   // Return an Integer object with the given int.
   private native Integer getIntegerObject(int number);

   public static void main(String args[]) {
      TestJNIConstructor obj = new TestJNIConstructor();
      System.out.println("In Java, the number is :" + obj.getIntegerObject(9999));
   }
}

这个类声明了一个getIntegerObject的native方法,这个方法接受一个int的数据,然后在native代码中创建一个Integer类型的对象,其中的值就是这个值。
C代码实现:TestJavaConstructor.c

#include <jni.h>
#include <stdio.h>
#include "TestJNIConstructor.h"

JNIEXPORT jobject JNICALL Java_TestJNIConstructor_getIntegerObject
          (JNIEnv *env, jobject thisObj, jint number) {
   // Get a class reference for java.lang.Integer
   jclass cls = (*env)->FindClass(env, "java/lang/Integer");

   // Get the Method ID of the constructor which takes an int
   jmethodID midInit = (*env)->GetMethodID(env, cls, "<init>", "(I)V");
   if (NULL == midInit) return NULL;
   // Call back constructor to allocate a new instance, with an int argument
   jobject newObj = (*env)->NewObject(env, cls, midInit, number);

   // Try runnning the toString() on this newly create object
   jmethodID midToString = (*env)->GetMethodID(env, cls, "toString", "()Ljava/lang/String;");
   if (NULL == midToString) return NULL;
   jstring resultStr = (*env)->CallObjectMethod(env, newObj, midToString);
   const char *resultCStr = (*env)->GetStringUTFChars(env, resultStr, NULL);
   printf("In C: the number is %s\n", resultCStr);

   return newObj;
}

JNI中用于创建对象(jobject)的函数有:

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

jobject NewObject(JNIEnv *env, jclass cls, jmethodID methodID, ...);
jobject NewObjectA(JNIEnv *env, jclass cls, jmethodID methodID, const jvalue *args);
jobject NewObjectV(JNIEnv *env, jclass cls, jmethodID methodID, va_list args);
   // Constructs a new Java object. The method ID indicates which constructor method to invoke

jobject AllocObject(JNIEnv *env, jclass cls);
  // Allocates a new Java object without invoking any of the constructors for the object.

对象(object)的array

JNI程序:TestJNIObjectArray.java

import java.util.ArrayList;

public class TestJNIObjectArray {
   static {
      System.loadLibrary("myjni"); // myjni.dll (Windows) or libmyjni.so (Unixes)
   }
   // Native method that receives an Integer[] and
   //  returns a Double[2] with [0] as sum and [1] as average
   private native Double[] sumAndAverage(Integer[] numbers);

   public static void main(String args[]) {
      Integer[] numbers = {11, 22, 32};  // auto-box
      Double[] results = new TestJNIObjectArray().sumAndAverage(numbers);
      System.out.println("In Java, the sum is " + results[0]);  // auto-unbox
      System.out.println("In Java, the average is " + results[1]);
   }
}

为了简单起见,这个类声明了一个native方法,这个方法接受一个Integer类型的array,然后在本地代码中计算这个array中的数的和与平均数,然后讲这两个数以Double array的形式返回。
C代码实现:TestJNIObjectArray.c

#include <jni.h>
#include <stdio.h>
#include "TestJNIObjectArray.h"

JNIEXPORT jobjectArray JNICALL Java_TestJNIObjectArray_sumAndAverage
          (JNIEnv *env, jobject thisObj, jobjectArray inJNIArray) {
   // Get a class reference for java.lang.Integer
   jclass classInteger = (*env)->FindClass(env, "java/lang/Integer");
   // Use Integer.intValue() to retrieve the int
   jmethodID midIntValue = (*env)->GetMethodID(env, classInteger, "intValue", "()I");
   if (NULL == midIntValue) return NULL;

   // Get the value of each Integer object in the array
   jsize length = (*env)->GetArrayLength(env, inJNIArray);
   jint sum = 0;
   int i;
   for (i = 0; i < length; i++) {
      jobject objInteger = (*env)->GetObjectArrayElement(env, inJNIArray, i);
      if (NULL == objInteger) return NULL;
      jint value = (*env)->CallIntMethod(env, objInteger, midIntValue);
      sum += value;
   }
   double average = (double)sum / length;
   printf("In C, the sum is %d\n", sum);
   printf("In C, the average is %f\n", average);

   // Get a class reference for java.lang.Double
   jclass classDouble = (*env)->FindClass(env, "java/lang/Double");

   // Allocate a jobjectArray of 2 java.lang.Double
   jobjectArray outJNIArray = (*env)->NewObjectArray(env, 2, classDouble, NULL);

   // Construct 2 Double objects by calling the constructor
   jmethodID midDoubleInit = (*env)->GetMethodID(env, classDouble, "<init>", "(D)V");
   if (NULL == midDoubleInit) return NULL;
   jobject objSum = (*env)->NewObject(env, classDouble, midDoubleInit, (double)sum);
   jobject objAve = (*env)->NewObject(env, classDouble, midDoubleInit, average);
   // Set to the jobjectArray
   (*env)->SetObjectArrayElement(env, outJNIArray, 0, objSum);
   (*env)->SetObjectArrayElement(env, outJNIArray, 1, objAve);

   return outJNIArray;
}

不像基本数据类型的array那样,你需要使用Get|SetObjectArrayElement()函数来处理每一个元素。
JNI提供了创建对象array(jobjectArray)的函数如下:

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.

jobject GetObjectArrayElement(JNIEnv *env, jobjectArray array, jsize index);
   // Returns an element of an Object array.

void SetObjectArrayElement(JNIEnv *env, jobjectArray array, jsize index, jobject value);
   // Sets an element of an Object array.

本地和全局引用

管理引用是编写高效程序的关键。比如,我们会在本地代码中经常使用FindClass(), GetMethodID(), GetFieldID()来会的一个jclass,jmethodID和jfieldID。其实这些变量应该只是在第一次的时候获取,之后直接使用就可以了,而不用每次都去获取一遍,这样可以提高程序执行效率。
JNI讲本地代码中的对象引用分为了两种类型: 本地和全局引用:
1. 本地引用是在本地代码中创建的,并且当函数退出或者返回的时候就被free了。它的有效范围只是这个native函数的内部。你也可以调用DeleteLocalRef()来显式地将某个本地引用作废,这样可以让垃圾回收时能够将这部分回收。作为参数传递到本地函数中的对象引用是本地引用,所有的从JNI函数返回的java对象(jobject)都是本地引用。
2. 全局引用会保留直到程序员调用DeleteGlobalRef()手动free掉他们,你可以使用NewGlobalRef()函数从本地引用创建一个全局引用。
下面我们给出一个例子。

public class TestJNIReference {
   static {
      System.loadLibrary("myjni"); // myjni.dll (Windows) or libmyjni.so (Unixes)
   }

   // A native method that returns a java.lang.Integer with the given int.
   private native Integer getIntegerObject(int number);

   // Another native method that also returns a java.lang.Integer with the given int.
   private native Integer anotherGetIntegerObject(int number);

   public static void main(String args[]) {
      TestJNIReference test = new TestJNIReference();
      System.out.println(test.getIntegerObject(1));
      System.out.println(test.getIntegerObject(2));
      System.out.println(test.anotherGetIntegerObject(11));
      System.out.println(test.anotherGetIntegerObject(12));
      System.out.println(test.getIntegerObject(3));
      System.out.println(test.anotherGetIntegerObject(13));
   }
}

上面的JNI程序声明了两个native函数,这两个都创建并且返回java.lang.Integer对象。在C代码实现中,我们需要获得java.lang.Integer的类引用,然后我们从中找到构造器的method ID,然后调用构造器。然而,我们希望,将我们获得的class引用和Method ID缓存起来,这样我们下次在使用的时候就不用再次去获取了。
下面是我们的C代码,我们希望这样可以OK(然而事实是不行!!!):

#include <jni.h>
#include <stdio.h>
#include "TestJNIReference.h"

// Global Reference to the Java class "java.lang.Integer"
static jclass classInteger;
static jmethodID midIntegerInit;

jobject getInteger(JNIEnv *env, jobject thisObj, jint number) {

   // Get a class reference for java.lang.Integer if missing
   if (NULL == classInteger) {
      printf("Find java.lang.Integer\n");
      classInteger = (*env)->FindClass(env, "java/lang/Integer");
   }
   if (NULL == classInteger) return NULL;

   // Get the Method ID of the Integer's constructor if missing
   if (NULL == midIntegerInit) {
      printf("Get Method ID for java.lang.Integer's constructor\n");
      midIntegerInit = (*env)->GetMethodID(env, classInteger, "<init>", "(I)V");
   }
   if (NULL == midIntegerInit) return NULL;

   // Call back constructor to allocate a new instance, with an int argument
   jobject newObj = (*env)->NewObject(env, classInteger, midIntegerInit, number);
   printf("In C, constructed java.lang.Integer with number %d\n", number);
   return newObj;
}

JNIEXPORT jobject JNICALL Java_TestJNIReference_getIntegerObject
          (JNIEnv *env, jobject thisObj, jint number) {
   return getInteger(env, thisObj, number);
}

JNIEXPORT jobject JNICALL Java_TestJNIReference_anotherGetIntegerObject
          (JNIEnv *env, jobject thisObj, jint number) {
   return getInteger(env, thisObj, number);
}

在上面的程序中,我们调用FindClass()获得了java.lang.Integer类引用,然后把它保存在一个全局静态的变量中。然而,在第二次调用中这个引用却无效了(并不是NULL)。这是因为FindClass()返回的是本地类引用,一旦当getInteger函数返回的时候,这个局部引用就失效了。
为了解决这个问题,我们需要从局部引用中创建一个全局引用,然后再赋值给全局static变量:

// Get a class reference for java.lang.Integer if missing
if (NULL == classInteger) {
   printf("Find java.lang.Integer\n");
   // FindClass returns a local reference
   jclass classIntegerLocal = (*env)->FindClass(env, "java/lang/Integer");
   // Create a global reference from the local reference
   classInteger = (*env)->NewGlobalRef(env, classIntegerLocal);
   // No longer need the local reference, free it!
   (*env)->DeleteLocalRef(env, classIntegerLocal);
}

需要注意的是,jmethodID和jfieldID并不是jobject,因此他们不能创建一个全局引用!!

java在线观看(jav在线网站) java在线网站给大家展示6个java在线网站)。后面还有java在线API,各种java在线在线api地址。 java在线观看1、LintCode Java学习爱好者的福音,和LeetCode类似,也是一个刷题的OJ网站,提供闯关式的阶梯训练以及国内外知名大厂的笔试面试真题。它不仅有算法题、数据库题、Java题目可以刷,还有Java和Sql的教程的手把手教程,一遍做题一边学习加深印象,非常地贴心,不过网站内容更适合Java学习爱好者。 阅读详情

相关推荐

【Java】JNI(Java Native Interface)指南与Hello World

【Java】JNI(Java Native Interface)指南与Hello World

LifeIsGood 1015

Java JNI(Java Native Interface)介绍

众所周知,Java 的主要优势之一是它的可移植性,这意味着一旦我们编写并且编译了代码,这个过程的结果就是不依赖于平台的字节码。它可以像我们预期的那样运行在任何能够运行 Java 虚拟机的机器或设备上。 但是,有时我们确实需要使用一些为某些特定架构而进行本地编译的原生代码。例如: 需要对硬件执行某些操作 对性能要求非常苛刻 想要重用的现有库,而不是用 Java 重写它。 为了实现这一点,JDK 在我们的 JVM 中运行的字节码和原生代码(通常用 C 或 C++ 编写)之间搭建了一座桥梁。

天寒寒的博客 1万+

java视频种子(超多30G)

全是学习的视频,2010传智播客struts2.1.8视频教程,张孝祥Java基础加强,还有面试题

简析java JNI技术

JNI是Java Native Interface的缩写,通过使用 Java本地接口书写程序,可以确保代码在不同的平台上方便移植。从Java1.1开始,JNI标准成为java平台的一部分,它允许Java代码和其他语言写的代码进行交互。本地代码与 Java 虚拟机之间是通过 JNI 函数实现相互操作的。JNI 函数通过接口指针来获得,本地方法将 JNI 接口指针当作参数来接受。

w2393040183的专栏 1741

一文了解ECU软件刷写的2种方法:Bootloader刷写和调试器刷写

分为刷写前、刷写中和刷写后三个阶段,如下示意:下面我们来详细了解一下Bootloader收到外部请求后开始刷写的三个阶段1)刷写前进行刷写的准备,一是确保刷写阶段总线通信的稳定性,二是避免刷写阶段出现非预期的故障,三是读取车辆数据供刷写前的一些检查等,如下所示:首先进行会话控制,通过功能寻址方式进入扩展会话模式,为后面的信息访问及其他指令做准备;然后检查刷写的前提条件,通过物理寻址方式发送历程控制请求。比如车确实处于静止状态,供电电压稳定等条件下才允许刷写;

menghuyouyou的博客 5787

【MFRC522】STM32与MFRC522的SPI通信优化及常见问题解析

本文深入解析了STM32与MFRC522进行SPI通信的优化方法与常见问题。从基础的硬件连接到SPI时序优化,再到关键的寄存器配置(如RFCfgReg设为0x4F以提升读卡稳定性),文章提供了详细的调试技巧和实战排坑指南,帮助开发者实现稳定高效的IC读卡应用。

yhn45678901的博客 841

一篇文章教你完全掌握jni技术

jni全称java native interface,我把它分为三部分,java代表java语言,native代表当前程序运行的本地环境,一般指windows/linux,而这些操作系统都是通过C/C++实现的,所以native通常也指C/C++语言,interface代表java跟native两者之间的通信接口,jni可以实现java和C/C++通信。它是java生态的特征,所以定义在jdk标准当中。

chuyouyinghe的专栏 7301

雷达气象学(8)——反射率因子图实战(强对流预警篇)

本文聚焦雷达反射率因子图在强对流预警中的实战应用,深入解析了柱状回波、有界弱回波区(BWER)、三体散射(TBSS)等关键回波结构特征,这些是识别超级单体风暴和大冰雹的核心“身份证”。文章强调从静态识别转向动态追踪与多源数据综合研判的思维转变,并提供了系统的实战分析流程与常见误区避坑指南,旨在提升对强对流天气的短临预警能力。

weixin_29213827的博客 486

【Android】通过JNI封装C++并自动化打包SDK

【Android】通过JNI封装C++并自动化打包SDK从JNI的资料说起资料搜集功能快捷键合理的创建标题,有助于目录的生成如何改变文本的样式插入链接与图片如何插入一段漂亮的代码片生成一个适合你的列表创建一个表格设定内容居中、居左、居右SmartyPants创建一个自定义列表如何创建一个注脚注释也是必不可少的KaTeX数学公式新的甘特图功能,丰富你的文章UML 图表FLowchart流程图导出与导入导出导入 从JNI的资料说起 你好! 这是你第一次使用 Markdown编辑器 所展示的欢迎页。如果你想学习如

Kindle君的博客 1101

一体化伺服电机与施耐德PLC TM241CEC24T在Canopen协议下的应用

一.硬件组成 软件组成:施耐德SoMachineV4.3二.○1.打开SoMachineV4.3,点击“新建项目”○2.点击“空白项目”○3.项目命名○4.点击“创建项目” 三. 点击“Logic Builder” 四. ○1.右击项目”PMM_CANOPEN_ST”添加设备○2.点击”LogicController”选择PLC型号TM241CEC24T/U○3.点击“添加设备” 五. ○1.右击CAN_1,添加设备○2.选择“CANopen Perfomance”○3.点击“添加设备”

m0_46512607的博客 2521

史上最全的Logisim存储系统实验教程(基于华中科技大学计算机组成原理实验)内赋源码下载

本博客是最全的最好的解释的华中科技大学计算机组成实验存储系统实验,本博客给出了电路实现,也给出了使用电路的原因有利于新手学习十分详细。并且内赋源码下载。

qq_62325622的博客 2万+

JNI 记

Java Native Interface(JNI)从零开始详细教程 ==================================================================================== 首先声明:文章非原创,看了很多关于JNI的介绍,只有这篇个人认为最好,并且附加本人探究过程中的一些见解。文...

weixin_33971977的博客 145

已过tiktok校招客户端,面经分享

面试的话, 一天面完3面, 效率很高, 三天之后就发了offer 字节邮件里面也说了不能泄露面试题, 那我就把我秋招参与美团,字节,腾讯,阿里面试被问到的全部问题总结着写出来了, 这其实是我每一轮面试完之后我都会总结哪里答对了, 哪里没有答对, 总结了一大堆问题出来. 答案未必正确, 我只是给自己写了个简单的一句话概括, 可能不够完善, 建议看官自行回答一下这些问题 二本非科班, 暑假在字节实习过, 不过不是tiktok部门, 因此秋招就没啥时间准备面试了, 只投了几个大厂, 顺便也在字节跨部门转正,

a1472750149的博客 1308

什么是Java Native Interface(JNI)?

Java Native Interface(JNI)是 Java 编程语言提供的一种机制,它允许 Java 代码与用其他编程语言(如 C、C++)编写的代码进行交互。性能优化:当 Java 应用中某些关键代码片段对性能要求极高,而 Java 本身的执行效率无法满足需求时,可以使用 JNI 调用用 C 或 C++ 编写的高效代码,因为这些语言在底层操作、内存管理等方面往往能实现更高效的执行。利用现有库。

candy的博客 2128

迅投miniQMT量化交易之【网格交易】的实现(25)——写在最后

和大家一起分享如何使用miniQMT实现我们自己的网格交易系统。如果您对量化交易感兴趣,欢迎一起交流。

tzzqn2008的专栏 829

医学图像处理实战:利用OpenSlide解析病理SVS切片的完整解决方案

本文介绍了使用openslide处理病理SVS切片的完整流程,从基础安装到科研应用。主要内容包括:1)SVS切片特点及openslide工具简介;2)环境配置与软件安装;3)基础操作:读取切片、查看信息、可视化不同层级图像;4)进阶操作:坐标裁剪与批量处理;5)科研方向拓展:结合AI模型进行病理分割分类、量化分析及可视化报告。教程提供了完整的代码示例,帮助毕业设计学生快速掌握病理图像分析的核心技能。

m0_71589036的博客 312

学习JNI (Java Native Interface)

JNI 是 Java 平台提供的一套标准,它允许 Java 代码与其他语言(主要是 C 和 C++)编写的本地代码进行交互。注意函数名 `Java_com_example_NativeDemo_sayHello`,它遵循特定的命名规则,将包名、类名和方法名用下划线连接起来。工具(或者更现代的方法,如 Android Studio 的 Gradle 插件会自动处理)根据包含。这些方法只有方法签名,没有方法体。方法实现对应的 C/C++ 函数。这个头文件包含了本地方法对应的 C/C++ 函数签名。

qq_46279058的博客 1245

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

Java Programming Tutorial Java Native Interface (JNI)

https://www3.ntu.edu.sg/home/ehchua/programming/java/JavaNativeInterface.html Java Programming Tutorial Java Native Interface (JNI) 1.Introduction At times, it is necessary to use native (non-Ja...

han_han_1的专栏 2285

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

JNI(JAVA NATIVE INTERFACE) 指南

JNI使用指南

你是不是傻的java大坑 1037

最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版

Part-E1-SDIO-Specification-Ver4.00-Final-120220.pdf:最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版,包括SDIO 接口的外设,SDIO 接口官方协议等。

JNI之一:什么是JNI (Java Native Interface)

JNI,即Java本地接口 (Java Native Interface),它是连接Java代码和本地代码之间的桥梁,其中,本地代码可以是C,C++,Fortran等语言编写的。JNI允许我们在Java代码中调用本地代码,也允许本地代码调用Java代码。 我们都知道,在Java中存在本地方法(native method),这种方法用native关键字进行修饰。本地方法底层是用C/C++语言实现的。调用本地方法和调用普通的Java方法的语法一样。 Java代码会被编译成平台无关的字节码,而用C/C++编写的.

qq_29328443的博客 2343

JNI(java-native-interface)以及查看jni源码实现

想阅读java源码离不开对native关键字的认识。 java中带有native关键字的方法为外部方法,不由java代码实现,多由c或c++实现。 源码中的native方法多定义在源码包中的include文件夹内的jni.h头文件中,用C-Free等编译器可以打开查看。 JNI是Java Native Interface的缩写,通过使用 Java本地接口书写程序,可以确保代码在不同的平台上方便移植...

m0_37932390的博客 2078

Java本地接口(Java Native Interface,JNI)讲解

Java本地接口(Java Native Interface,JNI)是一个编程框架,允许Java代码与其他语言写的代码,特别是C和C++,进行交互。这个功能使得Java程序能够调用系统级别的库和那些已经用这些语言实现的库。JNI主要用于两个方面:一是调用C或C++代码,二是被C或C++代码调用。这种能力扩展了Java的使用范围,允许它执行一些在纯Java环境中无法完成的任务,如访问低级系统功能、使用现有的库等。

www_tlj的专栏 1892

JNI(Java Native Interface)入门篇

文章目录前言一、JNI是什么?二、环境准备三、操作过程1. Java声明native方法2. 编译生成 class 文件3. 编译生成 .h 文件4. 手动编写 c 文件5. 编译生成 .o 文件6. 编译生成 dll 文件总结 前言 提示:这里可以添加本文要记录的大概内容: 例如:随着人工智能的不断发展,机器学习这门技术也越来越重要,很多人都开启了学习机器学习,本文就介绍了机器学习的基础内容。 一、JNI是什么? 百度百科: JNI 是Java Native Interface的缩写,通过使用 Ja

weixin_42132143的博客 1656

Java Native Interface (JNI) 简介

是 Java 提供的一种接口,用于允许 Java 应用程序与本地(Native)代码进行交互。通过 JNI,Java 代码可以调用 C/C++ 等其他语言编写的库,反之亦然。JNI 的主要用途包括:与底层系统库交互、调用高性能本地代码、或使用 Java 不能直接访问的硬件设备。问题:JNI 的常见问题与挑战内存管理问题:问题:Java 使用自动垃圾回收,而 C/C++ 代码需要手动管理内存。这可能会导致内存泄漏、指针错误或空指针访问等问题。共性规律:涉及不同语言的互操作时,内存管理往往是最大的挑战。

goTsHgo的博客 1279
上一篇: Heap Sort堆排序
下一篇: Debian Linux包管理机制
createchance
博客等级 码龄15年 156粉丝 90原创
评论 12
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值