| 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 void DoWithJNI(std::function<void(JNIEnv*)> f){ |
| 20 | JNIEnv *env=NULL; |
| 21 | bool didAttach=false; |
| 22 | sharedJVM->GetEnv((void **) &env, JNI_VERSION_1_6); |
| 23 | if(!env){ |
| 24 | sharedJVM->AttachCurrentThread(&env, NULL); |
| 25 | didAttach=true; |
| 26 | } |
| 27 |
| 28 | f(env); |
| 29 |
| 30 | if(didAttach){ |
| 31 | sharedJVM->DetachCurrentThread(); |
| 32 | } |
| 33 | } |
| 34 |
| 35 | inline void AttachAndCallVoidMethod(jmethodID method, jobject obj, ...){ |
| 36 | if(!method || !obj) |
| 37 | return; |
| 38 | va_list va; |
| 39 | va_start(va, obj); |
| 40 | DoWithJNI([&va, method, obj](JNIEnv* env){ |
| 41 | env->CallVoidMethodV(obj, method, va); |
| 42 | }); |
| 43 | va_end(va); |
| 44 | } |
| 45 |
| 46 | inline std::string JavaStringToStdString(JNIEnv* env, jstring jstr){ |
| 47 | if(!jstr) |
| 48 | return ""; |
| 49 | const char* jchars=env->GetStringUTFChars(jstr, NULL); |
| 50 | std::string str(jchars); |
| 51 | env->ReleaseStringUTFChars(jstr, jchars); |
| 52 | return str; |
| 53 | } |
| 54 |
| 55 | inline jbyteArray BufferToByteArray(JNIEnv* env, Buffer& buf){ |
| 56 | jbyteArray arr=env->NewByteArray((jsize)buf.Length()); |
| 57 | jbyte* elements=env->GetByteArrayElements(arr, NULL); |
| 58 | memcpy(elements, *buf, buf.Length()); |
| 59 | env->ReleaseByteArrayElements(arr, elements, 0); |
| 60 | return arr; |
| 61 | } |
| 62 |
| 63 | } |
| 64 | } |
| 65 |
| 66 | #endif //LIBTGVOIP_JNIUTILITIES_H |
| 67 |