C调用java
jclass TestProvider; jobject mTestProvider; jmethodID showtoast; jmethodID sayHello; JNIEXPORT void JNICALL Java_com_beats_music_musicbeats_NdkTest_setTemp (JNIEnv * env, jobject jobj, jstring jstr){ // 1. C 中映射 类 TestProvider=(*env)->FindClass(env,"com/beats/music/musicbeats/active/ToastUtil"); // 2.C中新建对象 jmethodID construction_id = (*env)->GetMethodID(env, TestProvider,"<init>", "()V"); mTestProvider = (*env)->NewObject(env, TestProvider,construction_id); // 3.C中映射方法 // 静态: showtoast = (*env)->GetStaticMethodID(env, TestProvider, "showtost","(Ljava/lang/String;)V"); // 非静态: // sayHello = (*jniEnv)->GetMethodID(jniEnv, TestProvider, "sayHello","(Ljava/lang/String;)V"); //4.调用 // 调用静态: (*env)->CallStaticVoidMethod(env,TestProvider,showtoast,jstr); // 非静态: // (*jniEnv)->CallVoidMethod(jniEnv, mTestProvider, sayHello,jstrMSG); };
char*转jstring
将char*转成jstring /** * jni中有对应GetStringChar方法 * 把一个jstring转换成一个c语言的char* 类型. */ char* _JString2CStr(JNIEnv* env, jstring jstr) { char* rtn = NULL; jclass clsstring = (*env)->FindClass(env, "java/lang/String"); jstring strencode = (*env)->NewStringUTF(env,"GB2312"); jmethodID mid = (*env)->GetMethodID(env, clsstring, "getBytes", "(Ljava/lang/String;)[B"); jbyteArray barr = (jbyteArray)(*env)->CallObjectMethod(env, jstr, mid, strencode); // String .getByte("GB2312"); jsize alen = (*env)->GetArrayLength(env, barr); jbyte* ba = (*env)->GetByteArrayElements(env, barr, JNI_FALSE); if(alen > 0) { rtn = (char*)malloc(alen+1); //"\0" memcpy(rtn, ba, alen); rtn[alen]=0; } (*env)->ReleaseByteArrayElements(env, barr, ba,0); return rtn; }