Linux下Java JNI起步

來源:互聯網
上載者:User

1. 建立JniTest.java:

public class JniTest {
    static {
        System.loadLibrary("hello");
    }

    public native void say();

    public static void main(String[] args) {
        System.out.println("I'm in Java");
        new JniTest().say(); 
    }
}

2.編譯JniTest.java並產生Native標頭檔:

javac JniTest.java 
javah -jni JniTest

3. 根據JniTest.h中的函數原型,建立hello.c檔案:

#include <stdio.h>

#include "JniTest.h"

JNIEXPORT void JNICALL Java_JniTest_say(JNIEnv *env, jobject obj)
{
    printf("I'm in c/c++\n");
}

4. 為方便編譯,產生一個Makefile檔案:

Makefile:
.PHONY: all

all:

        javac JniTest.java

        gcc --shared -I /usr/lib/jvm/java-6-openjdk-i386/include hello.c -o libhello.so

5. 編譯make,並執行:

java -Djava.library.path=. JniTest

註:如不指明libray路徑,將報錯:

[ancoo@ubuntu jnitest]$ java JniTest 
Exception in thread "main" java.lang.UnsatisfiedLinkError: no hello in java.library.path
        at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1738)
        at java.lang.Runtime.loadLibrary0(Runtime.java:823)
        at java.lang.System.loadLibrary(System.java:1028)
        at JniTest.<clinit>(JniTest.java:4)
Could not find the main class: JniTest.  Program will exit.

聯繫我們

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