[ Help | Solution | Course Notes | Exercises ]


Simple Native Call

The Problem

Implement a function in C++ that can be called from Java code. The function is a trivial function that calculates the area of a circle, given its radius. The important aspect of this exercise is not the calculation itself but, rather, the techniques used in communicating with the C++ code. All JNI programs use these techniques to some extent.

Task list

  1. Task #1. Create a java class that will declare the native method, calculateAreaOfCircle. For this exercise, name the java class MathFuncs and name the shared library MathFuncsImp, implying that this class and shared library could be extended later to support other math-related methods.

  2. Task #2. Create another java class that will be used to test the native method. Name this class Main. It should have a public static void main method from which the native method will be invoked.

  3. Task #3. Compile the java files with javac.

  4. Task #4. Create the C/C++ header file MathFuncs.h with javah.

  5. Task #5. Implement the native method in C++. Name this file MathFuncs.cpp (or MathFuncs.C, depending on which extension your compiler accepts.)

  6. Task #6. Compile the C++ file and make a shared library.

  7. Task #7. Test the program by running the java interpreter.

Step-by-step

The above task numbers are linked to the help page. Also available is the complete solution of the exercise including. With the solution, you will also find sample scripts to build and execute the program under Windows NT, Solaris and Linux.

Copyright © 1998 Sergio Antoy. All Rights Reserved
February 99, version 020199