====== 002 CからJavaの関数を実行する ======
===== 概要 =====
Androidには、NDKを利用してC/C++コード側からJavaのコードを呼ぶ機能が備わっています。
CallVoidMethod()やCallIntMethod() などがそれに当たります。
==== Javaのコード ====
package com.hoge.hoge;
public class Sample
{
public void Hello()
{
Log.v( "Hoge", "call Hello" );
}
public void SetParam( int _param )
{
Log.v( "Hoge", "call SetParam _param =" + _param );
}
public void SetParam2( int _param, int _param2 )
{
Log.v( "Hoge", "call SetParam2 _param =" + _param + "_param2=" + _param2 );
}
public int GetParam()
{
Log.v( "Hoge", "call GetParam" );
}
public int GetParam2( int _param )
{
Log.v( "Hoge", "call GetParam2 = " + _param );
}
}
==== Cのコード ====
JavaVM * g_JVM = NULL;
extern "C" jint JNI_OnLoad(JavaVM* vm, void* reserved)
{
JNIEnv* env;
if( vm->GetEnv( reinterpret_cast(&env), JNI_VERSION_1_6) != JNI_OK )
{
return -1;
}
g_JVM = vm;
}
void Func()
{
jclass clazz = env->FindClass("com.hoge.hoge.Sample");
jclass sampleClass = (jclass)env->NewGlobalRef( clazz );
if( sampleClass == 0 )
{
return;
}
env->DeleteLocalRef( clazz );
JNIEnv *env = NULL;
int status = g_JVM->GetEnv((void **)&env, JNI_VERSION_1_6);
if(status < 0)
{
status = g_JVM->AttachCurrentThread(&env, NULL);
if(status < 0)
{
printf( 0, "error Func.\n" );
return;
}
}
// --------------------------------------
// public void Hello()
// --------------------------------------
{
jmethodID methodID = env->GetMethodID( sampleClass, "Hello", "()V" );
env->CallVoidMethod( g_androidApp->activity->clazz, methodID );
}
// --------------------------------------
// public void SetParam( int _param )
// --------------------------------------
{
int param = 100;
jmethodID methodID = env->GetMethodID( sampleClass, "SetParam", "(I)V" );
env->CallVoidMethod( g_androidApp->activity->clazz, methodID, param );
}
// --------------------------------------
// public void SetParam( int _param )
// --------------------------------------
{
int param = 100;
int param2 = 200;
jmethodID methodID = env->GetMethodID( sampleClass, "SetParam2", "(II)V" );
env->CallVoidMethod( g_androidApp->activity->clazz, methodID, param, param2 );
}
// --------------------------------------
// public int GetParam()
// --------------------------------------
{
jmethodID methodID = env->GetMethodID( sampleClass, "GetParam", "()I" );
int ret = env->CallIntMethod( g_androidApp->activity->clazz, methodID );
}
// --------------------------------------
// public int GetParam2()
// --------------------------------------
{
int param = 100;
jmethodID methodID = env->GetMethodID( sampleClass, "GetParam2", "(I)I" );
int ret = env->CallIntMethod( g_androidApp->activity->clazz, methodID, param );
}
}