Skip to content
Loic Oudot edited this page Jan 12, 2014 · 4 revisions

Templates are files used by java4cpp to customize types mappings between Java and C++ and to controls JNI code generation.

The java4cpp-templates project provide a sets of templates for a fully operational Java/C++ mappings.

Type mappings

base-templates.xml

This is the base mappings for all the class type object in Java. This file is mandatory in java4cpp.

Java type C++ type
void void
boolean bool
byte unsigned char
char char
double double
float float
int int
long long long
short short
arrays std::vector
enums enum + proxy
other classes proxy class

All Java classes, will be mapped in a proxy C++ class. For example, java.util.Map will be translated in java::util::Map.

Enums are converted in a header file that contains a C++ enum and a proxy C++ class that contains Enums methods. For example:

public enum Enumeration {
    ONE(10), TWO(20), THREE(30);

    private int value;

    Enumeration(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }
}

will be translated in a C++ enum:

typedef enum {
   NULL_VALUE = -1,
   ONE,
   TWO,
   THREE
} EnumerationEnum;

and a C++ proxy:

class Enumeration
{
   public:
   ...
   explicit Enumeration(EnumerationEnum arg1);
   virtual ~Enumeration();

   public:
   virtual int getValue();
   ...
};

Arrays are transformed in std::vector, for example:

Type Java C++
primitive double[] std::vector<double>
enums Enumeration[] std::vector<EnumerationEnum>
classes java.lang.Double[] std::vector<java::lang::Double>
muti-dims double[][] std::vector<std::vector<double> >

jnistring-templates.xml

Transforms java.lang.String into std::string by using UTF jni API (NewStringUTF, GetStringUTFChars). Works well if char in the C++ project is defined as unicode (wchar).

string-templates.xml

Transforms java.lang.String into std::string by using platform's default charset. Works well if char in the C++ project is defined in ISO-8859-1 (Windows) and other.

optional-templates.xml

Transforms primitive object in boost::optional. For example, java:lang::Double will be transformed in boost::optional<double>. Using boost::optional permit us to have a C++ syntax very similar to Java.

boost::optional<int> value;

// test nullability
if( value ) { ... }

// get a value with default
int result = value.get_value_or(0);

// sets a value
value = 42;
...

For a detailed semantics about boost::optional<> click here

JNI code generation

Java4cpp use freemarker templates to generate proxies source code. java4cpp-templates project includes theses files:

File name Usage
header-templates.ftl Used for generating .h file of a proxy
source-templates.ftl Used for generating .cpp file of a proxy
enum-templates.ftl Used for generating .h file for enums
execption-templates.ftl Used for generating source code for exception translation
common.ftl Some freemarker utilities functions
Clone this wiki locally