其他分享
首页 > 其他分享> > JNI测试

JNI测试

作者:互联网

JNI测试 

1:生成JNI的基础流程用例

HelloJNI.java代码

 1 public class HelloJNI {  // Save as HelloJNI.java
 2    static {
 3       System.loadLibrary("HelloJNI"); // Load native library hello.dll (Windows) or libhello.so (Unixes)
 4                                    //  at runtime
 5                                    // This library contains a native method called sayHello()
 6    }
 7  
 8    // Declare an instance native method sayHello() which receives no parameter and returns void
 9    private native void sayHello();
10  
11    // Test Driver
12    public static void main(String[] args) {
13       new HelloJNI().sayHello();  // Create an instance and invoke the native method
14    }
15 }

 

javac生成class文件

javac HelloJNI.java

javah生成h文件

javah HelloJNI.java

生成的h文件内容为

 1 /* DO NOT EDIT THIS FILE - it is machine generated */
 2 #include <jni.h>
 3 /* Header for class HelloJNI */
 4 
 5 #ifndef _Included_HelloJNI
 6 #define _Included_HelloJNI
 7 #ifdef __cplusplus
 8 extern "C" {
 9 #endif
10 /*
11  * Class:     HelloJNI
12  * Method:    sayHello
13  * Signature: ()V
14  */
15 JNIEXPORT void JNICALL Java_HelloJNI_sayHello
16   (JNIEnv *, jobject);
17 
18 #ifdef __cplusplus
19 }
20 #endif
21 #endif

 

HelloJNI.c实现c++方法,

1 #include <stdio.h>      // C Standard IO Header
2 #include "HelloJNI.h"   // Generated
3  
4 // Implementation of the native method sayHello()
5 JNIEXPORT void JNICALL Java_HelloJNI_sayHello(JNIEnv *env, jobject thisObj) {
6    printf("Hello World!\n");
7    return;
8 }

 

 使用g++生成libHelloJNI.so

1 g++ --shared HelloJNI.c -o libHelloJNI.so -I/usr/lib/jvm/java-8-openjdk-amd64/include -I/usr/lib/jvm/java-8-openjdk-amd64/include/linux

 

设置java lib查找路径

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/mnt/d/workspace/self/java/jni

 

java调用HelloJNI

java HelloJNI

 

结果如下所示

 

标签:java,void,sayHello,测试,HelloJNI,JNI,include,native
来源: https://www.cnblogs.com/hgwang/p/14542967.html