步骤 1:编写 Java 代码
我们从编写 Java 源代码文件开始,它将声明本机方法(或方法),装入包含本机代码的共享库,然后实际调用本机方法。
我们从编写 Java 源代码文件开始,它将声明本机方法(或方法),装入包含本机代码的共享库,然后实际调用本机方法。
这里是名为JNI_javaCallc_test:
直接使用文本编辑器或在ecilpos中建立工程敲入以下代码:
- package test;
- public class JNI_javaCallc_test {
- //c/c++本地方法
- public native int intMethod(int n);
- public native boolean booleanMethod(boolean bool);
- public native String stringMethod(String text);
- public native int intArrayMethod(int[] intArray);
- //java main方法
- public static void main(String[] args){
- //包含c语言动态库
- System.loadLibrary("test_JNI_javaCallc_test");
- JNI_javaCallc_test sample = new JNI_javaCallc_test();
- int square = sample.intMethod(5);
- boolean bool = sample.booleanMethod(true);
- String text =sample.stringMethod("JAVA");
- int sum = sample.intArrayMethod(new int[] { 1, 1, 2, 3, 5, 8, 13 });
- System.out.println("intMethod: " + square);
- System.out.println("booleanMethod: " + bool);
- System.out.println("stringMethod: " + text);
- System.out.println("intArrayMethod: " + sum);
- }
- }
package test; public class JNI_javaCallc_test { //c/c++本地方法 public native int intMethod(int n); public native boolean booleanMethod(boolean bool); public native String stringMethod(String text); public native int intArrayMethod(int[] intArray); //java main方法 public static void main(String[] args){ //包含c语言动态库 System.loadLibrary("test_JNI_javaCallc_test"); JNI_javaCallc_test sample = new JNI_javaCallc_test(); int square = sample.intMethod(5); boolean bool = sample.booleanMethod(true); String text =sample.stringMethod("JAVA"); int sum = sample.intArrayMethod(new int[] { 1, 1, 2, 3, 5, 8, 13 }); System.out.println("intMethod: " + square); System.out.println("booleanMethod: " + bool); System.out.println("stringMethod: " + text); System.out.println("intArrayMethod: " + sum); } }
这段代码做了些什么?
首先,请注意对 native 关键字的使用,它只能随方法一起使用。
native 关键字告诉 Java 编译器:方法是用 Java 类之外的本机代码实现的,但其声明却在 Java 中。只能在 Java 类中声明本机方法,而不能实现它(但是不能声明为抽象的方法,使用native关键字即可),所以本机方法不能拥有方法主体。
从第 6 行到第 12 行,我们声明了四个 native 方法。
在第 17 行,我们装入了包含这些本机方法的实现的共享库文件。(到步骤 5 时,我们将创建该共享库文件。)
最终,从第 21 行到第 27 行,我们调用了本机方法。
注:这个操作和调用非本机 Java 方法的操作没有差异。
现在,让我们逐行研究一下代码:
从第 6 行到第 12 行,我们声明了四个 native 方法。
在第 17 行,我们装入了包含这些本机方法的实现的共享库文件。(到步骤 5 时,我们将创建该共享库文件。)
最终,从第 21 行到第 27 行,我们调用了本机方法。
注:这个操作和调用非本机 Java 方法的操作没有差异。