Search code examples
javac++mfcjava-native-interface

Unable to use JNI when enabled from within Win32/MFC application


I'm trying to use Java functions from within a Visual C++ application by availing of the Java Native Interface, but am not having much luck.

I'm calling the code in a button click handler function within a CDialog, and I get as far as trying to create a Java VM instance and my application throws an access violation exception: "Unhandled exception at 0x0F7D260A (mfc120u.dll) in MyApp.exe: 0xC0000005: Access violation reading location 0xFEEEFF26." However, when I put my code into a skeleton C++ app containing just a main() function, it all works fine.

As far as I can tell, I've set my project up correctly in Visual Studio 2013. I'm including jni.h from the include directory in my JDK folder, and I'm linking against jvm.lib contained inside my JDK lib folder. I'm using JDK 1.8.0_91 as well.

For what it's worth, here is the code:

JNIEnv *env = NULL;
JavaVM *jvm = NULL;
jint res;
  // Initialization arguments
JavaVMInitArgs vm_args;
memset(&vm_args, 0, sizeof(vm_args));

JavaVMOption options[3];
memset(&options, 0, sizeof(options));

options[0].optionString = "-Djava.class.path=C:/";
options[1].optionString = "-Xms128m"; // 128MB initial heap size
options[2].optionString = "-Xmx1g"; // 1GB maximum heap size

vm_args.version = JNI_VERSION_1_8;
vm_args.nOptions = 3;
vm_args.options = options;
vm_args.ignoreUnrecognized = JNI_TRUE;
jint status = JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args);

Any help would be most appreciated


Solution

  • In the end, I figured this out. Apparently the JNI throws exceptions on startup by design to verify the environment it's running in. See Exception 0xC0000005 from JNI_CreateJavaVM (jvm.dll).

    When I disabled the particular exception in Win32 exceptions in visual studio , it all works fine.