recipe № 010

passing java.lang.String value from C to Java

In this sample, we will pass java.lang.String value from C to Java. Inside C code we will create zero terminated, char * based string and we will convert it into java.lang.String. After you end this tutorial, you should end up with structure similar to this one.

First of all, we need a Java class that will call native code. In this case we will introduce few changes.

As you can see, we are expecting object as a function call. We expect, to be precise, java.lang.String. Of course, inside C we are not able to use it directly, that’s why we have to convert C based string into Java based one.

Again, we have to compile the class and create native’s code header.

After this call, header is created

Note, that this time, we don’t have anything else apart from JNIEnv * and jclass as function call. This time, we don’t pass anything from our Java code.

Note that jstring will represent different structure in C and C++. You can always refer to ${JAVA_HOME}/include/jni.h

Now, we can generate implementation of the function. Pay attention to the code.

Notice the call to:

NewStringUTF(…);

This function will create jstring object that will be passed back to Java.

Compilation is plain and simple

After all elements are in place, all we have to do is to run the sample

As you can see, Java code produced on the stdout string that was declared inside C.