1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Copyright 2014 Alexis Laferrière <alexis.laf@xymus.net>
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
9 # http://www.apache.org/licenses/LICENSE-2.0
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
17 # Supporting services for the FFI with Java
19 c_compiler_option
("-I $(JAVA_HOME)/include/")
20 c_linker_option
("-L $(JNI_LIB_PATH) -ljvm")
26 private var jvm_cache
: nullable JavaVM = null
27 private var jni_env_cache
: nullable JniEnv = null
29 # Default Java Virtual Machine to use (will be instanciated using
30 # `create_default_jvm` if not already set)
33 if jvm_cache
== null then create_default_jvm
34 return jvm_cache
.as(not null)
37 # Sets the current default Java Virtual Machine (use with `jni_env=`)
38 fun jvm
=(jvm
: JavaVM) do jvm_cache
= jvm
40 # Current main `JniEnv`
41 # FIXME support threaded Java
44 if jni_env_cache
== null then create_default_jvm
45 return jni_env_cache
.as(not null)
48 # Sets the current default JNI env (use with `jvm=`)
49 fun jni_env
=(jni_env
: JniEnv) do jni_env_cache
= jni_env
51 # Called by `jvm` and `jni_env` to instanciate a Java Virual Machine.
52 # Used mostly for FFI with Java.
53 protected fun create_default_jvm
55 var builder
= new JavaVMBuilder
57 # By default, look for Java classes in a jar file the same dir as the executable
58 builder
.options
.add
"-Djava.class.path={sys.program_name}.jar"
60 var jvm
= builder
.create_jvm
61 assert jvm
!= null else print
"JVM creation failed"
64 self.jni_env
= builder
.jni_env
.as(not null)