Click here to Skip to main content
15,887,945 members
Articles / Programming Languages / Java / Java SE
Article

JNI Basics - 1

Rate me:
Please Sign up or sign in to vote.
4.19/5 (34 votes)
10 Sep 20023 min read 502.8K   82   80
Calling native functions which are written in C or C++ from Java, using JNI.

Image 1

Introduction

In this tutorial, I will try to explain how to call native functions which are written in C or C++ from Java, using JNI.

What is JNI

JNI is an acronym of Java Native Interface. Using JNI, we can call functions which are written in other languages from Java. Advantages and disadvantages of this method are as follows:

Advantages:

  1. You can use your existing library which was previously written in another language.
  2. You can call Windows API functions.
  3. For the sake of execution speed.
  4. You can call API functions of some server product which is in C or C++, from Java client.

Disadvantages:

  1. You can’t say "write once run anywhere".
  2. Difficult to debug runtime error in native code.
  3. Potential security risk.
  4. You can’t call it from Applets.

Here we will try to call the MFC function AfxMessageBox() from Java. Our function in C++ will take no arguments and will not return any value.

JavaScript
//Test1.java
class Test1
{
    static
    {
        System.loadLibrary("TestDll");
    }
    public static void main(String ar[])
    {
        System.out.println("Hello world from Java");
        Test1 t=new Test1();
        t.inDll();
    }
    public native void inDll();
}

In static block, we are loading a DLL named TestDll.dll which should be placed in <WINDIR>/SYSTEM32 directory. I am not saying you cannot put this DLL in other directories, you can, but then you will have to register that path in JVM. Here you can call another method as well, instead of loadLibrary().

JavaScript
System.load("c://winnt//system32//TestDll.dll");

I think load() method is better as far as usage is concerned because you can easily place your DLL in any directory.

JavaScript
public native void inDll();

As you can guess, this native keyword specifies that inDll() is a native function which is implemented in the library. Also noticeable, there is no implementation. When we call this function in our code, JVM will look for the function in the loaded DLL (due to static block, DLL will be loaded immediately after the loading of the class) and then call that function. Otherwise it will throw java.lang.UnsatisfiedLinkError exception.

Compile this class normally. Now we will need to generate header file of this class.

You can use javah.exe utility which is included with JDK.

Javah -jni Test1

Header file is generated in current directory with the name Test1.h. Keep this header file safe as we will use this soon.

Now we are going to write a DLL which will contain the implementation of our native function. I have chosen MFC AppWizard (DLL) in project and named my project: TestDll.

Include your class header file which was generated previously using javah.exe in TestDll.h.

Copy following line from Test1.h and paste it at the end of TestDll.h.

JavaScript
JNIEXPORT void JNICALL Java_Test1_inDll(JNIEnv *, jobject);

Change this line to:

JavaScript
JNIEXPORT void JNICALL Java_Test1_inDll(JNIEnv *env, jobject obj)
{
    AfxMessageBox("Hello World from dll");
}

Compile this DLL, you will get an error from compiler because compiler was unable to find jni.h file which is included in Test1.h. So include the following two directories in IDE settings.

  • <Drive>:\<JDK Directory>\include
  • <Drive>:\<JDK Directory>\include\win32

Go to Project/Settings, on C/C++ tab, go to Project option, insert following lines at the end:

/I "<Drive>:\<JDK Directory>\include "
/I "<Drive>:\<JDK Directory>\include\win32"

Now compile and generate your DLL, put newly created DLL in system32 directory and then run your class file. It should work properly. If you receive an error like UnsatisfiedLinkError, then recheck your procedure. If you are using any IDE, then try using command prompt. Hope it will work.

In this tutorial, I have tried to explain the basics of JNI. I will write a second tutorial of the series soon in which I will explain how to pass parameters to native functions and return something, along with a practical example.

Waiting for your comments and questions.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
Pakistan Pakistan
Irfan Dawood is the junior year student at Department of Computer Science, University of Karachi. His interest includes programming in C++ and Java.

Comments and Discussions

 
GeneralDebug DLL File Pin
lvguangchuan18-Oct-05 10:17
lvguangchuan18-Oct-05 10:17 
GeneralHelp me in solving Unsatisfiedlinkerror! Pin
Anonymous17-Aug-05 0:00
Anonymous17-Aug-05 0:00 
GeneralRe: Help me in solving Unsatisfiedlinkerror! Pin
Yanaisama26-Dec-06 5:31
Yanaisama26-Dec-06 5:31 
GeneralRe: Help me in solving Unsatisfiedlinkerror! Pin
ravindra.java10-Apr-07 22:09
ravindra.java10-Apr-07 22:09 
Generalwithout JNI Pin
heinrichrohwer7-Jul-05 4:22
heinrichrohwer7-Jul-05 4:22 
Questioncan java access VB.NET .dlls? Pin
Abhishek Tiwari8-Apr-05 22:47
Abhishek Tiwari8-Apr-05 22:47 
AnswerRe: can java access VB.NET .dlls? Pin
Anonymous24-May-05 3:44
Anonymous24-May-05 3:44 
GeneralRe: can java access VB.NET .dlls? Pin
Abhishek Tiwari24-May-05 21:33
Abhishek Tiwari24-May-05 21:33 
hi, thanks for the rude reply. you did not concentrate on what i mentioned in the message.

My research was on java packet sniffers., and it turned out to be useless. Take my words for granted. If in this life it is possible for you build a packet sniffer in "pure java", do tell me and before i am too old to work on computers. My friend, java is bullshit for network programming, and you will know it when you understand the concepts of packet sniffing. I am not just a programmer. I have ample understanding of the networks.

This is why I specially mentioned that java does not have such low level API's. whatever you find on the net is the real native Dll working behind the scene, and the stupid java calling functions from the DLL ad display the result.
If this is what you call the power of java, you must better read the previous 2 lines again.

as for the solution you gave, its just the same i mentioned in my message. IT MUST BE DONE BY SOME OTHER AGENT, be it .NET Dll or c/c++ Dll. your answer says the same story and its no great idea.

You might call it a solution, I call it a serious issue with java. For networks, java is useless and cannot stand on its own feet. Take my words on this, and consult anyone you know is a java guru.

Go to SUN's website and know the truth, and please read before you reply.

regarding getting no. of solutions, its google's nature, just browse through them and see if you find anything useful.

I know this hurts you, but your mail did the same to me.
things are even. don't keep any hard feelings.

regards
Abhishek

GeneralBufferedImage to vtkSource Pin
Pythonian29-Mar-05 21:08
Pythonian29-Mar-05 21:08 
GeneralJava code executed before nattive Pin
User 172888422-Feb-05 0:22
User 172888422-Feb-05 0:22 
GeneralRe: Java code executed before nattive Pin
Anonymous14-Sep-05 13:47
Anonymous14-Sep-05 13:47 
GeneralRe: Java code executed before nattive Pin
pickson20-Mar-07 4:08
pickson20-Mar-07 4:08 
GeneralError in javah Pin
Lucas Ferst29-Oct-04 7:01
sussLucas Ferst29-Oct-04 7:01 
GeneralRe: Error in javah Pin
jan larsen8-Nov-04 21:50
jan larsen8-Nov-04 21:50 
GeneralExcecution an EXE file Pin
hashmi12-Apr-04 23:01
hashmi12-Apr-04 23:01 
GeneralJava with OPenGl Pin
prabu_univ2-Mar-04 20:55
prabu_univ2-Mar-04 20:55 
GeneralRe: Java with OPenGl Pin
Anonymous24-May-04 23:36
Anonymous24-May-04 23:36 
Generalcodeproject for Java Pin
Edelweiss18-Dec-03 6:46
Edelweiss18-Dec-03 6:46 
GeneralRe: codeproject for Java Pin
Anonymous13-Jan-04 3:08
Anonymous13-Jan-04 3:08 
GeneralCalling Java from cpp Pin
Anonymous16-Dec-03 20:17
Anonymous16-Dec-03 20:17 
GeneralRe: Calling Java from cpp Pin
Anonymous29-Dec-03 22:34
Anonymous29-Dec-03 22:34 
GeneralRe: Calling Java from cpp Pin
Anonymous21-Mar-04 15:06
Anonymous21-Mar-04 15:06 
GeneralRe: Calling Java from cpp Pin
maycol18-Aug-04 10:37
maycol18-Aug-04 10:37 
GeneralIt does not work for me Pin
Wilfried_Garnier29-May-03 7:50
Wilfried_Garnier29-May-03 7:50 
GeneralRe: It does not work for me Pin
jan larsen8-Nov-04 21:58
jan larsen8-Nov-04 21:58 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.