Java Native Interface... A try?

Discussion in 'Bài viết hướng dẫn JSE' started by Joe, 4/3/13.

  1. Joe

    Joe Administrator Staff Member

    Hello CongdongJava folk,

    I'm sure that some of you would like very much to exploit the features written in C/C++ and I'm also very sure that most of you know what JNI is -Java Native Interface. As its name says, JNI allows you to venture into the C/C++ jungle without getting lost in this maze;). A Java tool "javah" is the key. It allows you to generate a header file for C/C++ (suffix .h). With the header you need only to implement your C/C++ code. Things, for example, like Keyboard-Spyingb-), etc. are available for you in Java. Cool, huh? Here is an example to show you how to go JNI:

    1) A simple Java code Go_C_CPP.java
    PHP:
    public class Go_C_CPP {
        public 
    Go_C_CPP( ) { }
        public 
    synchronized native int call_C_CPP(Object parmObject);
    }
    2) You compile this code using javac and javah as following (e.g. Window-cmd)
    Code:
    javac -g:none -nowarn  Go_C_CPP.java
    javah -jni Go_C_CPP
    
    If no complaint:Dappears you've successfully generated a CPP-Header file called Go_C_CPP.h is like this:
    PHP:
    /* DO NOT EDIT THIS FILE - it is machine generated */
    #include <jni.h>
    /* Header for class Go_C_CPP */

    #ifndef _Included_Go_C_CPP
    #define _Included_Go_C_CPP
    #ifdef __cplusplus
    extern "C" {
    #endif
    /*
    * Class:    Go_C_CPP
    * Method:    call_C_CPP
    * Signature: (Ljava/lang/Object;)I
    */
    JNIEXPORT jint JNICALL Java_Go_1C_1CPP_call_1C_1CPP
      
    (JNIEnv *, jobjectjobject);

    #ifdef __cplusplus
    }
    #endif
    #endif
    3) Now you open an editor (e.g. notepad of "anhdiepmmk"b-)) and create your own C/C++ code
    PHP:
    #include "Go_C_CPP.h"
    ...
    JNIEXPORT jint JNICALL Java_Go_1C_1CPP_call_1C_1CPP
    JNIEnv *MyJavaCode,
      
    jobject This,
      
    jobject parm
    )
    {
      
    char *tmp;
      
    jclass jcls;
      
    jfieldID jid;
      
    jstring jstr;
      
    jcls = (*MyJavaCode)->GetObjectClass(MyJavaCodeparm);
      
    jid = (*MyJavaCode)->GetFieldID(MyJavaCodejcls"javaString""Ljava/lang/String;");
      if (
    jid == 0) {
          
    printf("Can't access javaString\n");
          return -
    1;
      }
      
    jstr = (*MyJavaCode)->GetObjectField(MyJavaCodeobjjid);
      
    tmp = (char *)(*MyJavaCode)->GetStringUTFChars(MyJavaCodeparmjstr0);
      
    //....your codes
      
    return 0;

    }
    4) Then...Here we go!
    PHP:
    Go_C_CPP iGoJNI = new Go_C_CPP( );
    if (
    iGoJNI.call_C_CCP("HelloWorld") == -1) {
      
    System.out.println("Can't call Go_C_CPP");
      
    System.exit(0);
    }
    ...
    Simple, isn't it?=))
    Joe
  2. Joe

    Joe Administrator Staff Member

    Oh... You newbies and rookies are "vo lu luon"?:)) OKAY...here is a help: The generated C/C++ code must be compiled as .dll and you know what dll means? Oh! It stands for Dynamic Library Link. An old invention of the Mini Computer Age. A herald of OO. Yes. It's OO.
    Back to your .dll. How can Java know that it needs a dll for a method? Yes. You must tell Java and command it to load the necessary dll for you. Sounds very complicated but it's quite...simple. Let's fumble with the above mentioned little Java code Go_C_CPP:
    PHP:
    public class Go_C_CPP {
        public 
    Go_C_CPP(String dllPaththrows Exception {
            
    System.loadLibrary(dllPath);
      }
      
    //
      
    public synchronized native int call_C_CPP(Object parmObject);
    }
    See? Quite simple, isn't it? ;)
    Joe
  3. Mọi người cho em hỏi, đến bước 3, khi biên dịch file C/C++ thì nó báo lỗi là không có thư viện jni.h là sao ạ. EM đã để file HelloWorld.c vào cùng với thư mục của file HelloWorld.h tạo ra khi dịch java rồi.
  4. Joe

    Joe Administrator Staff Member

    Look at the directory where you install your java and search for the subdirectory include -for example on Windows: C:\Program Files\Java\jdk1.7.0.13\include

  5. No. I use on ubuntu and I save project in Home/workspace/
    I save file HelloWorld.c in src where have HelloWorld.h, HelloWorld.class and file native.java.
  6. Joe

    Joe Administrator Staff Member

    Ubuntu? Similar. Run the command whereis then you may find where it is stored. Ubuntu runs OpenJDK and it could be a bit different.
    On Ubuntu (LINUX) it's very important to include this directory or library to your PATH, beside your CLASSPATH.
    Here is on my Ubuntu 13.04
    Code:
    joe@ubuntu:~$ whereis jni.h
    jni: /usr/lib/jni
    joe@ubuntu:~$ 
    nguyenvanquan7826 likes this.
  7. yes, it in /usr/lib/jni
    Now, What should I do ?
  8. Joe

    Joe Administrator Staff Member

    Boy! You want me to tutor you here in C++ -on CondongJava Forum ? =)) Hopefully our bosses JackV and Tranhuyvc won't ban me if I show you...I don't know what C compiler you have. Here is an example of Gnu C++:
    Code:
    joe@ubuntu:~$ gcc -fpic -c program1.c
    joe@ubuntu:~$ gcc -fpic -c program2.c
    ...
    joe@ubuntu:~$ gcc -shared -o mylib.so program1.o program2.o ... program100.o
    
    The shared lirbary mylib.so is
    PHP:
    public class MyCPP {
        public 
    MyCPP( ) throws Exception {
            
    System.loadLibrary("./joe/lib/mylib.so"); // load the lib
      
    }
    ....
  9. Sorry but when I run file HelloWorld.c, it error "HelloWorld.h:2:30: fatal error: jni.h: No such file or directory "
  10. khangphamngoc90

    khangphamngoc90 Algorithms Master Staff Member

    @quan : Ubuntu/Linux biên dịch C/C++ mặc định qua gcc compiler. Em có thể tìm hiểu cấu trúc biên dịch của nó nhé ;)
  11. Em biên dịch nhưng lỗi mà, không tìm thấy file jni.h @
  12. khangphamngoc90

    khangphamngoc90 Algorithms Master Staff Member

    Đây là đoạn clip mình làm rất đơn giản trên Ubuntu các bạn có thể vừa xem vừa code theo ;)
    nguyenvanquan7826 and Joe like this.
  13. Joe

    Joe Administrator Staff Member

    the most important things on UNIX/LINUX over everything ARE the PATH and the CLASSPATH. If you don't understand the functionality of the 2 words you get nowhere. The error message tells me that you, as every newbie usually is, think that UNIX (or Computer in general) is very smart and knows what you think in your skull. Therefore you get nowhere. Here is an example showing you how to set up your working environment
    Code:
    CLASSPATH=./classes:/media/Data/BOOM/classes:/media/Data/UbuntuJFX/JavaFXS
    ceneBuilder1.1/runtime/jre/lib:$CLASSPATH:
    PATH=./:/media/Data/BOOM:/media/Data/UbuntuJFX/JavaFXSceneBuilder1.1/runti
    me/jre/lib/i386:$PATH:
    export CLASSPATH
    export PATH
    
    nguyenvanquan7826 likes this.
  14. Joe

    Joe Administrator Staff Member

    Not bad !
    khangphamngoc90 likes this.
  15. Joe

    Joe Administrator Staff Member

    nguyenvanquan
    I know that you wrote something into my "profile". But due to bugs or whatever (I don't careb-)) I couldn't read your message. You have 2 choices to communicate with me:
    - this forum (excl. the writing into my profile)
    - jnartca@gmail.com
    ;)
    nguyenvanquan7826 likes this.
  16. Nhưng em làm đến đoạn :
    Code:
    gcc -shared -fpic -I/usr/lib/jvm/jdk1.7.0/include -I/usr/lib/jvm/jdk1.7.0/include/linux Test.c -o libTest.so
    thì nó vẫn bảo là
    Code:
    Test.c:1:17: fatal error: jni.h: No such file or directory
    Liệu có phải đường dẫn của em sai?
  17. Joe

    Joe Administrator Staff Member

    Now you confuse yourself. Your posting above says the jni.h is in the lib. /usr/lib/jni then you try to compile with 2 hints:
    -I/usr/lib/jvm/jdk1.7.0/include
    -I/usr/lib/jvm/jdk1.7.0/include/linux
    where is the -I/usr/lib/jni ?
    The concept of UNIX (LINUX is just a grandchild of UNIX) bases on a personalization. That means every user has his / her own environment and he or she defines how the environment looks like. You can't copy everything that Khangphamngoc has and apply in your own environment.
    nguyenvanquan7826 likes this.
  18. Em sửa được đường dẫn rồi, tạo được file libTest.so rồi nhưng thực thi java nó lại báo:
  19. Joe

    Joe Administrator Staff Member

    =))boy...boy...boy... You're like a spoiled boy. You really needs a nice patient girl who leads you step by step upwards....
    Haven't you seen the YouTube of Khangphamngoc? Have you set your environment variable LD_blabla ? No? Then play the YouTube again, again, again,....

Chia sẻ trang này