JNI, Visual C/C++ and malloc...How to release/free memory...

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

,jobjectljavaClass

){

size_ti;

wchar_tlbufInfo[INFO_BUFFER_SIZE];

DWORDllngCount = 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

[2845 byte] By [adym-lincolna] at [2007-11-27 11:33:51]
# 1

>

> My question is, how do I release/free up the char* I

> created with malloc?

>

Using the free() method.

> I've tried a couple of different ways, see commented

> code before the return statement, but nothing seems

> to work.

You must

1. Get the java result

2. Free the buffer

3. Return the java result.

jschella at 2007-7-29 16:53:49 > top of Java-index,Java HotSpot Virtual Machine,Specifications...