nitg: intro of the FFI with java
[nit.git] / lib / java.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2014 Alexis Laferrière <alexis.laf@xymus.net>
4 #
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
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
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.
16
17 # Supporting services for the FFI with Java
18 module java is
19 c_compiler_option("-I $(JAVA_HOME)/include/")
20 c_linker_option("-L $(JNI_LIB_PATH) -ljvm")
21 end
22
23 import jvm
24
25 redef class Sys
26 private var jvm_cache: nullable JavaVM = null
27 private var jni_env_cache: nullable JniEnv = null
28
29 # Default Java Virtual Machine to use (will be instanciated using
30 # `create_default_jvm` if not already set)
31 fun jvm: JavaVM
32 do
33 if jvm_cache == null then create_default_jvm
34 return jvm_cache.as(not null)
35 end
36
37 # Sets the current default Java Virtual Machine (use with `jni_env=`)
38 fun jvm=(jvm: JavaVM) do jvm_cache = jvm
39
40 # Current main `JniEnv`
41 # FIXME support threaded Java
42 fun jni_env: JniEnv
43 do
44 if jni_env_cache == null then create_default_jvm
45 return jni_env_cache.as(not null)
46 end
47
48 # Sets the current default JNI env (use with `jvm=`)
49 fun jni_env=(jni_env: JniEnv) do jni_env_cache = jni_env
50
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
54 do
55 var builder = new JavaVMBuilder
56
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"
59
60 var jvm = builder.create_jvm
61 assert jvm != null else print "JVM creation failed"
62
63 self.jvm = jvm
64 self.jni_env = builder.jni_env.as(not null)
65 end
66 end