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