The Cygnus Native Interface for C++/Java Integration | ||
---|---|---|
Prev | The Cygnus Native Interface for C++/Java Integration | Next |
Java methods are mapped directly into C++ methods. The header files generated by gcjh include the appropriate method definitions. Basically, the generated methods have the same names and “corresponding” types as the Java methods, and are called in the natural manner.
Both Java and C++ provide method overloading, where multiple methods in a class have the same name, and the correct one is chosen (at compile time) depending on the argument types. The rules for choosing the correct method are (as expected) more complicated in C++ than in Java, but given a set of overloaded methods generated by gcjh the C++ compiler will choose the expected one.
Common assemblers and linkers are not aware of C++ overloading, so the standard implementation strategy is to encode the parameter types of a method into its assembly-level name. This encoding is called mangling, and the encoded name is the mangled name. The same mechanism is used to implement Java overloading. For C++/Java interoperability, it is important that both the Java and C++ compilers use the same encoding scheme.
Static Java methods are invoked in CNI using the standard C++ syntax, using the `::' operator rather than the `.' operator. For example:
jint i = java::lang::Math::round((jfloat) 2.3);
Defining a static native method uses standard C++ method definition syntax. For example:
#include <java/lang/Integer.h> java::lang::Integer* java::lang::Integer::getInteger(jstring str) { ... }
Constructors are called implicitly as part of object allocation using the new operator. For example:
java::lang::Int x = new java::lang::Int(234);
Java does not allow a constructor to be a native method. Instead, you could define a private method which you can have the constructor call.
Virtual method dispatch is handled essentially the same way in C++ and Java -- i.e. by doing an indirect call through a function pointer stored in a per-class virtual function table. C++ is more complicated because it has to support multiple inheritance, but this does not effect Java classes. However, G++ has historically used a different calling convention that is not compatible with the one used by gcj. During 1999, G++ will switch to a new ABI that is compatible with gcj. Some platforms (including Linux) have already changed. On other platforms, you will have to pass the -fvtable-thunks flag to g++ when compiling CNI code. Note that you must also compile your C++ source code with -fno-rtti.
Calling a Java instance method in CNI is done using the standard C++ syntax. For example:
java::lang::Number *x; if (x->doubleValue() > 0.0) ...
Defining a Java native instance method is also done the natural way:
#include <java/lang/Integer.h> jdouble java::lang:Integer::doubleValue() { return (jdouble) value; }
In Java you can call a method using an interface reference. This is not yet supported in CNI.