C/C++调用Java函数传递多个参数并返回String类型;
package com.niubashaoye.ndk.jni;
public class CCallJavaTools {
/**
* C/C++调用Java函数传递多个参数
* @param num1
* @param str
* @param num2
* @return
*/
public String paramList(int num1, String str, int num2) {
return str + ",年龄:" + num1 + ",总成绩:" + num2;
}
* C/C++调用Java函数传递多个参数
* @param num1
* @param str
* @param num2
* @return
*/
public String paramList(int num1, String str, int num2) {
return str + ",年龄:" + num1 + ",总成绩:" + num2;
}
}
Java的JNITools类中的native函数:
/**
* 调用访问有3个参数和返回值的方法
*
* @param num
* @param str
* @param num2
* @return
*/
public native String paramList(int num, String str, int num2);
/**
* 调用访问有3个参数和返回值的方法
*
* @param num
* @param str
* @param num2
* @return
*/
public native String paramList(int num, String str, int num2);
Java调用native:
JNITools jniTools=new JNITools();
String resultStr = jniTools.paramList(28, "欧阳无敌", 689);
/*
* Class: Java_com_niubashaoye_ndk_jni_JNITools
* Method: paramList
* Signature: (ILjava/lang/String;I)Ljava/lang/String;
* 参数列表有3个参数,并且有返回值
*/
JNIEXPORT jstring JNICALL Java_com_niubashaoye_ndk_jni_JNITools_paramList(
JNIEnv *env, jobject obj, jint num1, jstring str, jint num2) {
//获取java传递的参数
const char *strCont = env->GetStringUTFChars(str, JNI_FALSE);
//通过反射获取java类
jclass ccallj = env->FindClass("com/niubashaoye/ndk/jni/CCallJavaTools");
//实例化该类
jobject jobj = env->AllocObject(ccallj);
//得到方法id
//参数列表:反射类,方法名称,方法签名;
//I:int类类型签名,Ljava/lang/String;是String的签名
jmethodID methodId = env->GetMethodID(ccallj, "paramList",
"(ILjava/lang/String;I)Ljava/lang/String;");
//调用方法
jstring result = (jstring) env->CallObjectMethod(jobj, methodId, num1,
env->NewStringUTF(strCont), num2);
return result;
}
JNIEnv *env, jobject obj, jint num1, jstring str, jint num2) {
//获取java传递的参数
const char *strCont = env->GetStringUTFChars(str, JNI_FALSE);
//通过反射获取java类
jclass ccallj = env->FindClass("com/niubashaoye/ndk/jni/CCallJavaTools");
//实例化该类
jobject jobj = env->AllocObject(ccallj);
//得到方法id
//参数列表:反射类,方法名称,方法签名;
//I:int类类型签名,Ljava/lang/String;是String的签名
jmethodID methodId = env->GetMethodID(ccallj, "paramList",
"(ILjava/lang/String;I)Ljava/lang/String;");
//调用方法
jstring result = (jstring) env->CallObjectMethod(jobj, methodId, num1,
env->NewStringUTF(strCont), num2);
return result;
}
执行流程:Java调用C/C++的paramList函数并传递String参数,C/C++调用Java的CCallJavaTools类的paramList()函数;
,并对参数进行拼接返回给C/C++函数,C/C++函数又返回Java调用native函数;
代码下载:https://download.csdn.net/download/niuba123456/10533304
代码下载:https://download.csdn.net/download/niuba123456/10533304