| 6 |
| #define LIBTGVOIP_JNIUTILITIES_H |
| 7 |
| 8 | #include "../../Buffers.h" |
| 9 | #include <functional> |
| 10 | #include <jni.h> |
| 11 | #include <cstdarg> |
| 12 | #include <string> |
| 13 |
| 14 | extern JavaVM* sharedJVM; |
| 15 |
| 16 | namespace tgvoip |
| 17 | { |
| 18 | namespace jni |
| 19 | { |
| 20 |
| 21 | inline void DoWithJNI(std::function<void(JNIEnv*)> f) |
| 22 | { |
| 23 | JNIEnv* env = NULL; |
| 24 | bool didAttach = false; |
| 25 | sharedJVM->GetEnv((void**)&env, JNI_VERSION_1_6); |
| 26 | if (!env) |
| 27 | { |
| 28 | sharedJVM->AttachCurrentThread(&env, NULL); |
| 29 | didAttach = true; |
| 30 | } |
| 31 |
| 32 | f(env); |
| 33 |
| 34 | if (didAttach) |
| 35 | { |
| 36 | sharedJVM->DetachCurrentThread(); |
| 37 | } |
| 38 | } |
| 39 |
| 40 | inline void AttachAndCallVoidMethod(jmethodID method, jobject obj, ...) |
| 41 | { |
| 42 | if (!method || !obj) |
| 43 | return; |
| 44 | va_list va; |
| 45 | va_start(va, obj); |
| 46 | DoWithJNI([&va, method, obj](JNIEnv* env) { |
| 47 | env->CallVoidMethodV(obj, method, va); |
| 48 | }); |
| 49 | va_end(va); |
| 50 | } |
| 51 |
| 52 | inline std::string JavaStringToStdString(JNIEnv* env, jstring jstr) |
| 53 | { |
| 54 | if (!jstr) |
| 55 | return ""; |
| 56 | const char* jchars = env->GetStringUTFChars(jstr, NULL); |
| 57 | std::string str(jchars); |
| 58 | env->ReleaseStringUTFChars(jstr, jchars); |
| 59 | return str; |
| 60 | } |
| 61 |
| 62 | inline jbyteArray BufferToByteArray(JNIEnv* env, Buffer& buf) |
| 63 | { |
| 64 | jbyteArray arr = env->NewByteArray((jsize)buf.Length()); |
| 65 | jbyte* elements = env->GetByteArrayElements(arr, NULL); |
| 66 | std::memcpy(elements, *buf, buf.Length()); |
| 67 | env->ReleaseByteArrayElements(arr, elements, 0); |
| 68 | return arr; |
| 69 | } |
| 70 |
| 71 | } |
| 72 | } |
| 73 |
| 74 | #endif // LIBTGVOIP_JNIUTILITIES_H |
| 75 |