Eclipse中使用JNI調用C++ build的dll
- Uper
最近想寫個從java程序中調用C++生成的dll的工具. 在網上搜索一些帖子,大概過程如下:
1. 建立自己的JAVA 類,該類帶有一個or多個native聲明的方法
2. 使用javac,生成.CLASS 文件
3. 使用javah,生成*.H文件
4. 根據*.H文件完成C++的dll
5. copy該dll到class所在的folder下
6. 使用java運行該application 即可.
但是當我把相關內容移到eclipse上時, 總是throw exception:java.lang.UnsatisfiedLinkError異常,後發現是我的*.h文件生成有問題。
下面把我的過程描述一下,以便參考:
Eclipse side
1. Create java class named SWIFTAlianceCASmfTest with function of declared native
package test.cs.web;
import java.lang.*;
public class SWIFTAlianceCASmfTest{
public native static int calculate(int addone);
public static void main(String arg[]){
try{
SWIFTAlianceCASmfTest objTest = new SWIFTAlianceCASmfTest();
int add1 = 3;
int add2 = SWIFTAlianceCASmfTest.calculate(add1);
System.out.println("The result is "+add2);
}catch(Exception ex){
System.out.println("The result is "+add2);
}
}
static {
System.loadLibrary("mycalculate");
}
}
2. Save it and eclipse will build and generate class file SWIFTAlianceCASmfTest.class in folder ../WEB-INF/CLASSES/test/cs/web/
3. Go to the folder ../WEB-INF/CLASSES/
Execute command javah -jni test.cs.web.SWIFTAlianceCASmfTest
Note: test.cs.web is package name and not lose it.
The file test_cs_web_SWIFTAlianceCASmfTest.h will be generated. Refer to below:
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class test_cs_web_SWIFTAlianceCASmfTest */
#ifndef _Included_test_cs_web_SWIFTAlianceCASmfTest
#define _Included_test_cs_web_SWIFTAlianceCASmfTest
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: test_cs_web_SWIFTAlianceCASmfTest
* Method: calculate
* Signature: (I)I
*/
JNIEXPORT jint JNICALL Java_test_cs_web_SWIFTAlianceCASmfTest_calculate
(JNIEnv *, jclass, jint);
#ifdef __cplusplus
}
#endif
#endif
4. C++ side: According to head file test_cs_web_SWIFTAlianceCASmfTest.h, build dll named mycalculate.dll using VC and implement function Java_test_cs_web_SWIFTAlianceCASmfTest_calculate(,,)
.cpp
#include "jni.h";
#include "test_cs_web_SWIFTAlianceCASmfTest.h";
JNIEXPORT jint JNICALL Java_test_cs_web_SWIFTAlianceCASmfTest_calculate
(JNIEnv *env, jclass obj, jint nAdd1)
{
return (nAdd1+nAdd1);
}
.def
LIBRARY LIB
EXPORTS
Java_test_cs_web_SWIFTAlianceCASmfTest_calculate @ 1
In VC tools, include the path of files jni.h & jni_md.h in JDK install directory.
5. Eclipse side: copy mycalculate.dll to folder ../WEB-INF/CLASSES/
Set Eclipse VM arguments: -Djava.library.path=<the position of mycalculate.dll located in> fgdsf
6. Run Java application in Eclipse and it will return result:The result is 6
以上有2點需要注意:
1. don't forget the package name when you generate head file by tool javah
2. the path of dll file and path of running command javah make is correctly.