-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathjvm_env.h
60 lines (49 loc) · 1.35 KB
/
jvm_env.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
//
// Created by asalehin on 9/2/20.
//
#ifndef FAST_MIXER_JVM_ENV_H
#define FAST_MIXER_JVM_ENV_H
#include <jni.h>
#include "../logging_macros.h"
#include "structs.h"
using namespace std;
inline JavaVM *java_machine;
inline shared_ptr<recording_method_ids> kotlinRecordingMethodIdsPtr {nullptr};
inline shared_ptr<mixing_method_ids> kotlinMixingMethodIdsPtr {nullptr};
inline int get_env(JNIEnv **g_env) {
int getEnvStat = java_machine->GetEnv((void **) g_env, JNI_VERSION_1_6);
if (getEnvStat == JNI_EDETACHED) {
if (java_machine->AttachCurrentThread(g_env, nullptr) != 0) {
LOGE("FAILED ATTACH THREAD");
return 2; //Failed to attach
}
return 1; //Attached. Need detach
}
return 0;//Already attached
}
class jvm_env {
public:
jvm_env() {
auto resCode = get_env(&mEnv);
if (resCode == 2)
throw runtime_error("Cannot retrieve JNI environment");
needDetach = (resCode == 1);
}
~jvm_env() {
if (needDetach && java_machine) {
java_machine->DetachCurrentThread();
}
}
JNIEnv *env() const noexcept {
return mEnv;
}
private:
JNIEnv *mEnv;
bool needDetach;
};
template<typename Callable>
auto call_in_attached_thread(Callable func) {
jvm_env env;
return func(env.env());
}
#endif //FAST_MIXER_JVM_ENV_H