The moose likes Other JSE/JEE APIs and the fly likes Invoking JVM through C++ code Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Other JSE/JEE APIs
Bookmark "Invoking JVM through C++ code" Watch "Invoking JVM through C++ code" New topic

Invoking JVM through C++ code

sachin kale

Joined: Sep 22, 2005
Posts: 2
I am trying to invoke the JVM using JNI.

The C++ code compiles & links properly(It shouts after removing jvm.dll from path). However it gives an error message after executing it.

Error message is : Can't create java VM. It returns -1 which is defined as JNI_ERR i.e. unknown error in JNI.h. I had tried on both versions of java SDK 1.3 & 1.2.2. Can any body please explain me what may be the problem ?

These are steps that we are following to create the JVM :
1) JNI_CreateJavaVM(): - It returns the Java VM pointer through return parameter. Method return 0 for successfull creation -1 for failure(debugging I recieve -1) . (This �JNI_CreateJavaVM()� method is in �jni.h�) 2)Calling class methods. 3) DestroyJavaVM():- on Java VM pointer.

Thanks in advance !!!

This is the program:
#include <jni.h>

#define PATH_SEPARATOR ';' /* define it to be ':' on Solaris */
#define USER_CLASSPATH "." /* where Prog.class is */

main() {
JNIEnv *env;
JavaVM *jvm;
jint res;
jclass cls;
jmethodID mid;
jstring jstr;
jclass stringClass;
jobjectArray args;

#ifdef JNI_VERSION_1_2
JavaVMInitArgs vm_args;
JavaVMOption options[1];
options[0].optionString =
"-Djava.class.path=" USER_CLASSPATH;
vm_args.version = 0x00010002;
vm_args.options = options;
vm_args.nOptions = 1;
vm_args.ignoreUnrecognized = JNI_TRUE;
/* Create the Java VM */
res = JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args);
JDK1_1InitArgs vm_args;
char classpath[1024];
vm_args.version = 0x00010001;
/* Append USER_CLASSPATH to the default system class path */
sprintf(classpath, "%s%c%s",
vm_args.classpath = classpath;
/* Create the Java VM */
res = JNI_CreateJavaVM(&jvm, &env, &vm_args);
#endif /* JNI_VERSION_1_2 */

if (res < 0) {
fprintf(stderr, "Can't create Java VM\n");
cls = (*env)->FindClass(env, "Prog");
if (cls == NULL) {
goto destroy;

mid = (*env)->GetStaticMethodID(env, cls, "main",
"([Ljava/lang/String V");
if (mid == NULL) {
goto destroy;
jstr = (*env)->NewStringUTF(env, " from C!");
if (jstr == NULL) {
goto destroy;
stringClass = (*env)->FindClass(env, "java/lang/String");
args = (*env)->NewObjectArray(env, 1, stringClass, jstr);
if (args == NULL) {
goto destroy;
(*env)->CallStaticVoidMethod(env, cls, mid, args);

if ((*env)->ExceptionOccurred(env)) {

[ September 22, 2005: Message edited by: sachin kale ]
[ September 25, 2005: Message edited by: sachin kale ]
Vitaly Shelest

Joined: Sep 28, 2005
Posts: 4
Try the tool at
I agree. Here's the link:
subject: Invoking JVM through C++ code
It's not a secret anymore!