参考:
http://setting.iteye.com/blog/304594
http://blog.youkuaiyun.com/crayonyi/article/details/7413017
首先是java代码:
1:新建一个TestJNI类
public class TestJNI
{
static
{
System.loadLibrary("TestJNI");
}
public static native void sayHello(String msg);
public static void main(String[] args)
{
sayHello("Hello,this is my first JNI program !");
}
}
2:使用命令行编译该类生成class文件 javac TestJNI.java 生成TestJNI.class文件
3:使用命令行生成C头文件 javah TestJNI 生成TestJNI.h文件
TestJNI.h内容如下:
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class TestJNI */
#ifndef _Included_TestJNI
#define _Included_TestJNI
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: TestJNI
* Method: sayHello
* Signature: (Ljava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_TestJNI_sayHello
(JNIEnv *, jclass, jstring);
#ifdef __cplusplus
}
#endif
#endif
然后使用vs2010生成供调用的dll文件
1:新建一个工程,选择Win32工程,next
2:选择dll工程 finish就可以了
3:将TestJNI.h添加为工程头文件,先将TestJNI.h拷到工程目录下,然后在header files 文件夹右键--->add --->existing item
4:打开StdAfx.h文件,再最后面添加:
#include <jni.h>
#include "TestJNI.h"
这里会不识别 #include <jni.h>,别着急
5:编辑TestJNI.cpp文件,内容如下:
#include "stdafx.h"
#include "TestJNI.h"
JNIEXPORT void JNICALL Java_TestJNI_sayHello(JNIEnv * env, jclass obj, jstring jMsg)
{
const char *strMsgPtr = env->GetStringUTFChars( jMsg , 0);
MessageBox( 0, strMsgPtr, "Message box from VC++", 0 );
env->ReleaseStringUTFChars( jMsg, strMsgPtr);
}
6:打开工程属性,选择Configuration Properties --->VC++ Directories--->include Directories 添加jdk路径下的include和/include/win32目录,这里包含jni.h等头文件,如果不包含这两个目录,工程中的#include<jni.h>将无法找到所包含的文件
7:build工程,打开工程目录的debug目录,将其中生成的TestJNI.dll考到java工程的java.library.path目录下(一般的是系统的system32目录),当然也可在工程的配置里面配置java.library.path目录为dll文件所在的目录
到这里这个小小的jni测试工程就可以正确运行了。
关于 JNIEXPORT void JNICALL Java_TestJNI_sayHello(JNIEnv * env, jclass obj, jstring jMsg)的说明:
前面的一部分是java的关键字 供虚拟机调用外部程序时识别用的,格式是固定的。而Java_TestJNI_sayHello中的TestJNI则是java工程的类名,sayHello则是类中所要调用的本地方法的方法名
最后要注意的是在真正的应用中要注意变量的类型,因为java虚拟机使用的变量存储方式和其他语言是不一样的,例如java中int是32位的,而一般C中int是16位的,在使用时要注意映射关系。
更多详细内容:http://docs.oracle.com/javase/6/docs/technotes/guides/jni/