Search code examples
javac++java-native-interface

How to set a field from C++ to Java, using JNI


I have a java class:

public class LibClass
{
    public static String receivedValue;
    ...native methods...
}

Then in the c++ code, I want to set the value of the String from C++. I don't want to create new objects, I just want to assign a value to the String.

In C++ I have this so far:

JNIEXPORT void JNICALL Java_com_aries_LibClass_singleCallback
  (JNIEnv *env, jclass clz, jstring value)
{
    jclass clazz = (env)->FindClass("com/aries/LibClass");

}

I'm looking for something like (env)->SetObjectArrayElement but for Strings.

Is this possible, and if so, how?

Thanks


Solution

  • You will need methods "GetStaticFieldID()" and "SetStaticObjectField()". A Java String is just an object. (I assume you know how to create a Java String from a native string).

    See Accessing Static Fields in the JNI documentation.

    Edit: sample C (not C++) code (error checking omitted)

    jstring str;
    JNIEnv *env;
    jclass clazz;
    jfieldID fid;
    
    // initialize str and env here ...
    
    clazz = (*env)->FindClass(env, "my/package/MyClass");
    fid = (*env)->GetStaticFieldID(env, clazz , "myField", "Ljava/lang/String;");
    (*env)->SetStaticObjectField(env, clazz, fid, str);