日期:2014-05-17  浏览次数:20647 次

Windows 下 JNI 备忘
1、编写需要使用Jni的Java类文件
public class JniCall {
	static {
		System.loadLibrary("testJNA");
	}
	
	public native static int add(int first, int second);
	
	public static void main(String[] args) {
		int first = 3;
		int second = 4;
		
		System.out.printf("print in java : %d + %d = %d", first, second, add(first, second));
	}
}

本地方法必须声明为native。

2、编译出class文件,用javah从class文件生成C的头文件JniCall.h
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class JniCall */

#ifndef _Included_JniCall
#define _Included_JniCall
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     JniCall
 * Method:    add
 * Signature: (II)I
 */
JNIEXPORT jint JNICALL Java_JniCall_add
  (JNIEnv *, jclass, jint, jint);


typedef struct Student {
	char * name;
	int age;
	int height;

}StudentObj;

#ifdef __cplusplus
}
#endif
#endif



3、在VC下建立一个动态链接库项目testJNA

倒数第二个。

4、把生成的JniCall.h和$JAVA_HOME/include/jni.h、$JAVA_HOME/include/win32jni_md.h拷贝到vc项目testJNA的目录下


5、编写C的本地实现

#include "stdafx.h"


BOOL APIENTRY DllMain( HANDLE hModule, 
                       DWORD  ul_reason_for_call, 
                       LPVOID lpReserved
					 )
{
    return TRUE;
}

JNIEXPORT jint JNICALL Java_JniCall_add(JNIEnv *, jclass, jint first, jint second) {
	printf("print in c    : %d + %d = %d \n", first, second, first + second);
	return first + second;
}


6、构建testJNA项目,生成testJNA.dll文件


7、把testJNA.dll拷贝到$JAVA_HOME/jre/bin目录下

8、运行Java类,调用本地方法
D:\Java\jdk1.6.0_02\bin>java JniCall
print in c    : 3 + 4 = 7
print in java : 3 + 4 = 7
D:\Java\jdk1.6.0_02\bin>