linux下通過eclipse開發用java調用c程式的方法:
1.先建立好java工程並建立java檔案如下:
public class testso {
static {
System.loadLibrary("testc"); //這裡項目顯示為:libtestc.so,只需要填實際的名字,
//前尾碼可以不填
}
public native static int get();
public native static void set(int i);
public static void main(String[] args){
testso t = new testso();
t.set(10);
System.out.println(t.get());
}
}
2.在終端或者用eclipse編譯testso.java檔案(javac testso.java)產生相應的class檔案testso.class
3.同理用javah testso.class檔案產生testso.h檔案。其中.h檔案內容如下:
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
#ifndef __testso__
#define __testso__
#ifdef __cplusplus
extern "C"
{
#endif
JNIEXPORT jint JNICALL Java_testso_get (JNIEnv *env, jclass);
JNIEXPORT void JNICALL Java_testso_set (JNIEnv *env, jclass, jint);
#ifdef __cplusplus
}
#endif
#endif /* __testso__ */
4.建一個c工程,注意項目類型為Shared Library.然後建立一個c檔案,內容如下:
#include"testso.h"
int i=0;
JNIEXPORT jint JNICALL Java_testso_get (JNIEnv *env, jclass jc){
return i;
}
JNIEXPORT void JNICALL Java_testso_set (JNIEnv *env, jclass jc, jint j){
i=j;
}
5.把test.h檔案拷貝到c工程項目下,方便找到!
6.在運行testso.java時,要添加好運行環境(其中注意variable不能隨便填!):
點擊run--->在Environment裡面點擊new建立--->variable填:LD_LIBRARY_PATH ----->value填:so檔案所在目錄,這裡為:/home/alen/workspace/testc/Debug
7.最後運行java檔案,顯示10!恭喜你,成功了!其他類似的調用c的方法,同樣實現,歡迎一起討論!