java jni调用 非托管 dll

Step1:

 编写java类,e.g.:

//filename: HelloWorld.java
public class HelloWorld{
	public native void  displayHelloWorld();
	public native int add(int a,int b);
	
	static {
		System.loadLibrary("hello");
	}
	public static void main(String[] args){
		HelloWorld hw=new HelloWorld();
		hw.displayHelloWorld();
		System.out.println();
		System.out.println(" 1+20= "+ hw.add(1,20) );
	}
}

Step2:  javac HelloWorld.java

Step3:  javah 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:    displayHelloWorld
 * Signature: ()V
 */
JNIEXPORT void JNICALL Java_HelloWorld_displayHelloWorld
  (JNIEnv *, jobject);

/*
 * Class:     HelloWorld
 * Method:    add
 * Signature: (II)I
 */
JNIEXPORT jint JNICALL Java_HelloWorld_add
  (JNIEnv *, jobject, jint, jint);

#ifdef __cplusplus
}
#endif
#endif

Step4:用vc6建立一个win32 dll项目, 项目名hello

Step5:

tools->option->directory(标签)

directories增加两个include 路径(具体看java的实际include路径):

D:\java\jdk\jdk1.6.0_21\include

D:\java\jdk\jdk1.6.0_21\include\win32

Step6:

新建hello.cpp

#include <jni.h>
#include "HelloWorld.h"
#include <stdio.h>
#include <windows.h>

JNIEXPORT void JNICALL Java_HelloWorld_displayHelloWorld
  (JNIEnv *, jobject)

{
	printf("hello 中国 !@#$");
}

/*
* Class:     HelloWorld
* Method:    add
* Signature: (II)I
*/
JNIEXPORT jint JNICALL Java_HelloWorld_add
(JNIEnv *, jobject, jint a, jint b){

	return a+b;
}


posted @ 2011-02-17 12:23  庚武  Views(344)  Comments(0Edit  收藏  举报