Hello,

in the application for Android (Android Studio) it became necessary to use the NDK. However, the following difficulties appeared.

In the file with ++ (jni folder) there is a function

#define sd 0x0F jint Java_com_bignerdranch_android_newmyndkproj_MainActivity_intFromJNI(JNIEnv* env, jobject thiz, jstring str) { //Здесь нужно взять строку str сравнить с другой строкой с помощью if // и вернуть дефайн sd если истина. return ; } 

This is the problem with the body of this function. It is necessary to compare the input string str with another string and if true return define sd . If you translate all this into java code, it should be something like the following:

  int sd = 0x0F; if (str.equals("reg785")){ return sd; } else{ return 0; } 

How to handle the jstring type so that it can be compared with a previously known string variable?

A Java activity that uses intFromJNI looks like this:

 static { System.loadLibrary("my-jni"); } public native String intFromJNI(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); int testInt = intFromJNI(String str); TextView mainText = (TextView) findViewById(R.id.textView); mainText.setText( Integer.toString(intFromJNI("reg785")) ); } 

Please tell me how to write the body of the function intFromJNI so that you can compare the input string str of type jstring with a previously known string, for example "reg785"?

Thank you in advance for all the answers.


  • one
    Here is the way to translate jstring to char *. You can use strcmp to compare strings. - αλεχολυτ
  • @alexolut, thank you very much for the answer. Problem solved, with some adjustment. The answer is stated in the main question. - foxis
  • better make the answer exactly as the answer, so it will be easier to find it. - αλεχολυτ

1 answer 1

The answer to my question (thank you very much @alexolut):

When I typed in the body of the function intFromJNI code

  const char *nativeString = env->GetStringUTFChars(javaString, JNI_FALSE); 

I got an error: "request for member 'getstringutfchars' in something

After some searches, I found a solution to the problem in the English version .

Those. the line should look like this:

  const char *res = (*env)->GetStringUTFChars(env, str, JNI_FALSE); 

As a result, the function body must be:

  #define sd 0x0F jint Java_com_bignerdranch_android_newmyndkproj_MainActivity_intFromJNI(JNIEnv* env, jobject thiz, jstring str) { const char *res = (*env)->GetStringUTFChars(env, str, JNI_FALSE);; if(strcmp(res, "reg785") == 0){ return sd; } else{ return 0; } }