Integrate C code within Java code using Java Native Interface in Ubuntu

3 Jan

Java and C are two of the most widely used high level programming languages today. As a result of which there is often a need to incorporate the two in a single application. Like say for example, we have some legacy code written in C or C++ and we want to use certain features of the powerful Java platform within our application without rewriting the legacy code in Java.

This is where JNI or Java Native Interface comes riding in from the darkness on a fine steed and helps save the day.

This post serves to illustrate how to write a simple HelloWorld application using JNI wherein a certain function written in C will be invoked from a Java driver class.

And oh, this is for the Linux user. So if you are on Windows you should be better off Googling the same issue.

Prerequisites:

Needless to say, your system should have Java installed. I do not wish to digress and explain installing Java on Linux, there are a host of tutorials that will help you with the same.

So first up, we write a tiny Java code, and then analyse it’s anatomy to see how it’s different from the usual Java code.

import java.io.*;


class HelloWorld {
private native void nprint();
public static void main(String[] args) {
new HelloWorld().nprint();
}


static {
System.loadLibrary(“HelloWorld”);
}
}

It’s a simple HelloWorld class with a few striking features.

  1. private native void nprint(); This statement is crucial here. What it does is, it declares a native method, nprint(). (hence the n in the beginning) What is a native method? A native method is one that is implemented in some other native language (in this case, it will be, in C)
  2. public static void main(String[] args)  – the usual driver method. It invokes the aforementioned method nprint()
  3. System.loadLibrary(“HelloWorld”) locates a native library corresponding to the name “HelloWorld” and loads the native library into the application. It shall be clearer as we progress.
Now we compile this class. So head over to your terminal and type
javac HelloWorld
Now we need to create a native header file that we can include in our C program. Doing that is simple. Another line in the terminal:
javah jni HelloWorld
Now if you do an ls -al, you shall see the original HelloWorld.java file that you’ve written, the HelloWorld.class file that was produced after compilation and HelloWorld.h – the header file that just got created.
If you check the contents of the header file, you’ll see this line
JNIEXPORT void JNICALL Java_HelloWorld_nprint
  (JNIEnv *, jobject);
Java_HelloWorld_nprint(JNIEnv *, jobject) : This is the C method that we implement. All the fanciful names in the function name – forget them for the time being, and proceed with the task at hand.
Also, this is important. The header file is system generated. So DO NOT EDIT it. Right, with that caution in mind, we move to the remaining part.
Now we write the native code in C.
#include jni.h
#include stdio.h
#include “HelloWorld.h”
JNIEXPORT void JNICALL
Java_HelloWorld_nprint(JNIEnv *env, jobject obj) {
printf(“Hello JNI World!\n”);
return;
}
Do not blindly copy this code! Thanks to Blogger’s adeptness at parsing everything within angular brackets as html and not displaying the same I have been unable to include the header files in their proper syntax. Simply enclose jni.h and stdio.h within angular brackers and we’re done.
Also notice that the function that we’ve written is the same function whose prototype we saw in the header file. This function isn’t difficult to comprehend – save for the high sounding names, but let us leave that there.
Now we need to compile the C code and create a native library . We shall use our favourite compiler and all it takes is a single line in the terminal.
gcc -I/usr/lib/jvm/java-6-openjdk/include  -o libHelloWorld.so -shared HelloWorld.c
This command compiles HelloWorld.c and also creates a native library called libHelloWorld. You will find the newly created library file libHelloWorld.so within your current working folder.
Now we are all set to run our Java program. There is however one thing we need to take care of. We need to define the native library directory path. To do that we run the following two commands.
LD_LIBRARY_PATH=.
(This is because the native shared library is contained within the current folder ( . ) )
and then
export LD_LIBRARY_PATH
That is it. Now we are all set to run our first JNI program.
 java -Djava.library.path=. HelloWorld
If all goes well, you’ll see the output.
Hello JNI World!
There you go. Your first working JNI program!
To sum up, here’s a screenshot from my terminal, that shows the sequence of shell commands (click for bigger picture).

Hello world!

2 Jan

Welcome to WordPress.com. After you read this, you should delete and write your own post, with a new title above. Or hit Add New on the left (of the admin dashboard) to start a fresh post.

Here are some suggestions for your first post.

  1. You can find new ideas for what to blog about by reading the Daily Post.
  2. Add PressThis to your browser. It creates a new blog post for you about any interesting  page you read on the web.
  3. Make some changes to this page, and then hit preview on the right. You can always preview any post or edit it before you share it to the world.

Setting up OpenCV 2.3 and Eclipse on Ubuntu 11.10

1 Jan
This post seeks to help you in installing OpenCV and Eclipse and setting them up on Ubuntu 11.10 Oneiric so that you can begin development straight away.

What is OpenCV? OpenCV is a library of programming functions (in C and some C++ classes) mainly aimed at real time computer vision and image processing. It is a cross platform library, first developed by Intel and now supported by Willow Garage, and is free for use under the open source BSD license.

What is Eclipse? Eclipse is a multi-language software development platform comprising an IDE and lots of plug ins to help you develop applications in several widely used programming languages.

This walk through is aimed at helping you to set up OpenCV 2.3 (the latest version as of January 2012), and Eclipse CDT (Eclipse with the C Development Toolkit) on Ubuntu 11.10.

Ubuntu 11.10 does come with OpenCV 2.1 in the repositories, but we want OpenCV 2.3 … so we first begin with adding a PPA for OpenCV 2.3.

Head over to the terminal and type

$ sudo add-apt-repository ppa:gijzelaar/cuda
$ sudo add-apt-repository ppa:gijzelaar/opencv2.3
$ sudo apt-get update

Now, do the usual apt-get to get OpenCV. Note that the usual Ubuntu repos have a package called libcv-dev, however with the new PPA we are looking for a package called libopencv-dev.


$ sudo apt-get install libopencv-dev

This installs OpenCV on your computer. You will find the package files in /usr/include/opencv/

Now for Eclipse. You can do the usual apt-get (sudo apt-get install eclipse) to get Eclipse or you can download from the official website. I recommend the former. At the end you should have the following packages installed on your machine. ( I further recommend you install Synaptic Package Manager (sudo apt-get install synaptic) and then check for the individual packages.)


eclipse
eclipse-platform
eclipse-rcp
eclipse-platform-data
eclipse-pde
pdebuild
eclipse-cdt


Now you should be able to launch Eclipse. So do that and then create a new C or C++ project.


We shall write an introductory OpenCV program in C++ in this project, so we name the project ImageDisplay. (Note that I have created a C++ project and not a C project. While Ubuntu comes with the default gcc compiler for C, it does not have the GNU C++ compiler, g++ by default. In case you also wish to use C++ instead of C, do a sudo apt-get install g++ to install the g++ compiler on your computer).



We now have a C++ project called ImageDisplay. To enable us to use the OpenCV libraries in this project we need to include these libraries. To do that, right click on the ImageDisplay project in the Project Explorer on the left and select Properties. Go to C/C++ build in the left menu and then Settings, in the dialog box that appears.

The Configuration bar should be set to Debug [ Active ]. In the Tool Setting tab, select Directories in the GCC C++ Compiler menu and add the path

/usr/include/opencv


Now go to Libraries under GCC C++ Linker and add the libraries that you would need. Typically you would definitely need opencv_core and opencv_highgui. The other libraries that you can add are


opencv_imgproc
opencv_ml
opencv_video
opencv_features2d
opencv_calib3d
opencv_objdetect
opencv_contrib
opencv_legacy
opencv_flann


Lastly, in the Library search path, add /usr/lib.


Make sure that you add these paths and directories for the Release build as well (in the Configuration bar).


Now we are all set to write our first OpenCV program.


Before that let us once run through what all we’ve done.

  • Installed OpenCV.
  • Installed Eclipse.
  • Installed G++.
  • Created a project called ImageDisplay.
  • Configured the libraries and paths with our project.

Now for the program.


Create a file within your ImageDisplay project called main.cpp. Also, copy an image (.jpg format) to your project workspace folder. (You had set your workspace folder when you had started Eclipse. If you do not remember, then it mostly is in your home folder, and it’s called workspace. There’ll be a folder within the folder corresponding to you current project called ImageDisplay. So copy the image there. Call it image.jpg)


Double click main.cpp in the Project Explorer and write the following piece of code. If all goes well, when you compile and run this program, you should see a window and your image.jpg should be displayed in it.
Just replace the quotes in the include statements with angular brackets.


#include “cstdlib”
#include “cmath”
#include “cv.h”
#include “highgui.h”


int main(int argc, char *argv[])

{

cvNamedWindow( “Example1”, CV_WINDOW_AUTOSIZE );
IplImage* img = 0;
img=cvLoadImage(“image.jpg”);
cvShowImage(“Example1”, img );
cvWaitKey(0);
cvReleaseImage(&img );
return 0;
}

Now save this file (Ctrl+S) and compile the code (ie “build” the project with Ctrl+B). Now click on the green arrow in the Eclipse toolbar to run the code.


You should see a window pop up called Example1 and your image.jpg should be in it.

You might face an error during compile time / run time that looks something like this :

Gtk-WARNING **: Unable to locate theme engine in module_path: “pixmap”,

This is because you do not have a package in your system. To install it, just head over to the terminal and type

sudo apt-get install gtk2-engines-pixbuf

That should be it. If you face any problem reread this post again and follow it carefully. Else of course, you can drop me a mail.





Also a very Happy New Year. Why I don’t get all gaga on New Year’s can be summed up nicely in the words of Mark Twain.

New Year’s is a harmless annual institution, of no particular use to anybody save as a scapegoat for promiscuous drunks, and friendly calls, and humbug resolutions, and we wish you to enjoy it with a looseness suited to the greatness of the occasion

So there.





A Time Travel Through Incredible India

30 Dec
This and the past few posts, form the complete story of some of the most incredible things I experienced and saw during my week-long tour of Madhya Pradesh. To make it easier for you to go through, I shall index them in this pilot post, and hyperlink each place to its respective post.

  1. A Walk in a Pre-historic Park
  2. A Boat Ride through a Marble Palace
  3. Cave Paintings of the Early Man
  4. Stupas at Sanchi
  5. Muslim Palaces at Mandu

a Time Travel through Incredible India – 5 : Muslim Palaces at Mandu

30 Dec
We are all aware of the monumental standards that the Mughals set when it came to building palaces and pleasure domes for themselves – yeah, we’ve all seen the Taj Mahal, Humayun’s Tomb et al.

Now little known to many, before the Taj Mahal was designed, the architects drew inspiration from another, albeit less grander Muslim piece of architecture. That, and various other exquisite Muslim palaces and pavilions form the fifth and the closing part of my Madhya Pradesh travelogue.

We leave Bhopal and travel by road to Indore. The distance is a little less than 200 kilometers and can be covered in two-and-a-half to three hours, on a usual day.

Our place of interest is not Indore however. It is 100 kilometers south west of Indore, and this place is the ruined city of Mandu. Established in the 10th century by Raja Bhoj, it gained prominence during the Mughal rule in the Medieval Age, as the capital city of Hoshang Shah, the king of Malwa. After the Mughals however, when the Marathas shifted their capital to Dhar, the importance of the town waned.

Mandu is home to a number of beautiful Muslim palaces. The most noteworthy of them, being the Jahaj Mahal, a huge ship-like palace, positioned between two huge lakes (which still exist, but are much smaller). The Jahah Mahal was built by Hoshang Shah, as his harem, and it was meant to give a sea-like ambiance to the lady members who stayed there – with the cool wind arising from the cross-ventilation between the two lakes.

Beside the Jahaj Mahal, there is yet another exquisite palace, albeit smaller, known as Hindola Mahal, which features sloping walls on its three sides – to give the impression that the entire structure is swaying with the wind.

All these do make one wonder on the creativity of the architects in those times!

The next place that we visit is Roopmati’s pavilion – a “pavilion” that was built by Baz Bahadur, the last sultan of Malwa, for his Hindu queen – Roopmati, a singer and Rajput by birth. The pavilion was built for a specific purpose – to be a seat for the queen while she would gaze down the Narmada valley at the flowing waters of the Narmada. The pavilion is perched atop a cliff overlooking the valley – the Narmada is not visible to the naked eye, but there is a telescope that allows one to see it from the terrace.

Beside the Pavilion is the palace of the sultan Baz Bahadur himself.

The last couple of places that we visit in Mandu are the Jami Masjid, and thereafter the tomb of Hoshang Shah. This tomb of Hoshang Shah, was the structure that inspired the design of the Taj Mahal, as you shall see in the slideshow that follows.

The Masjid shows the confluence of two unique architectural patterns, the Hindu straight-cut-rectangular dharmshala style, and the second, the curve-oriented and arches of the traditional Mughal style.

https://picasaweb.google.com/s/c/bin/slideshow.swf

That was it. This is the end of the travelogue. It was an incredible learning experience for me. I hope I have been able to share most of what I felt with you.

Thank you for staying till the end.

a Time Travel through Incredible India – 4 : Stupas at Sanchi

28 Dec
This post takes us back to Bhopal and then some 60 kilometers to its north west – to Sanchi.

Everyone has heard of Sanchi. We’ve all read about it in our History books, seen the beautiful Stupas that make Sanchi so important today, in print.

Trust me when I say, the real thing is a totally different deal.


Back in the times of the Maurya Empire (circa 250 BC), when the newly found faith of Buddhism was fragmenting, a few hundred years after the death of founder Gautam Buddha, it was King Ashok who took upon himself the monumental task of propagating the religion and methodically channelising its progress.

And thus the construction of the Stupas were started. Stupas are essentially round, mound like structures, housing significant Buddhist relics; Today they are some of the most iconic historical structures of India, and with good reason. When India won her independence in 1947, Jawaharlal Nehru was quick enough to recognise the Ashokan Stupas as a aymbol of the very beginning of the existence of the Indian State. Before Ashok, India had existed physically and geographically, but the concept of a political state, stretching from present-day Kashmir to Kanyakumari, was unheard of. Ashok was the first emperor who consolidated most of the region of the present Indian subcontinent into a single political entity – and thus, this period can safely be considered to be the beginning of an Indian polity.

It was because of this, Nehru established the Ashok Stambha, the pillar-head of the oldest (southern) entrance gate to the Stupa, as the national emblem of India.

I shall stop this rant and shall provide the customary slideshow. I hope you like the pictures.

https://picasaweb.google.com/s/c/bin/slideshow.swf

The next and hopefully the last part of this travelogue shall take us to Indore, and to Mandu – the site of some beautiful Mughal architecture from Medieval India.

a Time Travel through Incredible India – 3 : Cave paintings of the early man

28 Dec
After the visual treat that was the Narmada valley, we leave Jabalpur and move on to the capital city of Madhya Pradesh – Bhopal.

Now there isn’t really much to see in Bhopal except for a couple of really huge lakes, which have given Bhopal, the name – city of lakes. However Bhopal is close to two extremely important tourist spots, both of which are important enough to have been declared as World Heritage Sites.

The first one is far less known than the second, but is equally as enchanting in a different way, and forms the content for this post. It is only 45 kilometers to the south of Bhopal, but the road conditions are bad enough to make a Humvee think twice before venturing ahead. Which affected our rattly old Chevy rather badly, for the information – resulting in two consecutive punctures.

 This place is known as the Bhimbetka, and it is home to some of the oldest cave paintings known to man. Ten thousand years or more ago, these rocks were shelters to the early man, and in his .. er … past time (?) the early man painted on the walls of these rock shelters. Overlapping and superimposition of paintings imply that these rocks were used as canvas for art by different people from different periods – from the Upper Paleolithic, through the Mesolithic and Chalcolithic periods, right up to the early historic to the very recent Medieval age.

The amazing thing about these paintings is that they weren’t etched into the stone. Rather, they were painted, and given that they were painted, it’s a wonder how the paintings haven’t fallen prey to erosion and other natural processes. In fact, recent marks made by the Archaeological Survey of India on the same stones, only 60 years back have faded and discoloured.

These rock paintings were discovered by a VS Wakankar in 1957 when he saw some unique rock formations while traveling by train. Hundreds of such rock shelters where discovered of which fifteen caves have been opened for sightseeing.

Most of these paintings depict  animals like bison, boars, horses, lions while others depict the culture of the early homo sapien, their festivals, rituals and the like. It really is marvelously, considering the fact that at this juncture in pre-history, the early man was coming out of an animal-like existence and learning the art of self expression in the form of art, that which has survived till today. I am embedding a slideshow here, do click on the slideshow and view the photos in all their glory in picasa. They really are incredible.

https://picasaweb.google.com/s/c/bin/slideshow.swf

Also, the name Bhimbetka comes from Bhima, the strongest of the Pandavas in the Mahabharata – during the Pandava’s 12 year exile, Bhim had apparently resided in this region – and hence Bhimbetka – the seat of Bhima.

That is it for this post. The next post shall take us to Sanchi, also 40 odd kilometers from Bhopal, in another direction – the home of the historic Stupas and the iconic Ashok Stambha, the national emblem of India.



a Time Travel through Incredible India – 2 : A Boat Ride through a Marble Palace

26 Dec
Our next stop takes us to Jabalpur – 227 km to the west of Amarkantak and some 70 odd km from the National Fossil Park at Ghughua – which we covered in the previous post.

There is nothing spectacularly historical or archaeological in this city – but what sets this city apart is its proximity to one of the finest river valleys in the country – that of the Narmada. We’ve all read about the Narmada in our geography books – how it’s the traditional boundary between North India and South India, and how it’s one of the few peninsular rivers to flow westwards from its source in Amarkantak (which you might recall from my previous post) to the Arabian Sea, through a valley between the Vindhyas (to its north) and the Satpura (to its south) range.

Quite close to the city of Jabalpur, is a place called Bhedaghat in the Jabalpur district of Madhya Pradesh, where the Narmada carves out a gorge through rocks made out of pure marble. And the breathtaking beauty of this marble-valley is one of the primary reasons that has helped tourism flourish in this state,

There are two ways of experiencing the marble rocks – both of which are splendid in their own unique way. The first is by taking a cable car and getting a bird’s eye view of one of the best portions of the valley – with a beautiful waterfall to boot. The second way is a 50 minute boat ride down the valley and  getting “up close and personal” with the rocks.

The boat ride through the valley revealed some beautiful natural marble “sculptures” – which are mostly figments of human imagination, humourous nevertheless when explained. I have included some of them in the slideshow below.

https://picasaweb.google.com/s/c/bin/slideshow.swf

This completes the Jabalpur chapter of this travelougue. Next up, Bhopal, and cave paintings of the early man and the iconic Ashok Stambha at the Sanchi Stupa.

a Time Travel through Incredible India – 1 : A walk in a prehistoric park

23 Dec
This is part one of a three (or more) part tour-de-excellence through MadhyaPradesh, the very heart of the Indian subcontinent.

Indeed, when I set out for this journey, little did I know that this would turnout to be one of the most incredible travelling experiences I’ve ever been on -which is a significant thing, considering that Jammu-Kashmir and Keralaare the only two states in India that I haven’t been to. So, I was bothapprehensive yet expectant of the “wonders” that I would behold inthe course of ten odd days.

 With this and the next few blog posts, I wish to recount the experiencesthat I have had in the past few days, and hope to take you, the reader down tothe very beginning of life on earth, to the roots of the present day homo sapien and some astonishingmilestones of Indian culture – which still affects our day to day life in the21st century.

Our journey begins on the road, aboard a rattly Chevrolet Tavera, atAmarkantak. Amarkantak, situated in Madhya Pradesh, close to the MP-Chattisgarhborder is home to some of the oldest Shiv temples on the planet. These are someoutstanding works of art, dating back to 1000 AD – all sculpted out of stone.One look at the temples and one is compelled to wonder at the craftsmanship ofthe artisans who toiled with pickaxes and shovels and craved these brilliantarchitectural masterpieces, which have stood the test of time and seen medievalIndian history unfold alongside them.

Amarkantak is also of geographic importance as the source of the greatNarmada, which cuts through the rich igneous rocks of the Deccan plateau,between the Vindhya and the Satpura ranges, and empties into the Arabian Sea inGujarat. Also, merely a couple of kilometers away from the source of theNarmada is the source of the Son river. What is startling is that the entirewatershed region is such, that within a couple of kilometers, the altitudevaries so much that, the Narmada flows westward  towards Gujarat, and thatthe Son flows North East-ward to join the Ganga in the great Northern Plains.

https://picasaweb.google.com/s/c/bin/slideshow.swf

Leaving Amarkantak behind us, we travel westward, towards Jabalpur -National Highway 22. We cross the two towns of Dindori and Shahpur and thencome to a fork and turn left. 14 kilometers down this road and we come to oneof the most amazing, yet little known places in India. In fact, it’s the onlysuch place that we have in our country, and even outside India, very few ofthese exist.

The National Fossil Park Park.

The National Fossil Park at Ghughua, is a rare, an extremely rare example of an entiretropical evergreen forest being petrified over millions of years – resistingall forms of biological decay while at it. Carbon dating has estimated thatthese plant fossils date back to the late Cretaceous and the early Tertiaryperiod in the geological timescale. That is more than 65 million years ago.Which is, well, a hell lot. Considering that dinosaurs had just becomeextinct then, and that the closest ancestor to the modern man was still manymillions of years away.

These fossils are predominantly of the prehistoric date palm and banana.This treasure trove of natural history was unearthed by a Dr Dharmendra Prasad,the statistical officer of the Mandla district of Madhya Pradesh, and afterrealizing the significance of this natural wonder, the Government of Indiadeclared this as a National Park in 1983.

Geological studies on the fossils excavated have proved several theories ofcontinental drift. The fact that the fossils are predominantly of evergreenplants imply that 65 million years ago, this region of India enjoyed a warmhumid climate with plenty of rainfall all year around. Also, the discovery of anumber of eucalyptus tree fossils have verified that the Deccan plateu and presentday Australia (which have eucalyptus forests to this date) shared the samelandmass – that of the ancient Gondwanaland. Seeing the fossils -million-year-old plants turned to stone – over the years – lying where theyonce stood, witnessing the evolution of planet earth happening all around them- the changing landscapes, new species appearing and dying out, the earlyprimates first learning the art of working with tools, the discovery of fire,the appearance of the first homo sapien– is exciting enough to send a shudder up one’s spine!

https://picasaweb.google.com/s/c/bin/slideshow.swf

After a surreal experience, which I’m thankful to have witnessed, we boardour rattly old Chevy and head to Jabalpur.

Part two of our journey – the enchanting marble rocks of the Narmada valleyin Jabalpur will be taken up in the next post. 🙂

walking into Mordor

22 Dec
I have been pouring over Google Maps for the past few days, for finding routes and more interesting places to visit in Madhya Pradesh. And then this idea propped in my mind – the result of which was rather hilarious.

I love these tiny Easter Eggs Google keeps planting in arbitrary places in their products. ❤

Brillaint, ain’t it? 🙂

Also, Merry Christmas to everyone.