recipe № 009

passing java.lang.String value from Java to C

In this sample we will pass String into C code from Java. After you finish this tutorial, you should end up with the directory structure similar to this one

First of all, we need a Java class that will call native code. That’s fairly simple

As you can see, we are passing object here. This is something different comparing to passing int, byte, boolean, etc. First of all, pay attention to native code declaration. We will pass java.lang.String, but inside C, we won’t be able to use it the same way we do in Java. We will “convert” it to C based string.

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

After header is created

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 two functions:

GetStringUTFChars(…);
ReleaseStringUTFChars(…);

First function converts string from Java object to const char* based string.You have to call both functions each time you use strings. GetStringUTFChars to get the string, ReleaseStringUTFChars to release it whenever you decide that it will no longer be used in your code. After getting bytes of the string, we can use it as a regular, char* based, zero terminated string in C flavor.

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, we can read what was passed to native code as it was written to stdout. And that’s what we wanted to get.