Monday, February 23, 2009

SOA Live Demo - JNI

This article focuses on how to connect a C++ Dynamic Link Library to a Java program using the Java Native Interface. To run a C++ function in a Java program, we would require the C++ function to be in a DLL and this DLL to be loaded at run-time into the memory by the Java program.

Load the library from the Java program using the full path with the load function or let the JVM load the DLL using the system path with the loadLibrary function.

The C++ function is declared native in the Java program. Compile the file to generate the class file using the javac command.

Create a C++ header for the native function using the javah command on the generated class file. A declaration for the function is generated following the syntax java_<class>_<function>.

Create a new project to generate the DLL in Visual C++. The project consists of the header generated from the previous step, a C++ file using the function declaration generated in the header and a header consisting of the required function that is to be used in the Java program. A DLL is generated from this project.

Any C++ application can be created normally which uses the existing function.

Copy the DLL generated from Visual Studio to the path specified in the Java application and run the Java program using the java command.

As a result, the same function was used in a C++ program as well as in a Java program.

About Me

I have done my Engineering from Osmania University and am currently working as a Senior Software Developer at McGraw-Hill Financials. I previously worked as a Technical Evangelist (Campus Ambassador) at Sun Microsystems while I was doing my Engineering.