Calling a Java/Android method from C/C++ | Techbirds

Continuing my previous blog on how to use native code using JNI. I am sharing an example on how to call Java/android method from your native code(c/c++).

com.exapmle.android.MainActivity.java

public class MainActivity extends Activity { private static String libname = “mylib”;

static { System.loadLibrary(libname);}

@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_activity); String result = call_to_native(); System.out.println(result);

}

public void call_From_native(String result) { System.out.println(result); } public native String call_to_native();

}

Corresponding Native class

#include #include

#include

jstring com_example_android_MainActivity_getJniString( JNIEnv* env, jobject obj){

jstring jstr = (*env)->NewStringUTF(env, “Native call from java through JNI”);

// first get the Class Signature.
jclass cls = (*env)->FindClass(env, “com/example/android/MainActivity”);

//then find java Method Signature to be called. for example: For a method with no arguments returning void, the method signature string is “()V”.
jmethodID msg = (*env)->GetMethodID(env, cls, “call_From_native”, “(Ljava/lang/String;)Ljava/lang/String;”);

jobject result = (*env)->CallObjectMethod(env, obj, msg, jstr);
const char* str = (*env)->GetStringUTFChars(env,(jstring) result, NULL);

return (*env)->NewStringUTF(env, str);
}

386 total views, 1 views today

Share this Onfacebook-5451589twitter-1787163linkedin-4378421google-3081033