77
88JavaVM * gJvm = NULL ;
99
10- JNIEXPORT jint JNICALL JNI_OnLoad (JavaVM * vm , void * reserved ) {
11- gJvm = vm ;
12- return JNI_VERSION_1_6 ;
10+ void findJvm () {
11+ if (gJvm != NULL ) {
12+ return ;
13+ }
14+
15+ JavaVM * vmBuf [1 ];
16+ jsize nVMs = 0 ;
17+
18+ jint res = JNI_GetCreatedJavaVMs (vmBuf , 1 , & nVMs );
19+ if (res == JNI_OK && nVMs > 0 ) {
20+ gJvm = vmBuf [0 ];
21+ } else {
22+ gJvm = NULL ;
23+ }
1324}
1425
1526JNIEnv * getEnv () {
27+ findJvm ();
28+ if (gJvm == NULL ) {
29+ printf ("Could not find JavaVM\n" );
30+ return NULL ;
31+ }
32+
1633 JNIEnv * env ;
1734 if ((* gJvm )-> GetEnv (gJvm , (void * * )& env , JNI_VERSION_1_6 ) != JNI_OK ) {
1835 if ((* gJvm )-> AttachCurrentThread (gJvm , (void * * )& env , NULL ) != 0 ) {
36+ printf ("Failed to attach current thread\n" );
1937 return NULL ;
2038 }
2139 }
@@ -24,34 +42,18 @@ JNIEnv* getEnv() {
2442
2543const char * call_https_java (JNIEnv * env ) {
2644 jclass cls = (* env )-> FindClass (env , "HttpsCaller" );
27- if ((* env )-> ExceptionCheck (env )) {
28- (* env )-> ExceptionDescribe (env );
29- (* env )-> ExceptionClear (env );
30- return "Class not found (exception)" ;
31- }
32- if (!cls ) return "Class not found" ;
3345
3446 jmethodID mid = (* env )-> GetStaticMethodID (env , cls , "callHttps" , "()Ljava/lang/String;" );
35- if ((* env )-> ExceptionCheck (env )) {
36- (* env )-> ExceptionDescribe (env );
37- (* env )-> ExceptionClear (env );
38- return "Method not found (exception)" ;
39- }
40- if (!mid ) return "Method not found" ;
4147
4248 jstring result = (jstring )(* env )-> CallStaticObjectMethod (env , cls , mid );
43- if ((* env )-> ExceptionCheck (env )) {
44- (* env )-> ExceptionDescribe (env );
45- (* env )-> ExceptionClear (env );
46- return "Java method threw exception" ;
47- }
48- if (!result ) return "Java method returned null" ;
4949
50- const char * str = (* env )-> GetStringUTFChars (env , result , 0 );
51- if (!str ) return "Failed to get UTF chars" ;
50+ const char * str = (* env )-> GetStringUTFChars (env , result , NULL );
5251
5352 char * copied = strdup (str );
53+
5454 (* env )-> ReleaseStringUTFChars (env , result , str );
55+ (* env )-> DeleteLocalRef (env , result );
56+ (* env )-> DeleteLocalRef (env , cls );
5557
56- return copied ? copied : "Memory allocation failed" ;
58+ return copied ;
5759}
0 commit comments