Symbian
Symbian OS Library

FAQ-0275 How do I convert a Java string to an 8-bit descriptor?

[Index][spacer] [Previous] [Next]



 

Classification: Java Category: JNI
Created: 09/23/99 Modified: 09/17/2001
Number: FAQ-0275
Platform: Not Applicable

Question:
I have a native function called from Java through the JNI mechanism which receives a java.lang.String as one of its parameters. How do I convert that string to an EPOC 8-bit descriptor?

Answer:
The java.lang.String would be received on the native side as a jstring. You would do something like the following.
/*
* Class: Example
* Method: _native
* Signature: (Ljava/lang/String;)I
*/

JNIEXPORT jint JNICALL Java_Example__1native(JNIEnv* aJNI, jclass, jstring aFile)
{
const char* const ptr=aJNI->GetStringUTFChars(aFile,NULL); // #1
TPtrC8 file(REINTERPRET_CAST(const TUint8*,ptr),aJNI->GetStringUTFLength(aFile)); // #2
jint error=NativeStuff(file);
aJNI->ReleaseStringUTFChars(aFile,ptr); // #3
return error;
}

Notes:


    1. The GetStringUTFChars() method returns a pointer to an array of the UTF-8 characters of the string. The second parameter being NULL indicates you are not concerned whether the array is a copy or not. It is best to declare the pointer as const char* const to help forestall any attempt to modify the Java string in place.

    2. The REINTERPRET_CAST is necessary because char* is signed data whereas the constructors for EPOC descriptors require unsigned data. If you wanted to go on and modify the string, you would copy it to a TBuf8 at this point.

    3. After use has been made of the pointer to the Java UTF-8 data, the memory used by the array needs to be freed up for Java garbage collection through calling the ReleaseStringUTFChars() method. Failure to do this will result in a memory leak.

    4. For further details about standard JNI methods see http://java.sun.com/products/jdk/1.2/docs/guide/jni/spec/jniTOC.doc.html