Calling Java from C

Up to now, we have been modeling the situation where Java drives the application. In this example, we have a C application that would like to make calls to Java methods. The "invocation API" is used to embed the Java Virtual Machine in a C program. The steps to attend to include:
  1. Use javac to produce a .class file
  2. Create a C source file that begins with #include <jni.h> (line 25)
  3. Write the C main() (lines 26-60)
  4. Compile the C source file into a .exe executable
  5. Set the PATH to include Java's run-time environment directory
  6. Run the .exe executable
Line 34 demonstrates one way to ensure that Java's CLASSPATH environment variable is correctly configured so that the Java .class file is found at run-time.

To instantiate the JVM. use JNI_CreateJavaVM() (line 44). All three argument are passed by address. The last one is an input parameter, the first two are output parameters. As before, all JNI functions are accessed via the env pointer.

Because the C code is the main() (or starting point) of this application, there is no pre-existing Java object to reference. The first order of business is to "find" the desired Java class and create an instance of that class (lines 46-48). This is just like finding and creating the "exception" object in a previous example. Then, lines 49-58 are just like the immediately preceeding example. Finally, the counterpart to JNI_CreateJavaVM() is DestroyJavaVM() (line 59).

The commands for steps 4 and 5 above are something like:

   cl JNIdemos.cpp q:\cpp\java\jdk1.2\lib\jvm.lib
   set PATH=%PATH%;q:\cpp\java\jdk1.2\jre\bin\classic
[source: Horstmann98, pp615-616]