linux下通過eclipse開發用java調用c程式的方法

來源:互聯網
上載者:User

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的方法,同樣實現,歡迎一起討論!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.