[ Help | Solution | Course Notes | Exercises ]


Calling a Java Method from Native Code

The Problem

In this exercise, we will declare two print methods in a Java class. One print method, which will be named printStringNative, will be a native method implemented in C++. The other method will be named printStringJava and will be implemented in the Java class. Both methods are void methods that take a String as their only argument. The string argument is what will be printed.

The twist in this exercise is that the native method will not simply call the C/C++ function printf or cout, but will instead call the printStringJava method that we will implement in Java.

Task list

  1. Task #1. Create a java class that will declare the native method, printStringNative. For this exercise, name the java class PrintFuncs and name the shared library PrintFuncsImp. This class should also implement the public method printStringJava which will take a String as a parameter and print it to the screen. PrintFuncs.skel can be used as a starting point. (Expand comments of the form "//+")

  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. Main.skel can be used as a starting point. (Expand comments of the form "//+")

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

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

  5. Task #5. Implement the native method in C++. Name this file PrintFuncs.cpp (or PrintFuncs.C, depending on which extension your compiler accepts.) The C++ function should be named printStringNative and it should take a Java string as a parameter. To print the string, the function should call printStringJava that you implemented in PrintFuncs.java. PrintFuncsImp.skel can be used as a starting point. (Expand comments of the form "//+".)

  6. Task #6. Compile the C++ file and create 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. 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