jni_signature_alt = mclass_type.jni_signature_alt
return_type = mclass_type
else
- params.add "recv"
+ params.add to_java_call_context.cast_to(mclass_type, "self")
if signature.return_mtype != null then
var ret_mtype = signature.return_mtype
ret_mtype = ret_mtype.resolve_for(mclass_type, mclass_type, mmodule, true)
redef fun compile_to_files(mmodule, compdir)
do
+ var ffi_ccu = ffi_ccu
+ assert ffi_ccu != null
+
# Make sure we have a .java file
mmodule.ensure_java_files
mmodule.insert_compiler_options
# Enable linking C callbacks to java native methods
- mmodule.ensure_linking_callback_methods(ffi_ccu.as(not null))
+ mmodule.ensure_linking_callback_methods(ffi_ccu)
+
+ # Function to build instances to the Java class NitObject
+ var callbacks = mmodule.callbacks_used_from_java.callbacks
+ if callbacks.not_empty then
+ var cf = new CFunction("jobject nit_ffi_with_java_new_nit_object(JNIEnv *env, void *data)")
+ cf.exprs.add """
+ // retrieve the current JVM
+ Sys sys = Pointer_sys(NULL);
+
+ jclass java_class = Sys_load_jclass(sys, "nit/app/NitObject");
+ if (java_class == NULL) {
+ PRINT_ERROR("Nit FFI with Java error: failed to load class NitObject.\\n");
+ (*env)->ExceptionDescribe(env);
+ exit(1);
+ }
+
+ jmethodID java_init = (*env)->GetMethodID(env, java_class, "<init>", "(J)V");
+ if (java_init == NULL) {
+ PRINT_ERROR("Nit FFI with Java error: NitObject constructor not found.\\n");
+ (*env)->ExceptionDescribe(env);
+ exit(1);
+ }
+
+ jobject nit_object = (*env)->NewObject(env, java_class, java_init, (jlong)data);
+ if (nit_object == NULL) {
+ PRINT_ERROR("Nit FFI with Java error: NitObject construction failed.\\n");
+ (*env)->ExceptionDescribe(env);
+ exit(1);
+ }
+
+ return nit_object;
+ """
+ ffi_ccu.add_local_function cf
+
+ # Function to extract the pointer held by instances of the Java class NitObject
+ cf = new CFunction("void *nit_ffi_with_java_nit_object_data(JNIEnv *env, jobject nit_object)")
+ cf.exprs.add """
+ Sys sys = Pointer_sys(NULL);
+ jclass java_class = Sys_load_jclass(sys, "nit/app/NitObject");
+ if (java_class == NULL) {
+ PRINT_ERROR("Nit FFI with Java error: failed to load class NitObject.\\n");
+ (*env)->ExceptionDescribe(env);
+ exit(1);
+ }
+
+ jfieldID java_field = (*env)->GetFieldID(env, java_class, "pointer", "J");
+ if (java_field == NULL) {
+ PRINT_ERROR("Nit FFI with Java error: NitObject field not found.\\n");
+ (*env)->ExceptionDescribe(env);
+ exit(1);
+ }
+
+ jlong data = (*env)->GetLongField(env, nit_object, java_field);
+
+ return (void*)data;
+ """
+ ffi_ccu.add_local_function cf
+ end
# Java implementation code
var java_file = mmodule.java_file
redef class MModule
private var callbacks_used_from_java = new ForeignCallbackSet
- # Pure java class source file
- private var java_file: nullable JavaClassTemplate = null
+ # Java source file extracted from user FFI code with generated structure
+ var java_file: nullable JavaClassTemplate = null
# Set up the templates of the Java implementation class
private fun ensure_java_files
for cb in callbacks do
jni_methods.add_all(cb.jni_methods_declaration(self))
end
+ for cb in callbacks_used_from_java.types do
+ jni_methods.add_all(cb.jni_methods_declaration(self))
+ end
var cf = new CFunction("void nit_ffi_with_java_register_natives(JNIEnv* env, jclass jclazz)")
cf.exprs.add """
# Tell the C compiler where to find jni.h and how to link with libjvm
private fun insert_compiler_options
do
- c_compiler_options = "{c_compiler_options} -I $(JAVA_HOME)/include/"
- c_linker_options = "{c_linker_options} -L $(JNI_LIB_PATH) -ljvm"
+ cflags.add_one("", "-I $(JAVA_HOME)/include/ -I $(JAVA_HOME)/include/linux/")
end
# Name of the generated Java class where to store all implementation methods of this module
assert sys_class != null
var sys_jni_env_meth = modelbuilder.try_get_mproperty_by_name2(self, mmodule, sys_class.mclass_type, "jni_env")
if sys_jni_env_meth == null or not sys_jni_env_meth isa MMethod then
- toolcontext.error(self.location, "Java FFI error: you must import the `java` module when using the FFI with Java")
+ toolcontext.error(self.location, "Java FFI Error: you must import the `java` module when using the FFI with Java")
return
end
super Template
var java_class_name: String
- init(name: String) do self.java_class_name = name
var header = new Template
var class_content = new Template
fun write_to_files(compdir: String): ExternFile
do
var filename = "{java_class_name}.java"
- var filepath = "{compdir}/{filename}"
+ var filepath = compdir/filename
write_to_file filepath
class JavaFile
super ExternFile
- redef fun makefile_rule_name do return "{filename.basename(".java")}.class"
- redef fun makefile_rule_content do return "javac {filename.basename("")} -d ."
+ # Full Java class name: package and class
+ fun full_name: String do return filename.basename(".java")
+
+ redef fun makefile_rule_name do return full_name.replace(".", "/") + ".class"
+ redef fun makefile_rule_content do return "javac {filename} -d ."
redef fun add_to_jar do return true
end
private class ToJavaCallContext
super CallContext
- redef fun cast_to(mtype, name) do return "({mtype.jni_type})({name})"
- redef fun cast_from(mtype, name) do return "({mtype.cname})({name})"
+ redef fun cast_to(mtype, name)
+ do
+ if mtype.java_is_nit_object then
+ return "nit_ffi_with_java_new_nit_object(nit_ffi_jni_env, {name})"
+ else
+ return "({mtype.jni_type})({name})"
+ end
+ end
+
+ redef fun cast_from(mtype, name)
+ do
+ if mtype.java_is_nit_object then
+ return "({mtype.cname})nit_ffi_with_java_nit_object_data(nit_ffi_jni_env, {name})"
+ else
+ return "({mtype.cname})({name})"
+ end
+ end
+
redef fun name_mtype(mtype) do return mtype.jni_type
end
private class FromJavaCallContext
super CallContext
- redef fun cast_to(mtype, name) do return "({mtype.cname})({name})"
- redef fun cast_from(mtype, name) do return "({mtype.jni_type})({name})"
+ redef fun cast_to(mtype, name)
+ do
+ if mtype.java_is_nit_object then
+ return "({mtype.cname})nit_ffi_with_java_nit_object_data(nit_ffi_jni_env, {name})"
+ else
+ return "({mtype.cname})({name})"
+ end
+ end
+
+ redef fun cast_from(mtype, name)
+ do
+ if mtype.java_is_nit_object then
+ return "nit_ffi_with_java_new_nit_object(nit_ffi_jni_env, {name})"
+ else
+ return "({mtype.jni_type})({name})"
+ end
+ end
+
redef fun name_mtype(mtype) do return mtype.jni_type
end
super ForeignType
var java_type: String
- init (java_type: String) do self.java_type = java_type
end
redef class NitniCallback
var csignature = mproperty.build_c_implementation_signature(recv_mtype, mmodule, "___indirect", long_signature, from_java_call_context)
var cf = new CFunction("JNIEXPORT {csignature}")
cf.exprs.add "\t{mproperty.build_ccall(recv_mtype, mainmodule, null, long_signature, from_java_call_context, null)}\n"
- ccu.add_local_function cf
+ ccu.add_non_static_local_function cf
# In Java, declare the extern method as a private static local method
var java_signature = mproperty.build_csignature(recv_mtype, mainmodule, null, short_signature, java_call_context)
#
# * Primitives common to both languages use their Java primitive type
# * Nit extern Java classes are represented by their full Java type
- # * Other Nit objects are represented by `int` in Java. It holds the
- # pointer to the underlying C structure.
- # TODO create static Java types to store and hide the pointer
- private fun java_type: String do return "int"
+ # * Other Nit objects are represented by `NitObject` in Java, a class
+ # encapsulating the pointer to the underlying C structure.
+ private fun java_type: String do return "nit.app.NitObject"
+
+ # Is this type opaque in Java? As so it is represented by `nit.app.NitObject`.
+ private fun java_is_nit_object: Bool do return true
# JNI type name (in C)
#
# So this is a C type, usually defined in `jni.h`
- private fun jni_type: String do return "jint"
+ private fun jni_type: String do return "jobject"
# JNI short type name (for signatures)
#
# Is used by `MMethod::build_jni_format` to pass a Java method signature
# to the JNI function `GetStaticMetodId`.
- private fun jni_format: String do return "I"
+ private fun jni_format: String do return "Lnit/app/NitObject;"
# Type name appearing within JNI function names.
#
# Used by `JavaLanguage::compile_extern_method` when calling JNI's `CallStatic*Method`.
# This strategy is used by JNI to type the return of callbacks to Java.
private fun jni_signature_alt: String do return "Int"
+
+ redef fun compile_callback_to_java(mmodule, mainmodule, ccu)
+ do
+ if self isa MClassType and mclass.ftype isa ForeignJavaType then return
+
+ var java_file = mmodule.java_file
+ if java_file == null or mmodule.callbacks_used_from_java.callbacks.is_empty then return
+
+ for variation in ["incr", "decr"] do
+ var friendly_name = "{mangled_cname}_{variation}_ref"
+
+ # C
+ var csignature = "void {mmodule.impl_java_class_name}_{friendly_name}(JNIEnv *nit_ffi_jni_env, jclass clazz, jobject object)"
+ var cf = new CFunction("JNIEXPORT {csignature}")
+ cf.exprs.add "\tnitni_global_ref_{variation}(nit_ffi_with_java_nit_object_data(nit_ffi_jni_env, object));"
+ ccu.add_non_static_local_function cf
+
+ # Java
+ java_file.class_content.add "private native static void {friendly_name}(nit.app.NitObject object);\n"
+ end
+ end
+
+ redef fun jni_methods_declaration(from_mmodule)
+ do
+ var arr = new Array[String]
+ for variation in ["incr", "decr"] do
+ var friendly_name = "{mangled_cname}_{variation}_ref"
+ var jni_format = "(Lnit/app/NitObject;)V"
+ var cname = "{from_mmodule.impl_java_class_name}_{friendly_name}"
+ arr.add """{"{{{friendly_name}}}", "{{{jni_format}}}", {{{cname}}}}"""
+ end
+
+ return arr
+ end
end
redef class MClassType
if ftype isa ForeignJavaType then return ftype.java_type.
replace('/', ".").replace('$', ".").replace(' ', "").replace('\n',"")
if mclass.name == "Bool" then return "boolean"
- if mclass.name == "Char" then return "char"
+ if mclass.name == "Char" then return "int"
if mclass.name == "Int" then return "long"
if mclass.name == "Float" then return "double"
+ if mclass.name == "Byte" then return "byte"
+ if mclass.name == "Int8" then return "byte"
+ if mclass.name == "Int16" then return "short"
+ if mclass.name == "UInt16" then return "short"
+ if mclass.name == "Int32" then return "int"
+ if mclass.name == "UInt32" then return "int"
return super
end
+ redef fun java_is_nit_object
+ do
+ var ftype = mclass.ftype
+ if ftype isa ForeignJavaType then return false
+
+ var java_primitives = once new HashSet[String].from(
+ ["Bool", "Char", "Int", "Float", "Byte", "Int8", "Int16", "UInt16", "Int32", "UInt32"])
+ return not java_primitives.has(mclass.name)
+ end
+
redef fun jni_type
do
var ftype = mclass.ftype
if ftype isa ForeignJavaType then return "jobject"
if mclass.name == "Bool" then return "jboolean"
- if mclass.name == "Char" then return "jchar"
+ if mclass.name == "Char" then return "jint"
if mclass.name == "Int" then return "jlong"
if mclass.name == "Float" then return "jdouble"
+ if mclass.name == "Byte" then return "jbyte"
+ if mclass.name == "Int8" then return "jbyte"
+ if mclass.name == "Int16" then return "jshort"
+ if mclass.name == "UInt16" then return "jshort"
+ if mclass.name == "Int32" then return "jint"
+ if mclass.name == "UInt32" then return "jint"
return super
end
else break
end
+ # Change `float[]` to `[float`
+ if jni_type.has('[') then
+ var depth = jni_type.chars.count('[')
+ var java_type = jni_type.replace("[]", "")
+ var short
+
+ if java_type == "boolean" then
+ short = "Z"
+ else if java_type == "byte" then
+ short = "B"
+ else if java_type == "char" then
+ short = "C"
+ else if java_type == "short" then
+ short = "S"
+ else if java_type == "int" then
+ short = "I"
+ else if java_type == "long" then
+ short = "J"
+ else if java_type == "float" then
+ short = "F"
+ else if java_type == "double" then
+ short = "D"
+ else
+ short = "L{java_type};"
+ end
+
+ return "["*depth + short
+ end
+
return "L{jni_type};"
end
if mclass.name == "Bool" then return "Z"
- if mclass.name == "Char" then return "C"
+ if mclass.name == "Char" then return "I"
if mclass.name == "Int" then return "J"
if mclass.name == "Float" then return "D"
+ if mclass.name == "Byte" then return "B"
+ if mclass.name == "Int8" then return "B"
+ if mclass.name == "Int16" then return "S"
+ if mclass.name == "UInt16" then return "S"
+ if mclass.name == "Int32" then return "I"
+ if mclass.name == "UInt32" then return "I"
return super
end
redef fun jni_signature_alt
do
var ftype = mclass.ftype
+
if ftype isa ForeignJavaType then return "Object"
if mclass.name == "Bool" then return "Boolean"
- if mclass.name == "Char" then return "Char"
+ if mclass.name == "Char" then return "Int"
if mclass.name == "Int" then return "Long"
if mclass.name == "Float" then return "Double"
+ if mclass.name == "Byte" then return "Byte"
+ if mclass.name == "Int8" then return "Byte"
+ if mclass.name == "Int16" then return "Short"
+ if mclass.name == "UInt16" then return "Short"
+ if mclass.name == "Int32" then return "Int"
+ if mclass.name == "UInt32" then return "Int"
+ return super
+ end
+
+ redef fun compile_callback_to_java(mmodule, mainmodule, ccu)
+ do
+ # Don't generate functions for reference counters on extern classes
+ if mclass.ftype != null then return
+
+ super
+ end
+
+ redef fun jni_methods_declaration(from_mmodule)
+ do
+ # Don't generate functions for reference counters on extern classes
+ if mclass.ftype != null then return new Array[String]
+
return super
end
end
else format.add "V"
end
- return format.join("")
+ return format.join
end
# Similar to `build_c_signature` but adapted to create the signature expected by JNI for C functions
var cparams = new List[String]
- # This is different
- cparams.add "JNIEnv *env"
+ cparams.add "JNIEnv *nit_ffi_jni_env"
cparams.add "jclass clazz"
if not self.is_init then
- cparams.add "{call_context.name_mtype(recv_mtype)} recv"
+ cparams.add "{call_context.name_mtype(recv_mtype)} self"
end
for p in signature.mparameters do
var param_mtype = p.mtype.resolve_for(recv_mtype, recv_mtype, from_mmodule, true)
private fun java_call_context: JavaCallContext do return new JavaCallContext
private fun to_java_call_context: ToJavaCallContext do return new ToJavaCallContext
private fun from_java_call_context: FromJavaCallContext do return new FromJavaCallContext
+
+redef class CCompilationUnit
+ # Similar to `add_local_function` but not `static`
+ #
+ # Used when the signature contains a visibility attribute.
+ private fun add_non_static_local_function(c_function: CFunction)
+ do
+ body_decl.add c_function.signature
+ body_decl.add ";\n"
+
+ body_impl.add "\n"
+ body_impl.add c_function.to_writer
+ end
+end