TooManyEduardos
TooManyEduardos

Reputation: 4404

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

Upvotes: 0

Views: 5441

Answers (2)

user2543253
user2543253

Reputation: 2173

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);

Upvotes: 4

Sergey
Sergey

Reputation: 41

Do you already check http://journals.ecs.soton.ac.uk/java/tutorial/native1.1/implementing/method.html ? P.S. The second argument of singleCallback should probably be jobject type (this).

Upvotes: 0

Related Questions