Jni C linux平台第一個執行個體__linux

來源:互聯網
上載者:User

1、平台:linux

2、安裝jdk,gcc

3、編寫java代碼

HelloWorld.java


public class HelloWorld

{

    private native void print();

 

    static

    {

        System.loadLibrary("HelloWorld");

     }

 

     public static void main(String[] args)

     {

          new HelloWorld().print();

     }

}

 

4、編譯Java代碼

 

 javac HelloWorld.java

 

5、產生標頭檔

 

javah -jni HelloWorld

 

6、標頭檔如下

 

/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class HelloWorld */

#ifndef _Included_HelloWorld
#define _Included_HelloWorld
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     HelloWorld
 * Method:    print
 * Signature: ()V
 */
JNIEXPORT void JNICALL Java_HelloWorld_print
  (JNIEnv *, jobject);

#ifdef __cplusplus
}
#endif
#endif

 

 

7、編寫c檔案

 

#include "HelloWorld.h"
#include <jni.h>

JNIEXPORT void JNICALL Java_HelloWorld_print(JNIEnv *env, jobject obj)
{
        printf("Hello World");
}

 

8、將c檔案編譯成linux平台下的動態串連庫,這裡需要注意,linux平台動態連結程式庫的命名方法(lib***.so)

 

gcc -I$JAVA_HOME/include -I$JAVA_HOME/include/linux -c HelloWorld.c

 

使用上面的命令編譯,產生.o檔案,再將.o檔案打包成.so檔案

 

gcc -shared -o libHelloWorld.so HelloWorld.o

 

產生libHelloWorld.so動態連結程式庫檔案

 

9、設定動態庫地址

 

export LD_LIBRARY_PATH=libHelloWorld.so所在目錄 :$LD_LIBRARY_PATH

 

10、運行代碼

 

java HelloWorld

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.