jvm :: JavaVM :: defaultinit
# Represents a jni JavaVM
extern class JavaVM `{JavaVM *`}
# Create the JVM
#
# The corresponding `JniEnv` can be obtained by calling `env`.
#
# Unavailable on some platforms, including Android where you cannot instanciate a new JVM.
private new(args: JavaVMInitArgs) import jni_error `{
#ifdef ANDROID
JavaVM_jni_error(NULL, "JVM creation not supported on Android", 0);
return NULL;
#endif
JavaVM *jvm;
JNIEnv *env;
jint res;
res = JNI_CreateJavaVM(&jvm, (void**)&env, args);
if (res != JNI_OK) {
JavaVM_jni_error(NULL, "Could not create Java VM", res);
return NULL;
}
return jvm;
`}
private fun jni_error(msg: CString, v: Int)
do
print "JNI Error: {msg} ({v})"
abort
end
# Unload the Java VM when the calling thread is the only remaining non-daemon attached user thread
fun destroy `{
(*self)->DestroyJavaVM(self);
`}
# `JniEnv` attached to the calling thread
#
# A null pointer is returned if the calling thread is not attached to the JVM.
fun env: JniEnv import jni_error `{
JNIEnv *env;
int res = (*self)->GetEnv(self, (void **)&env, JNI_VERSION_1_6);
if (res == JNI_EDETACHED) {
JavaVM_jni_error(NULL, "Requesting JNIEnv from an unattached thread", res);
return NULL;
}
else if (res != JNI_OK) {
JavaVM_jni_error(NULL, "Could not get JNIEnv from Java VM", res);
return NULL;
}
return env;
`}
# Attach the calling thread to the JVM and return its `JniEnv`
fun attach_current_thread: JniEnv import jni_error `{
JNIEnv *env;
#ifdef ANDROID
// the signature is different (better actually) on Android
int res = (*self)->AttachCurrentThread(self, &env, NULL);
#else
int res = (*self)->AttachCurrentThread(self, (void**)&env, NULL);
#endif
if (res != JNI_OK) {
JavaVM_jni_error(NULL, "Could not attach current thread to Java VM", res);
return NULL;
}
return env;
`}
# Detach the calling thread from this JVM
fun detach_current_thread import jni_error `{
int res = (*self)->DetachCurrentThread(self);
if (res != JNI_OK) {
JavaVM_jni_error(NULL, "Could not detach current thread to Java VM", res);
}
`}
end
lib/jvm/jvm.nit:132,1--211,3