【JNI开发】C++调用java函数的实现方法

时间:2022-05-07 20:18:15

本文的主要内容:C++中调用java类的成员函数和静态成员函数


1,java代码

public class SNaviEngineManager {

    public void sendMessage(int msg)
    {

    }

    public static int sendMessage(int msg)
    {

    }	

}

2,c++代码

调用成员函数

void ms_sendmessage(int msg)
{
	
	// 获取JNI环境
	bool attach = false;
	int status=0;
	JNIEnv* pEnv = NULL;
	status = g_jvm->GetEnv((void **) &pEnv, JNI_VERSION_1_6);  
	if( status < 0 )
	{
		LOGI("AttachCurrentThread");
		g_jvm->AttachCurrentThread(&pEnv, NULL);
		attach = true;
	}

	jmethodID mid = pEnv->GetMethodID( g_jcNaviEngine, "<init>", "()V");  
        jobject obj = pEnv->NewObject( g_jcNaviEngine, mid);
	if (obj == 0)  
	{  
		LOGE("Create object failed!");  
         }  

	// 调用成员方法  
        mid = pEnv->GetMethodID( g_jcNaviEngine, "sendMessage", "(I)V");
	if (mid != 0)  
	{  
		pEnv->CallVoidMethod( obj, mid, msg );	
	} 

	
	// 释放JNI环境
	if( attach )
	{
		g_jvm->DetachCurrentThread();
	}
}

调用静态成员函数

void ms_sendmessage(int msg)
{
	
	// 获取JNI环境
	bool attach = false;
	int status=0;
	JNIEnv* pEnv = NULL;
	status = g_jvm->GetEnv((void **) &pEnv, JNI_VERSION_1_6);  
	if( status < 0 )
	{
		LOGI("AttachCurrentThread");
		g_jvm->AttachCurrentThread(&pEnv, NULL);
		attach = true;
	}
 

	// 调用静态成员方法  
        jmethodID mid = pEnv->GetStaticMethodID( static_cast<jclass>(g_joNaviEngine), "sendMessage", "(I)V");
	if (mid != 0)  
	{  
		pEnv->CallStaticVoidMethod( obj, mid, msg );	
	} 

	
	// 释放JNI环境
	if( attach )
	{
		g_jvm->DetachCurrentThread();
	}
}

【注意】

在调用java类的成员函数时,一定要调用构造函数实例化java类

/** 实例化类对象 */
jobject getInstance( JNIEnv* pEnv , jclass classzz )
{
	if ( pEnv == NULL )
	{
		return NULL ;
	}

	// 获取构造方法
	jmethodID constructor = pEnv->GetMethodID(classzz, "<init>", "()V"); 
	if (NULL == constructor) 
	{ 
		return NULL;
	}   
	// 实例化类对象  
	return pEnv->NewObject(classzz, constructor); 
}