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;
}