Search code examples
androidjava-native-interface

How to change int value in activity when I use public native void function


I'm new one and using Eclipse to develop Android app. I have an android project that use JNI.

But I have a question, and I can't solve it now. How to change int value in activity when I use public native void function?

My code as follow,

ImageActivity.java

int width = 100, height = 0;

public native void FindFeatures(long matRgba1, long matRgba2, long matRgba3, int width, int height);

FindFeatures(M1.getNativeObjAddr(), M2.getNativeObjAddr(), M3.getNativeObjAddr(), width, height);

String ch = ""+ width;
t.setText(ch);

jin_part.cpp

extern "C" {
JNIEXPORT void JNICALL Java_org_opencv_samples_tutorial2_ImageActivity_FindFeatures(JNIEnv*, jobject, jlong Rgba1, jlong Rgba2, jlong Rgba3, jint width, jint height);

JNIEXPORT void JNICALL Java_org_opencv_samples_tutorial2_ImageActivity_FindFeatures(JNIEnv*, jobject, jlong Rgba1, jlong Rgba2, jlong Rgba3, jint width, jint height)
{
  width = 20;
}
}

I want to change the with value from the JNI, and show it on the text of activity.

After running the code, the text result is still 100 as initial value, not 20.

I googled lots articles and tried, But failed.

If anyone can help, I'll appreciate your help. Thanks in advance.


Solution

  • The value isn't changing because the width variable in your JNI code is passed in by value, not by reference. (In this case, it would be the same if you had a Java implementation instead of a native implementation since the variable is a primitive type.) You cannot do what you want to directly.

    Possible work arounds:

    1. Make the method return the value instead of being void.
    2. Create a simple class that holds the integer values that you want to pass back and forth as member variables.

    For what it's worth, I think methods with "side-effects" like this are generally considered to be bad form, especially in the Java community. Maybe there's another way to get what you want?