下面是在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;
}
- 创建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
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class org_ming_jni_MyNativeImplementation */
#ifndef _Included_org_ming_jni_MyNativeImplementation
#define _Included_org_ming_jni_MyNativeImplementation
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: org_ming_jni_MyNativeImplementation
* Method: nativeMethod
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_org_ming_jni_MyNativeImplementation_nativeMethod
(JNIEnv *, jobject);
#ifdef __cplusplus
}
#endif
#endif
这将生成名为com_example_MyClass.h
的头文件。
- 编译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方法:
// Main.java
package com.example;
public class Main {
public static void main(String[] args) {
MyClass myClass = new MyClass();
myClass.nativeMethod();
}
}
确保在运行Java代码之前,将生成的DLL文件放在Java库路径或在运行时指定路径中。