java通过jni调用c++

时间:2022-08-10 20:20:58

创建java文件:HelloNative.java


public class HelloNative {
    public native void sayHello();

    /**
     * @param args
     */
    public static void main(String[] args) {
        System.loadLibrary("hello");
        HelloNative tNative = new HelloNative();
        tNative.sayHello();
    }
}

javac HelloNative.java生成HelloNative.class

javah -jni HelloNative 生成HelloNative.h

HelloNative.h内容:

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

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

#ifdef __cplusplus
}
#endif
#endif

创建HelloNative.cpp文件,实现JNIEXPORT void JNICALL Java_HelloNative_sayHello  (JNIEnv *, jobject);方法

#include <iostream>
#include "HelloNative.h"
JNIEXPORT void JNICALL Java_HelloNative_sayHello(JNIEnv *, jobject) {

    std::cout << "Hello! I am JNI!" << std::endl;
}

编译动态库:

g++ -I /usr/lib/jvm/java-7-openjdk-amd64/include/linux -I /usr/lib/jvm/java-7-openjdk-amd64/include/ -fPIC  -shared -o libhello.so HelloNative.cpp

生成libhello.so动态库

运行:java HelloNative

出现:Hello! I am JNI!