Search code examples
androidandroid-ndkjava-native-interfacendk-build

Modify value of String in JNI NDK


i have an int a = 20 in my java code

    public int a = 20 ;

then i had declared ndk & java native interface in my project witch can change value of int a = 20 to a= 100 , means that my native code change int a = 20 to 100 ;

    static {
    System.loadLibrary("native-lib");
}
public static native void myfunction (MyChangeActivity mclass);

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my_change);

    myfunction(this);

here is the c++ code id written

JNIEXPORT void JNICALL
Java_org_lotka_ndk_1hello_1world_MyChangeActivity_myfunction(
    JNIEnv *env ,
    jclass cls,
    jobject obj){
jclass myjclass = env->GetObjectClass(obj);
jfieldID myjfield =  env->GetFieldID(myjclass, "a", "I") ;
env->SetIntField(obj, myjfield, 100);
}

finish

i had an integer which the value of it was 20

int a = 20

but after jni part a will increase to 100

now my question is that how to do this with String

i want this at begining

String b = "website.com"

and change it to

String b = "google.com"

i want everything by ndk and following method that which i declared at the top for int but now i want string version of my code :)

tnks alot


Solution

  • The principle is the same. You get the field ID, and then you modify the field with Set*Field.

    The signature of the field is now Ljava/lang/String; instead of I. And instead of SetIntField you need to use SetObjectField.

    And unless you already have a jstring with the desired contents, you'll have to create one with NewString or NewStringUTF.