欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Android JNI 编程常见小问题

程序员文章站 2024-01-17 15:58:46
...
extern "C" {
jint
Java_com_cmcc_media_MicphoneService_setMicVolume(JNIEnv * jEnv, jobject jobj, jint volume)
{
   ...
}

cpp文件中如果不添加 extern "C" {}的话可能会导致java link lib error;

jstring 转string:
static char* jstring2string(JNIEnv* env, jstring jstr)
{
char* rtn = NULL;

jclass clsstring = (*env)->FindClass(env, "java/lang/String");

jstring strencode = (*env)->NewStringUTF(env, "utf-8");
jmethodID mid = (*env)->GetMethodID(env, clsstring, "getBytes", "(Ljava/lang/String;)[B");
jbyteArray barr= (jbyteArray)(*env)->CallObjectMethod(env, jstr, mid, strencode);
jsize alen = (*env)->GetArrayLength(env, barr);
jbyte* ba = (*env)->GetByteArrayElements(env, barr, JNI_FALSE);

if(alen > 0)
{
rtn = (char*)malloc(alen + 1);
memcpy(rtn, ba, alen);
rtn[alen] = 0;
}

(*env)->ReleaseByteArrayElements(env, barr, ba, 0);

return rtn;
}

或者
char* bytes = const_cast< char* > (env->GetStringUTFChars(string, NULL));
用完后 env->ReleaseStringUTFChars(string, bytes);


string转jstring:
static jstring string2jstring(JNIEnv* env, const char* pat)
{
       jclass strClass = (*env)->FindClass(env, "java/lang/String");
       jmethodID ctorID = (*env)->GetMethodID(env, strClass, "<init>", "([BLjava/lang/String;)V");
       jbyteArray bytes = (*env)->NewByteArray(env, strlen(pat));
       (*env)->SetByteArrayRegion(env, bytes, 0, strlen(pat), (jbyte*)pat);
       jstring encoding = (*env)->NewStringUTF(env, "utf-8");
       return (jstring)(*env)->NewObject(env, strClass, ctorID, bytes, encoding);
}

String16转String8:
String16 value;
String8 propvalue(value);