JNI内存释放

0

不要手动释放:jint、jlong、jchar
需要手动释放:jstring、jobject、jobjectArray、jintArray、jclass、jmethodID

FindClass	      DeleteLocalRef
NewString	      DeleteLocalRef
NewStringUTF          DeleteLocalRef
NewObject             DeleteLocalRef
NewXXXXArray          DeleteLocalRef
GetObjectField        DeleteLocalRef
GetObjectClass        DeleteLocalRef
GetObjectArrayElement DeleteLocalRef
GetStringChars        ReleaseStringChars
GetStringUTFChars     ReleaseStringUTFChars
GetXXXXArrayElements  ReleaseXXXXArrayElements
# 入参jstring jProducerId
const char *producerId = env->GetStringUTFChars(jProducerId, nullptr);
...
env->DeleteLocalRef(jProducerId);
env->ReleaseStringUTFChars(jProducerId, producerId);

# 入参jobject jRtcConfiguration
...
env->DeleteLocalRef(jRtcConfiguration);

# new
jclass jCallbackClazz         = env->GetObjectClass(this->routerCallback);
jmethodID producerNewCallback = env->GetMethodID(jCallbackClazz, "producerNewCallback", "(Ljava/lang/String;Ljava/lang/String;JJ)V");
const char* cKind       = kind.data();
jstring jKind           = env->NewStringUTF(cKind);
const char* cProducerId = producerId.data();
jstring jProducerId     = env->NewStringUTF(cProducerId);
env->CallVoidMethod(
    this->routerCallback,
    producerNewCallback,
    jKind,
    jProducerId,
    (jlong) producerPointer,
    (jlong) producerMediaTrackPointer
);
env->DeleteLocalRef(jKind);
env->DeleteLocalRef(jProducerId);
env->DeleteLocalRef(jCallbackClazz);

# 入参jbyteArray pcm
jbyte* srcBytes = env->GetByteArrayElements(pcm, 0);
const jbyteArray result = env->NewByteArray(config->size);
jbyte dstBytes[config->size];
...
env->SetByteArrayRegion(result, 0, config->size, dstBytes);
env->ReleaseByteArrayElements(pcm, srcBytes, 0);
//  不要释放
//  env->DeleteLocalRef(result);
//  env->ReleaseByteArrayElements(result, dstBytes, 0);
return result;