Invocation: Returning a string

Suppose I have a function that:

1. Takes an input string.

2. Uses Java (via Invocation) to calculate a jstring.

3. Converts the jstring to a a UTF string.

4. Returns the UTF string.

Like this (a JNIRef is a structure with references to classes and methods):

char *f( JNIEnv *env, JNIRef *j,char *strInput )

{

jstring jstrInput, jstrOutput;

char*strOutput;

jstrInput = (*env)->NewStringUTF( env, strInput );

CHECK_FOR_NULL(jstrInput);

// Do the calculation

jstrOutput = (jstring) (*env)->CallStaticObjectMethod(env,j->class,j->method,jstrInput);

CHECK_FOR_NULL(jstrOutput);

strOutput = (*env)->GetStringUTFChars( env, strOutput, NULL );

CHECK_FOR_NULL(strOutput);

return strOutput;

}

I'm leaking memory because I'm not releasing the string that GetStringUTF() generated, aren't I?

If I am leaking memory, what's the best way of doing something like this? I was thinking

something along the lines of (untested):

char *f( JNIEnv *env, JNIRef *j,char *strInput )

{

jstring jstrInput, jstrOutput;

char*strOutput;

jstrInput = (*env)->NewStringUTF( env, strInput );

CHECK_FOR_NULL(jstrInput);

// Do the calculation

jstrOutput = (jstring) (*env)->CallStaticObjectMethod(env,j->class,j->method,jstrInput);

CHECK_FOR_NULL(jstrOutput);

strOutput = (*env)->GetStringUTFChars( env, strOutput, NULL );

CHECK_FOR_NULL(strOutput);

char returnStr = strdup( strOutput );

CHECK_FOR_NULL(returnStr);

env->ReleaseStringUTFChars(jstrOutput, strOutput);

return returnStr;

}

As long as the caller free()'s the returnStr, is this safe?

[2248 byte] By [caffeinea] at [2007-11-26 16:00:12]
# 1

The answer is "yes".

However, once call GetStringUTFChars( env, strOutput, NULL ), you can no longer return strOutput; it gets mangled. I think it gets deallocated.

So you have to use strdup to create a copy of the string, release strOutput and jstrOutput, and then return the strdup copy.

caffeinea at 2007-7-8 22:21:32 > top of Java-index,Java HotSpot Virtual Machine,Specifications...