JNI Access Violation Excetpion
Hello all,
First of all, I am very new to JNI. I was putting together a little application to test JNI, but I keep getting an AccessViolationException when trying to access a jstring in my VC++ code.
// File: TestDll.dll
using namespace System;
using namespace System::Runtime::InteropServices;
[DllImport("user32")]
extern"C"long FindWindow( String^ windowClass, String^ windowName );
JNIEXPORT jlong JNICALL Java_Main_findWindow
(JNIEnv * env, jclass, jstring className, jstring windowName)
{
long handle = 0;
try{
constchar *nativeString;
nativeString = env->GetStringUTFChars( className,false );
handle = FindWindow(gcnew String(nativeString), nullptr);// for now use windowClass only
//DON'T FORGET THIS LINE!!!
env->ReleaseStringUTFChars( className, nativeString );
}
catch( System::AccessViolationException^ e )
{
Console::WriteLine(e->ToString());
}
return handle;
}
If i remove the lines about nativeString = env->GetStringUTFChars( windowClass,false);
handle = FindWindow(gcnew String(nativeString), nullptr);
and just call FindWindow("Notepad", nullptr)
from within the method, then I get no problems.
However, I want to pass the paramters from my Java code. I made sure I compiled the header file correctly, and the Java code is correct also I believe. The files are not long, so I will post them here.
//Main.java
publicclass Main
{
static
{
System.loadLibrary ("TestDll");
}
publicstaticvoid main (String ar[])
{
System.out.println ("Notepad has handle # " + findWindow ("Notepad",null));
}
publicstaticnativelong findWindow (String className, String windowName );
}
And heres he header file used by calling javah -jni Main
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class Main */
#ifndef _Included_Main
#define _Included_Main
#ifdef __cplusplus
extern"C"{
#endif
/*
* Class:Main
* Method:findWindow
* Signature: (Ljava/lang/String;Ljava/lang/String;)J
*/
JNIEXPORT jlong JNICALL Java_Main_findWindow
(JNIEnv * env, jclass, jstring className, jstring windowName);
#ifdef __cplusplus
}
#endif
#endif
Again, I am not certain exactly what is causing the error, just that anytime I try and access one of the jstring
passed as a paramter, this exception is thrown. Here is the output from my application:
System.AccessViolationException: Attempted to read or writeprotected memory. This is often an indication that other memory is corrupt.
at JNIEnv_.GetStringUTFChars(JNIEnv_* , _jstring* str, Byte* isCopy)
at Java_Main_findWindow(JNIEnv_* env, _jclass* __unnamed001, _jstring* className, _jstring* windowName)
Notepad has handle # 0
Ugh! Just as I am writing this post, and had to run the my program one more time so that i could redirect the output to a text file for easy copy and past, IT WORKED. I dont know how or why. I changed nothing. However, I still wanna know why it was throwing the exception in the first place.
Thanks, Dale

