Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
src_qjniobject.cpp
Go to the documentation of this file.
1// Copyright (C) 2021 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
3#include <QtCore/qglobal.h>
4#include <QtCore/qdebug.h>
5
6#if defined(Q_QDOC) || defined(Q_OS_ANDROID)
7
8#include <QtCore/qjniobject.h>
9#include <QtCore/qjnitypes.h>
10
11//! [QJniObject scope]
12void functionScope()
13{
14 QString helloString("Hello");
15 jstring myJString = 0;
16 {
17 QJniObject string = QJniObject::fromString(helloString);
18 myJString = string.object<jstring>();
19 }
20
21 // Ops! myJString is no longer valid.
22 QString myQtString = QJniObject(myJString).toString();
23}
24//! [QJniObject scope]
25
26//! [C++ native methods]
27static void fromJavaOne(JNIEnv *env, jobject thiz, jint x)
28{
29 Q_UNUSED(env);
30 Q_UNUSED(thiz);
31 qDebug() << x << "< 100";
32}
33
34static void fromJavaTwo(JNIEnv *env, jobject thiz, jint x)
35{
36 Q_UNUSED(env);
37 Q_UNUSED(thiz);
38 qDebug() << x << ">= 100";
39}
40
41void foo()
42{
43 // register the native methods first, ideally it better be done with the app start
44 const JNINativeMethod methods[] =
45 {{"callNativeOne", "(I)V", reinterpret_cast<void *>(fromJavaOne)},
46 {"callNativeTwo", "(I)V", reinterpret_cast<void *>(fromJavaTwo)}};
47 QJniEnvironment env;
48 env.registerNativeMethods("my/java/project/FooJavaClass", methods, 2);
49
50 // Call the java method which will calls back to the C++ functions
51 QJniObject::callStaticMethod<void>("my/java/project/FooJavaClass", "foo", "(I)V", 10); // Output: 10 < 100
52 QJniObject::callStaticMethod<void>("my/java/project/FooJavaClass", "foo", "(I)V", 100); // Output: 100 >= 100
53}
54//! [C++ native methods]
55
56#if 0 // Java code
57//! [Java native methods]
58class FooJavaClass
59{
60 public static void foo(int x)
61 {
62 if (x < 100)
63 callNativeOne(x);
64 else
65 callNativeTwo(x);
66 }
67
68private static native void callNativeOne(int x);
69private static native void callNativeTwo(int x);
70
71}
72//! [Java native methods]
73#endif
74
75#endif