pyjnius/jnius/jnius_jvm_desktop.pxi

89 lines
2.6 KiB
Cython
Raw Permalink Normal View History

2019-11-29 21:39:32 +00:00
import sys
import os
from os.path import join
from jnius.env import get_java_setup
2012-08-14 01:42:43 +00:00
# on desktop, we need to create an env :)
# example taken from http://www.inonit.com/cygwin/jni/invocationApi/c.html
cdef extern jint __stdcall JNI_CreateJavaVM(JavaVM **pvm, void **penv, void *args)
2012-08-14 01:42:43 +00:00
cdef extern from "jni.h":
int JNI_VERSION_1_4
2014-05-09 07:22:56 +00:00
int JNI_OK
2012-08-14 01:42:43 +00:00
jboolean JNI_FALSE
ctypedef struct JavaVMInitArgs:
jint version
jint nOptions
jboolean ignoreUnrecognized
JavaVMOption *options
ctypedef struct JavaVMOption:
char *optionString
void *extraInfo
2012-08-14 01:42:43 +00:00
cdef JNIEnv *_platform_default_env = NULL
2012-08-14 01:42:43 +00:00
2014-05-09 07:22:56 +00:00
cdef void create_jnienv() except *:
2012-08-14 01:42:43 +00:00
cdef JavaVM* jvm
cdef JavaVMInitArgs args
2014-05-09 07:22:56 +00:00
cdef JavaVMOption *options
cdef int ret
cdef bytes py_bytes
2014-05-09 07:22:56 +00:00
import jnius_config
2014-05-09 07:22:56 +00:00
optarr = jnius_config.options
cp = jnius_config.expand_classpath()
2017-10-29 21:28:10 +00:00
optarr.append("-Djava.class.path={0}".format(cp))
2014-05-09 07:22:56 +00:00
optarr = [str_for_c(x) for x in optarr]
2014-05-09 07:22:56 +00:00
options = <JavaVMOption*>malloc(sizeof(JavaVMOption) * len(optarr))
for i, opt in enumerate(optarr):
options[i].optionString = <bytes>(opt)
options[i].extraInfo = NULL
2012-08-14 01:42:43 +00:00
args.version = JNI_VERSION_1_4
args.options = options
2014-05-09 07:22:56 +00:00
args.nOptions = len(optarr)
2012-08-14 01:42:43 +00:00
args.ignoreUnrecognized = JNI_FALSE
2019-11-29 21:39:32 +00:00
if sys.version_info >= (3, 8):
# uh, let's see if this works and cleanup later
java = get_java_setup('win32')
jdk_home = java.get_javahome()
2019-11-29 21:39:32 +00:00
for suffix in (
('bin', 'client'),
('bin', 'server'),
('bin', 'default'),
2019-11-29 21:39:32 +00:00
('jre', 'bin', 'client'),
('jre', 'bin', 'server'),
('jre', 'bin', 'default'),
2019-11-29 21:39:32 +00:00
):
path = join(jdk_home, *suffix)
if not os.path.isdir(path):
continue
with os.add_dll_directory(path):
try:
ret = JNI_CreateJavaVM(&jvm, <void **>&_platform_default_env, &args)
except Exception as e:
pass
else:
break
else:
raise Exception("Unable to create jni env, no jvm dll found.")
else:
ret = JNI_CreateJavaVM(&jvm, <void **>&_platform_default_env, &args)
2014-05-09 07:22:56 +00:00
free(options)
if ret != JNI_OK:
raise SystemError("JVM failed to start")
jnius_config.vm_running = True
import traceback
jnius_config.vm_started_at = ''.join(traceback.format_stack())
2012-08-14 01:42:43 +00:00
2014-05-09 07:22:56 +00:00
cdef JNIEnv *get_platform_jnienv() except NULL:
if _platform_default_env == NULL:
2012-08-14 01:42:43 +00:00
create_jnienv()
return _platform_default_env