Click here to Skip to main content
5,787,682 members and growing! (20,884 online)
Email Password   helpLost your password?
Languages » Java » Beginners     Beginner

JNI Basics - 1

By Irfan Dawood

Calling native functions which are written in C or C++ from Java, using JNI.
Java, VC6, VC7, C++, Java, Windows, NT4, Win2K, WinXP, Visual Studio, Dev

Posted: 10 Sep 2002
Updated: 10 Sep 2002
Views: 201,858
Bookmarked: 56 times
Announcements
Loading...



Search    
Advanced Search
Sitemap
29 votes for this Article.
Popularity: 6.12 Rating: 4.18 out of 5
0 votes, 0.0%
1
0 votes, 0.0%
2
4 votes, 14.3%
3
11 votes, 39.3%
4
13 votes, 46.4%
5

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.

//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().

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.

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.

JNIEXPORT void JNICALL Java_Test1_inDll(JNIEnv *, jobject);

Change this line to:

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

About the Author

Irfan Dawood


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

Other popular Java articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 25 of 68 (Total in Forum: 68) (Refresh)FirstPrevNext
QuestionJNI problem helpmembergmour8:03 1 Dec '08  
Generalit finally works. Good.memberPeter, Chan22:33 30 Oct '08  
QuestionCalling java functions from c++memberAnkush M Gupta3:06 19 Oct '08  
AnswerRe: Calling java functions from c++membersaikrishna3500:15 20 Oct '08  
GeneralRe: But HowmemberAnkush M Gupta0:22 20 Oct '08  
GeneralExcept dll, others?memberyulin1117:56 3 Oct '08  
QuestionReading .lib filemembersharad thute1:58 1 Jul '08  
QuestionHow to call a DLL developed in C++ without re-Implimentation?memberyasirqau21:47 9 Apr '08  
GeneralCan I call .dll from Java Web App.(JSP, struts)memberjiraiya11723:53 7 Aug '07  
GeneralNon native (JNI less) access to COMmemberVikram RoopChand23:28 30 Jun '07  
GeneralMake it workedmemberbrofirdaus16:34 28 Jun '07  
GeneralRe: Make it workedmemberOLEDB_Novice5:09 9 Aug '07  
GeneralRe: Make it workedmemberOLEDB_Novice5:18 9 Aug '07  
GeneralC++ application to Java using JNImemberbrofirdaus17:49 24 Jun '07  
Generalpassing objects in jnimemberkatri1:53 23 Mar '07  
GeneralRe: passing objects in jnimemberK.M.Hussain6:13 23 Mar '07  
Questionsome problemmember23:18 23 Feb '07  
Generalhelpfulmembersheniss2:29 13 Oct '06  
Questionhelp me out JNI problemmembergood64:54 1 Aug '06  
GeneralUsing Visual Studio 2005memberWiseHacker16:52 14 Jun '06  
GeneralRe: Using Visual Studio 2005memberCodeKayak12:48 22 Nov '06  
GeneralRe: Using Visual Studio 2005memberfish.soluble7:23 22 Feb '07  
GeneralRe: Using Visual Studio 2005memberthebigandroid12:33 13 May '08  
Generalsupermarket simulationmembermccleon7:35 3 Mar '06  
Generalthe client retreive info from the server by pressing a button in javamembermccleon7:31 3 Mar '06  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 10 Sep 2002
Editor: Smitha Vijayan
Copyright 2002 by Irfan Dawood
Everything else Copyright © CodeProject, 1999-2009
Web15 | Advertise on the Code Project