AttachCurrentThread

I'm using the code below.

I successfully create a JVM the first time this is called. And the second time ( and every subsequent time ) this method is invoked, it displays that there is 1 JVM found, but the line:

jint attached = jvm->AttachCurrentThread( (void**)&env, &thr_args );

always returns 0. And when I try to find a class using the env variable it comes back NULL ( although, when first creating the JVM the FindClass method DOES find my class as desired).

Any thoughts ideas would be greatly appreciated.

JavaVM *jvm;

JNIEnv *env;

jint res;

jclass cls;

if ( nVMs == 0 ) {

fprintf(stderr, "No VMs created yet. Creating one now");

JavaVMInitArgs vm_args;

JavaVMOption options[1];

options[0].optionString = "-Djava.class.path=c:/WH";

vm_args.version = JNI_VERSION_1_4;

vm_args.options = options;

vm_args.nOptions = 1;

res = JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args);

if (res < 0) {

fprintf(stderr, "Can't create Java VM\n");

fprintf(stderr, "res:%ld", res );

} else {

fprintf(stderr, "VM created.");

}

if (env->ExceptionOccurred()) {

env->ExceptionDescribe();

}

} else {

JavaVMAttachArgs thr_args;

thr_args.version = JNI_VERSION_1_4;

jint attached = jvm->AttachCurrentThread( (void**)&env, &thr_args );

fprintf(stderr, "AttachCurrentThread: %i", attached);

}

fprintf(stderr, "FindClass com/test/TestMe\n");

cls = env->FindClass("com/test/TestMe");

if (cls == NULL) {

fprintf( stderr, "FindClass returned null ?!?" );

goto destroy;

}

fprintf( stderr, "Found Class !");

Output:

vmError = 0

nVMs = 0

No VMs created yet. Creating one now

VM created.

FindClass com/test/TestMe

Found Class !

vmError = 0

nVMs = 1

AttachCurrentThread: 0

FindClass com/test/TestMe

FindClass returned null ?!?

[2065 byte] By [MikePrettia] at [2007-10-3 11:50:10]
# 1
Your code is somewhat obscure about exactly where you defined the environment and the JVM. Are they globals?
bschauwejavaa at 2007-7-15 14:23:52 > top of Java-index,Java HotSpot Virtual Machine,Specifications...
# 2
You can attach the current thread as followsjvm->AttachCurrentThread( reinterpret_cast<void**>( &env), NULL );
vitallisa at 2007-7-15 14:23:52 > top of Java-index,Java HotSpot Virtual Machine,Specifications...