Hi folks,
Not sure whether this is a Windows forum question or not. I'm writing some simple JNI methods that call into Windows OS routines such as GetComputerName and GetSystemDirectory. The following is a sample method I've written that currently works:
JNIEXPORT jstring JNICALL Java_org_adym_MSInfoXample001_getComputerName (
JNIEnv * ljvmEnv
,jobject ljavaClass
) {
size_t i;
wchar_t lbufInfo[INFO_BUFFER_SIZE];
DWORD llngCount = INFO_BUFFER_SIZE;
char *lbufConverted = (char *)malloc( INFO_BUFFER_SIZE );
// Get and display the name of the computer.
//
llngCount = INFO_BUFFER_SIZE;
if( !GetComputerName( lbufInfo, &llngCount ) ) {
printf( "GetComputerName Failed!!!\n" );
}
// Convert the string...
//
wcstombs_s (
&i
,lbufConverted
,(size_t)INFO_BUFFER_SIZE
,lbufInfo
,(size_t)INFO_BUFFER_SIZE
);
// Free multibyte character buffer
//if ( lbufConverted ) {
// free( lbufConverted );
//}
//ljvmEnv->ReleaseStringUTFChars( lbufConverted, str );
return ljvmEnv->NewStringUTF( lbufConverted );
}
I got the conversion code off the M$ website as an example of how to use the wcstombs_s() function. The only way to interface with these types of OS functions is with a TCHAR or wchar_t. From other post in other forums, the newer (supported) way is wchar_t. Then I needed to convert those wchar_t strings over to char* in order to pass them back to Java. My C/C++ is rusty, especially with regards to Windows...In fact, I've never really written C/C++ to Windows before.
My question is, how do I release/free up the char* I created with malloc?
I've tried a couple of different ways, see commented code before the return statement, but nothing seems to work. If I use the free() before the return, I get garbage on the Java side...no big surprise there. The other ReleaseStringUTFChars() function call I haven't tried, only because I can't really see calling it "before" the call to NewStringUTF()...
Any help would be appreciated...
P.S. If you know a better way to do the conversion please tell me...I'm open to any kind of help at this point.
tia,
adym