JAVA可以通过JNI接口访问本地的动态连接库,从而扩展JAVA的功能。使用JAVA JNI接口主要包括以下步骤:
(1)编写JAVA代码,注明要访问的本地动态连接库和本地方法;
(2)编译JAVA代码得到.class文件;
(3)使用javah -jni 生成该类对应的C语言.h文件;
(4)使用C/C++实现(3)生成的.h文件中声明的各函数;
(5)编译C/C++实现代码生成动态连接库。
本文使用一个简单的helloWorld示例演示JNI的使用。
(1)编写JAVA代码
public class helloWorld
{
public native void SayHello(String name);
static
{
System.loadLibrary("examdll");
}
public static void main(String [] argv)
{
helloWorld hello = new helloWorld();
hello.SayHello("myName");
}
}
(2)编译JAVA代码
javac helloWorld.java
(3)生成实现函数头文件
javah -classpath . helloWorld
得到的文件内容如下:
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class helloWorld */
#ifndef _Included_helloWorld
#define _Included_helloWorld
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: helloWorld
* Method: SayHello
* Signature: (Ljava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_helloWorld_SayHello
(JNIEnv *, jobject, jstring);
#ifdef __cplusplus
}
#endif
#endif
(4)在VC中实现上述函数
#include "helloWorld.h"
#include <stdio.h>
#include <string.h>
void JNICALL Java_helloWorld_SayHello(JNIEnv * env, jobject obj, jstring str)
{
jboolean b = true;
char s[80];
memset(s, 0, sizeof(s));
strcpy_s(s ,(char*)env->GetStringUTFChars(str, &b));
printf("Hello, %s", s);
env->ReleaseStringUTFChars(str , NULL);
}
**** 这是JNI的关键:通过env我们可以使用JAVA提供的一组函数操作与转换函数传递的参数。
(5)编译VC项目得到动态连接库 examdll.dll。
首先是关于dll文件的生成:
方法如下:
打开VC++6.0,新建->; 工程 ->; win32 Dynamic-Link Library在向导中选择空工程
添加如用javah生成的头文件和自己写的一个cpp文件,然后编译运行,如果没有出现错误,既可以在编译成功的debug文件夹中找到dll文件,如果出现找不到jni.h的错误,那么用如下方法解决:
fatal error C1083: Cannot open include file: 'jni.h': No such file or directory将以下文件:\jdk\include\jni.h
\jdk\include\win32\jawt_md.h
\jdk\include\win32\jni_md.h
复制到Visual Studio.net的安装目录下的\Vc7\include目录中
如果是VC2005则存放到安装目录下的\VC\include目录中
如果是VC6.0,自己找相应的目录即可!