下面是在Java 8中使用JNI调用C++的DLL的步骤清单:
- 编写C++代码,创建动态链接库(DLL):
#include <jni.h>
#include <iostream>
#include "org_ming_jni_MyNativeImplementation.h" // com_example_MyClass.h 是通过 javah 自动生成的头文件JNIEXPORT void JNICALL Java_org_ming_jni_MyNativeImplementation_nativeMethod(JNIEnv *env, jobject obj) {std::cout << "Hello from C++!" << std::endl;
}
- 编译C++代码生成共享库DLL文件:
g++ -shared -o sample.dll -I"%JAVA_HOME%\include" -I"%JAVA_HOME%\include\win32" sample.cpp
g++ -shared cpplib.cpp -o cpplib.dll -I"D:\Program\Java\jdk-1.8\include" -I"D:\Program\Java\jdk-1.8\include\win32"
确保将%JAVA_HOME%
替换为您的Java安装路径。
- 创建Java类,并声明native方法:
package org.ming.jni;public class MyNativeImplementation implements MyNativeInterface {static {System.loadLibrary("cpplib");}public native void nativeMethod();
}
package org.ming.jni;public interface MyNativeInterface {void nativeMethod();
}
package org.ming;import org.ming.jni.MyNativeImplementation;
import org.ming.jni.MyNativeInterface;public class Main {public static void main(String[] args) {MyNativeInterface nativeInterface = new MyNativeImplementation();nativeInterface.nativeMethod();}}
- 生成C++头文件:
javac MyClass.java
javah -jni com.example.MyClass
javah -classpath D:\workspace\java_workspace\TestHttp\target\classes org.ming.jni.MyNativeImplementation
这将生成名为com_example_MyClass.h
的头文件。
- 使用Java代码调用native方法:
// Main.javapackage com.example;public class Main {public static void main(String[] args) {MyClass myClass = new MyClass();myClass.nativeMethod();}
}
确保在运行Java代码之前,将生成的DLL文件放在Java库路径或在运行时指定路径中。