2 messages in net.java.dev.jna.users[jna-users] Re: question ofr memory l...
FromSent OnAttachments
Timothy WallJul 28, 2008 7:09 am 
Timothy WallJul 28, 2008 7:55 am 
Actions with this message:
Paste this link in email or IM:
Paste this link in email or IM:
Atom feed for this thread
Paste this URL into your reader:
Subject:[jna-users] Re: question ofr memory leak of JNAActions...
From:Timothy Wall (twal@dev.java.net)
Date:Jul 28, 2008 7:55:30 am
List:net.java.dev.jna.users

Please redirect replies to use@jna.dev.java.net.

On Jul 28, 2008, at 10:24 AM, Jiang (EXT), Hongyi wrote:

Thank you for your answer. That means I have write two functions in C ++ and Java like: C++ DLL side char * _stdcall encrypt(char * cipherText) { ...... char * decipherText = new char[length]; ..... return decipherText; }

extern "C" void _stdcall free_array(void *arrayp) { delete[] arrayp; }

Java side: Pointer decrypt(byte[] cypherText); void free_array(Pointer p);

I think, I have to export these two functions in DLL, therefore I use _stdcall for two functions. Are all the statements correct?

Regards Hongyi

-----Original Message----- From: Timothy Wall [mailto:twal@dev.java.net] Sent: 2008年7月28日 16:10 To: Jiang (EXT), Hongyi Cc: use@jna.dev.java.net Subject: Re: question ofr memory leak of JNA

On Jul 28, 2008, at 9:14 AM, Jiang (EXT), Hongyi wrote:

I have a question concerning memory release in JNA. E.g. I have a function in Java and C++ as follows:

C++ function of DLL: char * encrypt(char * cipherText) { int length = strlen(cipherText) + 5; //increase length char * decipherText = new char[length]; strcpy(decipherText, cipherText); for(int i = strlen(cipherText); i < length; i++) decipherText[i] = ' '; decipherText[length - 1] = '¥0'; encrptText(decipherText, "Sessionkey"); return decipherText;

}

Java interface: String decrypt(byte[] cipherText);

Because the encrypt function in c++ can only encrypt 16bit, I have to extend the 11 bit cipherText to 16 with blank space.

Question 1: is the declaration of Java interface correct? Question 2: in C++ function, I have created memory with "new" keyword, how can I release it to avoid memory leak?

Yes, the code as you've written it will leak. Whenever a native function returns a pointer to allocated memory, you need to capture that value in a Pointer so that you can later pass it to a complementary "free" routine.

// Java Pointer decrypt(byte[] cypherText); // Use Pointer.getString(0) to convert to String void free_array(Pointer p);

// C++ extern "C" void free_array(void *arrayp) { delete[] arrayp; }