2010年9月23日 星期四

Using Java Native Interface on Ubuntu 10.04

從無到有: to achieve Java Native Interface(JNI) on Ubuntu 10.04
  • How to install Java SDK 1.6 on Ubuntu (manual)
    1. Download the Java JDK 1.6 from Sun's site.
    2. http://java.sun.com/javase/downloads/index.jsp 
    3. Select the Java SE Development Kit (JDK)
    4. This leads to a page allowing us to select the Operating System, usually we just choose "Linux".
    5. Then we came to a page which shows the available packages. I click on "jdk-6u21-linux-i586.bin" because this version is a package resembling to a tar.gz
    6. Once the newly downloaded file is here, we need to extract it to a folder named "jdk1.6.0_21" (for example).
    7. It's better then to move  Jdk1.6.0_21 folder to "/usr/local/" which is the standard folder for programs or GUI console.
    8. We will proceed to add the JAVA_HOME variable to the system. To do this, open bash.bashrc file with the following command:
    9. $sudo vi /etc/bash.bashrc
      At the end of the file put the following instructions.
      export JAVA_HOME=/usr/local/jdk1.6.0_21
      
      export PATH=$JAVA_HOME/bin:$PATH
      This makes sure that the JAVA_HOME variable is always available in the system.
    10. Open a new console and run the command:
    11. $java -version
      To which we assume the following result:
      java version "1.6.0_21"
      Java(TM) SE Runtime Environment (build 1.6.0_21-b06)
      Java HotSpot(TM) Server VM (build 17.0-b16, mixed mode)
  • Achieve a simple JNI implementation on Ubuntu (Java call C/C++)
  • Example: To Pass a string from Java to native method (C++) and prints personalized Hello World.
    1. HelloWorlo.java: main function to call native method
    2. class HelloWorld {
          public native void sayHi(String name);
          static
          {
              System.loadLibrary("HelloWorld");
          }
          public static void main(String[] args)
          {
              HelloWorld h = new HelloWorld();
              h.sayHi("Ryan Cho");
          }
      }
      
      We announce our intention to use native method "sayHi" from "HelloWorld" library -- System.loadLibrary("HelloWorld").
    3. Compile this class and generate class file "HelloWorld.class":
    4. javac HelloWorld.java
    5. Generate the header for native method:
    6. javah -jni HelloWorld
      The header file for native method "HelloWorld.h" is generated.
      HelloWorld.h: The header file for native method (automatic generated)
      /* 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:    sayHi
       * Signature: (Ljava/lang/String;)V
       */
      JNIEXPORT void JNICALL Java_HelloWorld_sayHi
        (JNIEnv *, jobject, jstring);
      
      #ifdef __cplusplus
      }
      #endif
      #endif
      
    7. Write implementation C++ file (HelloWorld.cpp):
    8. HelloWorld.cpp: The implementation file for native method.
      #include <jni.h>
      #include <iostream>
      #include "HelloWorld.h"
      
      using namespace std;
      
      JNIEXPORT void JNICALL Java_HelloWorld_sayHi
        (JNIEnv *env, jobject o, jstring s)
      {
          const char *str = env->GetStringUTFChars(s, 0);
          cout << "Hello! " << str << endl;
          env->ReleaseStringUTFChars(s, str);
      }
      
    9. There is no garbage collector in C++ world, so we need to do some cleanup. We save this as HelloWorld.cpp and compile it to generate shared library:
    10. g++ -shared -I/usr/local/jdk1.6.0_21/include -I/usr/local/jdk1.6.0_21/include/linux HelloWorld.cpp -o libHelloWorld.so
      !Attention: The path to your java include directory may be different.
    11. Run this example as following:
    12. java -Djava.library.path=. HelloWorld
      The result like this:
      Hello! Ryan Cho

Install sun-java6-jdk on Ubuntu 10.04

I just had trouble to install the Sun Java6 JDK after updating to Ubuntu 10.04. The problem was that the system couldn’t find the package sun-java6-sdk and apt-get gave me the message:

Package sun-java6-jdk is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source
E: Package sun-java6-jdk has no installation candidate

What I did to solve this problem was to add a new source

sudo add-apt-repository "deb http://archive.canonical.com/ lucid partner"

After this...

sudo apt-get update
sudo apt-get install sun-java6-jdk

It worked fine for me.

2010年9月17日 星期五

Qt4 學習筆記(九):循序容器 (QVector、QLinkedList、QList) 與迭代器 (iterator)

  • QVector、 QLinkedList與QList是Qt所提供的幾個常用容器類別。
    • QVector將項目(item)儲存在鄰接的記憶體空間之中,提供基於索引(index-based)存取方式的容器類別。
    • QLinkedList以鏈結(Linked)的方式儲存項目,提供基於迭代器(iterator- based)存取方式的容器類別。
    • QList提供基於索引的快速存取容器類別,內部使用指標陣列,可提供快速插入及移除項目。
  • 列出QVector、QLinkedList及QList的使用比較:
    • 如果想要有連續鄰接的記憶體空間來存放元件,則使用QVector。
    • 如果需要真正的鏈結資料結構,並使用基於迭代器的存取方式,則使用QLinkedList。
    • 在大部份情況下,QList可以滿足快速存取、插入、移除的需求,並可提供基於索引的存取方式。
  • QVector
  • QVector的基本使用方式,建立一個可容納兩個元素的QVector,並使用索引方式存取元素值:
    #include <iostream>
    #include <vector>
    using namespace std;
    
    QVector<double> vect(2);
    vect[0] = 1.0;
    vect[1] = 2.0;
    
    for (int i = 0; i < vect.count(); ++i) {
        // 使用 [] 運算子指定索引存取
        cout << vect[i] << endl;
    }
    
    for (int i = 0; i < vect.count(); ++i) {
        // 使用 at() 方法指定索引存取
        cout << vect.at(i) << endl;
    }
    
    可以使用QVector的append()方法來加入元素,使用remove()方法來移除元素,使用insert()方法來插入元素,例如append()的使用如下:
    vect.append(3.0);
    vect.append(4.0);
    
    或者是使用<<運算子附加元素:
    vect << 5.0 << 6.0;
    
    QVector提供的是鄰接的記憶體空間以存取物件,所以對於循序存取或使用索引,效率較高,但如果要插入或移除元素時,效率就會低落。QVector的子類別QStack提供了push()、pop()、top()等方法,方便進行堆疊結構的物件管理。
  • QList
  • QList提供的是基於索引的存取方式,其內部實作使用了指標陣列,陣列中每個指標指向所要儲存的元素,結合了QVector與QLinkedList的優點,提供快速存取與插入、移除,其索引存取方式或可用的方法與QVector是類似的,也可以使用<<運算子來附加元素。
    QList<QString> list;
    list << "caterpillar" << "momor" << "bush";
    
    for(int i = 0; i < list.size(); ++i) {
        cout << list[i].toAscii().data() << endl;
    }
    cout << endl;
        
    for(int i = 0; i < list.size(); ++i) {
        cout << list.at(i).toAscii().data() << endl;
    }    
    cout << endl;
    
    QList的子類別QStringList為Qt中應用很廣的類別,可以讓您儲存QString物件,QList的子類別QQueue則提供了佇列結構的容器管理。
  • QIterator
    • 關於迭代器於容器類別的使用,Qt提供兩種風格的迭代器:Java風格與STL風格。Java風格的迭代器使用上就如同Java的迭代器,使用這種迭代器對於Java開發人員較為容易,然而STL風格的迭代器則提供更有彈性的操作。
    • Java-Style iterator
    簡單示範在QList上使用Java風格迭代器:
    // Java-Style Iterator
    QList<QString> list;
    list << "caterpillar" << "momor" << "bush";
        
    QListIterator<QString> iterator(list);
    while (iterator.hasNext()) {
        cout << iterator.next().toAscii().data() << endl;
    }
    
    與Java迭代器類似的,hasNext()測試是否有下一個元素,next()傳回下一個元素,其它還有hasPrevious()、previous()等方法可以使用。Java風格的迭代器有兩種:唯讀與可讀寫。QListIterator是唯讀迭代器,對於可讀寫迭代器,命名上會加上Mutable,例如QMutableListIterator,除了next()、previous()等方法之外,還提供了insert()、remove()等方法可以使用,以QLinkedList使用Java風格迭代器為例:
    QLinkedList<QString> list;
    list << "caterpillar" << "momor" << "bush";
    
    QMutableLinkedListIterator<QString> rwIterator(list);
    while (rwIterator.hasNext()) {
        if(rwIterator.next() == "momor") {
            rwIterator.insert("bee");
            break;
        }
    }
    
    QLinkedListIterator<QString> rIterator(list);
    while (rIterator.hasNext()) {
        cout << rIterator.next().toAscii().data() << endl;
    }
    
    • STL-Style iterator
    • 關於使用STL風格迭代器,可以使用容器類別的begin()方法傳回基於STL的迭代器,它指向容器的第一個元素位址,end()方法則傳回指向容器最後一個元素之後的位址。您可以如下使用基於STL的迭代器:
    // STL-Style Iterator
    QList<QString> list;
    list << "caterpillar" << "momor" << "bush";
    
    QList<QString>::const_iterator i = list.begin();
    while (i != list.end()) {
        cout << (*i).toAscii().data() << endl;
        ++i;
    }
    
    STL風格的迭代器一樣有兩種,C<T>::const_iterator形式的迭代器宣告為唯讀,可以讀取資料,但無法修改資料,C<T>::iterator形式的迭代器則可以修改資料,例如:
    QList<QString> list;
    list << "caterpillar" << "momor" << "bush";
        
    QList<QString>::iterator i = list.begin();
    while (i != list.end()) {
        (*i) = (*i) + ".onlyfun";
        cout << (*i).toAscii().data() << endl;
        ++i;
    }
    
    對於簡單的循序存取,Qt提供了foreach虛擬關鍵字(pseudo-keyword),以標準的for迴圈實作,例如您可以如下循序取出QList中的元素:
    QList<QString> list;
    list << "caterpillar" << "momor" << "bush";
        
    foreach(QString str, list) {
        cout << str.toAscii().data() << endl;
    }