JNI接口的兩種實現方式


1.利用javac和javah生成頭文件,網上已有不少例子。
2.采用注冊的方式生成,這里重點介紹本方法。
 
(a).聲明好需要使用的和對象化的全局變量
static JavaVM* g_jvm = NULL;
static jclass g_java_capturer_class = NULL; // VideoCaptureAndroid.class.
static jclass g_java_encode_class = NULL; // VideoCaptureAndroid.class.
(b).初始化Java變量
extern "C" int32_t WINAPI InitCaptureAndroidVM(JavaVM* javaVM, jobject context) {
TRACE_INFO2("InitCaptureAndroidVM");
if (javaVM)
{
TRACE_INFO2("InitCaptureAndroidVM, init");
g_jvm = javaVM;
AttachThreadScoped ats(g_jvm);
g_context = ats.env()->NewGlobalRef(context);
}
else
{
if (g_jvm)
{
AttachThreadScoped ats(g_jvm);
if (g_context)
{
ats.env()->DeleteGlobalRef(g_context);
g_context = NULL;
}
g_jvm = NULL;
}
}
return 0;
}
(c).在實現對象的時候,注冊需要使用的ndk接口
extern "C" int32_t WINAPI InitCaptureObject() {
 
if (g_jvm) {
TRACE_INFO2("InitCaptureObject, bEnableHwEncoder="<<bEnableHwEncoder);
 
AttachThreadScoped ats(g_jvm);
jclass j_capture_class =
ats.env()->FindClass("com/anbang/videocapture/VideoCaptureAndroid");
assert(j_capture_class);
g_java_capturer_class =
reinterpret_cast<jclass>(ats.env()->NewGlobalRef(j_capture_class));
assert(g_java_capturer_class);
 
TRACE_INFO2("Register VideoCaptureAndroid Native Method");
 
JNINativeMethod native_methods[] = {
{"GetContext",
"()Landroid/content/Context;",
reinterpret_cast<void*>(&GetContext)},
{"OnOrientationChanged",
"(JI)V",
reinterpret_cast<void*>(&OnOrientationChanged)},
{"ProvideCameraFrame",
"([BIIJJ)V",
reinterpret_cast<void*>(&ProvideCameraFrame)}};
if (ats.env()->RegisterNatives(g_java_capturer_class,native_methods, 3) != 0)
assert(false);
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM