昨天突然想到一个问题:Java如何调用动态链接库DLL。然后开始上网查找资料,原来没有接触过这方面,就是小白一个。花了一天时间终于成功,在这里记录一下遇到的问题。
win7 x64 ;vs2010 ;eclipse
第一步:创建Satrt.java文件代码如下(这里借鉴
使用JNI进行Java与C/C++语言混合编程(1)--在Java中调用C/C++本地库
)public class Start {
public native int intMethod(int n);
public native boolean booleanMethod(boolean bool);
public native String stringMethod(String text);
public static void main(String[] args) {
System.loadLibrary("Start");
Start sample = new Start();
int square = sample.intMethod(5);
boolean bool = sample.booleanMethod(true);
String text = sample.stringMethod("Java");
System.out.println("intMethod: " + square);
System.out.println("booleanMethod: " + bool);
System.out.println("stringMethod: " + text);
}
}
win7下cmd中执行javac Start.java生成Start.class,之后执行javah Start。出现的问题Javac.exe找不到,Javah时有错误等等。
解决:重装JDK且采用默认路径。我原来是放在D盘下的,环境变量也配置无误,但就是有问题。这里建议采用默认路径。只装JDK即可(JDK中包含的jre也采用默认安装)。因为jdk内包含一个jre文件,所以自定义安装时jdk与jre安装在同一目录下并列,不必另外下载jre单独安装。
生成Start.h时注意在start.h的根目录下执行javah Start;另外Satrt不带.class后缀。
第二步:使用vs2010生成DLL
文件->新建项目->visualC++中选择win32项目;填写项目名Start,后确定->下一步;选择DLL,空项目,完成,新建头文件Start.h,源文件Start.cpp。将上一步生成的Start.h内容拷入。编写Start.cpp。注意:.h与.cpp中需要修改添加下文第三步的包头som
Start.cpp代码如下:
#include "Start.h"
#include <string.h>
JNIEXPORT jint JNICALL Java_som_Start_intMethod
(JNIEnv *env, jobject obj, jint num)
{
return num * num;
}
JNIEXPORT jboolean JNICALL Java_som_Start_booleanMethod
(JNIEnv *env, jobject obj, jboolean boolean)
{
return !boolean;
}
JNIEXPORT jstring JNICALL Java_som_Start_stringMethod
(JNIEnv *env, jobject obj, jstring string)
{
const char* str = env->GetStringUTFChars(string, 0);
char cap[128];
strcpy(cap, str);
env->ReleaseStringUTFChars(string, 0);
return env->NewStringUTF(strupr(cap));
}
注意:这里需要将jdk安装目录下include文件夹下的jni.h文件与include\win32下的jawt_md.h和jni_md.h拷贝到vs安装目录下的VC\include中。生成->配置管理器,在解决方案配置Release下编译,同时选择64位
启动调试,在项目路径x64\Release下找到Start. dll.
第三步:在eclipse中新建项目som,包名som,类名Start。Start代码如下:
package som;
public class Start {
public native int intMethod(int n);
public native boolean booleanMethod(boolean bool);
public native String stringMethod(String text);
public static void main(String[] args) {
System.loadLibrary("Start");
Start sample = new Start();
int square = sample.intMethod(5);
boolean bool = sample.booleanMethod(true);
String text = sample.stringMethod("Java");
System.out.println("intMethod: " + square);
System.out.println("booleanMethod: " + bool);
System.out.println("stringMethod: " + text);
}
}
将Start.dll文件拷贝到Java工程bin目录下;在eclipse环境变量中增加nativelibrary location支持;点击Java项目右键—Build Path—ConfigureBuild Path如
图
注意:在第一步中的.class文件不可使用eclipse中生成的。因为包含包头时javah有问题,
第四步:编译执行
输出如下:
参考文章:1