您现在的位置是:网站首页> C/C++
Qt C++和Java相互调用
- C/C++
- 2021-04-19
- 945人已阅读
1. C++调用Java
class Test: public QObject
{
public:
void callJavaMethodPrintHello();
}
void Center::callJavaMethodPrintHello()
{
//这里相当于获取MainActibity.java里的类对象
const QAndroidJniObject& activity = QtAndroid::androidActivity();
//调用打印
activity.callObjectMethod("printHello", "()V");
//获取值
QAndroidJniObject string = QAndroidJniObject::callStaticObjectMethod("net/sun/java/MainActivity", "getHello", "()Ljava/lang/String;");
qDebug()<<"callJavaMethodPrintHello......:"<<string.toString();
//传参
jint n = activity.callMethod<jint >("add", "(II)I", 1, 2);
qDebug()<<n;
}
1.const QAndroidJniObject& activity = QtAndroid::androidActivity();相当于获取java里MainActivity的类对象,拿到这个对象开始做其他操作。
2.callObjectMethod、callMethod、callStaticObjectMethod都是调用java代码的方法,具体使用可以参照QT帮助文档QAndroidJniObject类
3.net/sun/java/MainActivity为MainActivity.java的所在路径
4.调用java代码方面新手可能不太会传参和接受返回数据,下边的图标符号对应的类型供参考
MainActibity.java
public class MainActivity extends org.qtproject.qt5.android.bindings.QtActivity
{
private void printHello {
Log.i("@@@", "Hello world!");
}
private static String getHello() {
return "Hello!";
}
private int add(int a, int b) {
return a + b;
}
}
2. java调用C++
Test.cpp
static void JavaNotify_1()
{
qDebug()<<"C++ JavaNotify_1";
}
static void JavaNotify_2()
{
qDebug()<<"C++ JavaNotify_2";
}
static const JNINativeMethod gMethods[] = {
{ "CallJavaNotify_1", "()V", (void*)JavaNotify_1},
{ "CallJavaNotify_2", "()V", (void*)JavaNotify_2}
};
void RegJni()
{
QtAndroid::runOnAndroidThreadSync([=](){
QAndroidJniEnvironment Environment;
const char* mClassName ="net/sun/java/MainActivity";
jclass j_class;
j_class = Environment->FindClass(mClassName);
if (j_class == nullptr)
{
qDebug()<<"erro clazz";
return ;
}
jint mj = Environment->RegisterNatives(j_class, gMethods, sizeof(gMethods) / sizeof(gMethods[0]));
if (mj != JNI_OK)
{
qDebug()<<"register native method failed!";
return;
}else{
qDebug()<<"RegisterNatives success!";
}
});
qDebug()<<"++++++++++++++++++++++++";
}
Center::Center(QObject *parent) : QObject(parent)
{
}
gMethods是一个二维数组,把需要被调用的C++方法和Java方法绑定到一起,建立对应关系,比如,java中调用CallJavaNotify_1相应C++的JavaNotify_1就会被执行。然后Environment->RegisterNatives注册
MainActibity.java
public class MainActivity extends org.qtproject.qt5.android.bindings.QtActivity
{
public native void CallJavaNotify_1();
public native void CallJavaNotify_2();
private void callQtFunction(){
CallJavaNotify_1();
}
}
java中在你想要调用的地方调用即可。