Java Reference
In-Depth Information
JNI lets you add Java to legacy code. That can be useful for a variety of purposes and lets
you treat Java code as an extension language (just define or find an interface or class like
Ap-
plet
or
Servlet
, and let your customers implement it or subclass it).
The code in
Example 24-12
takes a class name from the command line, starts up the JVM,
and calls the
main()
method in the class.
Example 24-12. Calling Java from C
/*
* This is a C program that calls Java code.
* This could be used as a model for building Java into an
* existing application as an extention language, for example.
*/
#include <stdio.h>
#include <jni.h>
int
int
main
(
int
int
argc
,
char
char
*
argv
[]) {
int
int
i
;
JavaVM
*
jvm
;
/* The Java VM we will use */
JNIEnv
*
myEnv
;
/* pointer to native environment */
JDK1_1InitArgs jvmArgs
;
/* JNI initialization arguments */
jclass myClass
,
stringClass
;
/* pointer to the class type */
jmethodID myMethod
;
/* pointer to the main() method */
jarray args
;
/* becomes an array of Strings */
jthrowable tossed
;
/* Exception object, if we get one. */
JNI_GetDefaultJavaVMInitArgs
(
&
jvmArgs
);
/* set up the argument pointer */
/* Could change values now, like: jvmArgs.classpath = ...; */
/* initialize the JVM! */
iif
(
JNI_CreateJavaVM
(
&
jvm
,
&
myEnv
,
&
jvmArgs
)
<
0
) {
fprintf
(
stderr
,
"CreateJVM failed\\n"
);
exit
(
1
);
}
/* find the class named in argv[1] */
iif
((
myClass
=
(
*
myEnv
)
->
FindClass
(
myEnv
,
argv
[
1
]))
==
NULL
) {
fprintf
(
stderr
,
"FindClass %s failed\\n"
,
argv
[
1
]);
exit
(
1
);
}
/* find the static void main(String[]) method of that class */
myMethod
=
(
*
myEnv
)
->
GetStaticMethodID
(