JNI 测试程序
1:编写java文件
public class ShowMsgBox {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ShowMsgBox app = new ShowMsgBox();
try{
app.ShowMessage("Cenerated with JNI");
}catch(Exception e){
e.printStackTrace();
}
}
private native void ShowMessage(String string);
static{
// TODO Auto-generated method stub
try{
System.loadLibrary("MsgImpl");
}catch(Exception e){
e.printStackTrace();
}
}
}
编译该java文件:javac ShowMsgBox.java
生成C头文件javah: java -jni ShowMsgBox
编写自己的DLL
#include "stdafx.h"
#include <windows.h>
#include "ShowMsgBox.h"
BOOL APIENTRY DllMain( HANDLE hModule,
DWORD dwReason,
void ** lpReserved
)
{
return TRUE;
}
JNIEXPORT void JNICALL
Java_ShowMsgBox_ShowMessage(JNIEnv * jEnv, jobject a, jstring jMsg)
{
const char * msg;
msg = (*jEnv).GetStringUTFChars(jMsg, FALSE);
MessageBox(HWND_DESKTOP, msg, "Thinking in java: JNI", MB_OK | MB_ICONEXCLAMATION);
(*jEnv).ReleaseStringUTFChars(jMsg, msg);
}
将生成的dll文件copy到java源文件目录下运行java程序: java ShowMsgBox
如果有如下错误:
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目录中
如果是VC6.0,自己找相应的目录即可!
然后编译,成功后,将生成的.dll文件copy到JAVA文件的同一级目录中
换成:
const char *str = env-> GetStringUTFChars(s,0);
或const char* szStr = (*env).GetStringUTFChars(s, 0 );
1:编写java文件
public class ShowMsgBox {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ShowMsgBox app = new ShowMsgBox();
try{
app.ShowMessage("Cenerated with JNI");
}catch(Exception e){
e.printStackTrace();
}
}
private native void ShowMessage(String string);
static{
// TODO Auto-generated method stub
try{
System.loadLibrary("MsgImpl");
}catch(Exception e){
e.printStackTrace();
}
}
}
编译该java文件:javac ShowMsgBox.java
生成C头文件javah: java -jni ShowMsgBox
编写自己的DLL
#include "stdafx.h"
#include <windows.h>
#include "ShowMsgBox.h"
BOOL APIENTRY DllMain( HANDLE hModule,
DWORD dwReason,
void ** lpReserved
)
{
return TRUE;
}
JNIEXPORT void JNICALL
Java_ShowMsgBox_ShowMessage(JNIEnv * jEnv, jobject a, jstring jMsg)
{
const char * msg;
msg = (*jEnv).GetStringUTFChars(jMsg, FALSE);
MessageBox(HWND_DESKTOP, msg, "Thinking in java: JNI", MB_OK | MB_ICONEXCLAMATION);
(*jEnv).ReleaseStringUTFChars(jMsg, msg);
}
将生成的dll文件copy到java源文件目录下运行java程序: java ShowMsgBox
如果有如下错误:
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目录中
如果是VC6.0,自己找相应的目录即可!
然后编译,成功后,将生成的.dll文件copy到JAVA文件的同一级目录中
VC环境下(非标准C语法):
报错为:'GetStringUTFChars' : function does not take 3 parameters
把 const char* szStr = (*env)-> GetStringUTFChars( env, s, 0 );换成:
const char *str = env-> GetStringUTFChars(s,0);
或const char* szStr = (*env).GetStringUTFChars(s, 0 );