-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathmain.cpp
More file actions
87 lines (69 loc) · 2.49 KB
/
main.cpp
File metadata and controls
87 lines (69 loc) · 2.49 KB
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include <jni.h>
#include <dlfcn.h>
#include <cstring>
#include <cstdlib>
static void* unityLibraryHandle = nullptr;
extern "C" {
typedef jint (*JNI_OnLoad_t)(JavaVM *vm, void *reserved);
JNIEXPORT jboolean JNICALL
load(JNIEnv *env, jobject activityObject, jstring path) {
const char *libraryPath = env->GetStringUTFChars(path, nullptr);
if (!libraryPath) {
return JNI_FALSE; // Failed to obtain library path
}
char fullPath[1000];
snprintf(fullPath, sizeof(fullPath), "%s/%s", libraryPath, "libunity.so");
unityLibraryHandle = dlopen(fullPath, RTLD_LAZY | RTLD_LOCAL);
env->ReleaseStringUTFChars(path, libraryPath);
if (!unityLibraryHandle) {
return JNI_FALSE; // Failed to load Unity library
}
JNI_OnLoad_t jniOnLoad = reinterpret_cast<JNI_OnLoad_t>(dlsym(unityLibraryHandle, "JNI_OnLoad"));
if (!jniOnLoad) {
dlclose(unityLibraryHandle);
unityLibraryHandle = nullptr;
return JNI_FALSE; // JNI_OnLoad symbol not found
}
JavaVM *vm = nullptr;
if (env->GetJavaVM(&vm) != JNI_OK) {
dlclose(unityLibraryHandle);
unityLibraryHandle = nullptr;
return JNI_FALSE; // Failed to obtain Java VM
}
jint result = jniOnLoad(vm, nullptr);
if (result < JNI_VERSION_1_6) {
dlclose(unityLibraryHandle);
unityLibraryHandle = nullptr;
return JNI_FALSE; // JNI version mismatch
}
return JNI_TRUE; // Successfully loaded Unity library
}
JNIEXPORT jboolean JNICALL
unload(JNIEnv *env, jclass activityObject) {
if (unityLibraryHandle) {
dlclose(unityLibraryHandle);
unityLibraryHandle = nullptr;
}
return JNI_TRUE;
}
JNIEXPORT jint JNICALL
JNI_OnLoad(JavaVM *vm, void *reserved) {
JNIEnv *globalEnv;
if (vm->GetEnv(reinterpret_cast<void**>(&globalEnv), JNI_VERSION_1_6) != JNI_OK) {
return JNI_ERR; // Failed to obtain JNIEnv
}
jclass clazz = globalEnv->FindClass("com/unity3d/player/NativeLoader");
if (!clazz) {
return JNI_ERR; // Class not found
}
static const JNINativeMethod methods[] = {
{"load", "(Ljava/lang/String;)Z", reinterpret_cast<void *>(load)},
{"unload", "()Z", reinterpret_cast<void *>(unload)}
};
jint ret = globalEnv->RegisterNatives(clazz, methods, sizeof(methods) / sizeof(JNINativeMethod));
if (ret != JNI_OK) {
return ret; // Failed to register natives
}
return JNI_VERSION_1_6; // Successful initialization
}
} // extern "C"