-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathHowToCreateJavaWrappersForC++Code.txt
29 lines (22 loc) · 2.47 KB
/
HowToCreateJavaWrappersForC++Code.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
Java wrapper for MeasurementInfo C++ code
SWIG is used to generate Java wrappers for the MeasurementInfo C++ code. This will allow Java code to invoke public methods in the C++ code.
To use SWIG, a SWIG interface file has to be created. A sample interface file can be found here: bindings/swig/SpecUtils.i. This sample file brings in public declarations that are in SpecUtils/SpecUtils.h. SWIG will generate a large number of .java wrapper files.
Public C++ methods, which have primitive parameters and primitive return values such as int, float, double, char*, or std::string, are the easiest the wrap. In almost all cases, Java primitive arguments can be passed to the C++ code and the result are Java primitive data types.
Example:
bool load_file( const std::string &filename, ParserType parser_type, std::string file_ending_hint)
Java code: boolean result = info.load_file( filename, ParserType.kAutoParser, "" )
NOTE: ParserType is an enum.
For public methods that contain an object as a parameter or that returns an object, many times it is much easier to write a helper method, in the C++ code, that contains only primitive parameters and returns a primitive value.
Example:
bool write_csv( std::ostream &ostr ) const
Helper method: bool write_csv(std::string filename) const
For methods whose parameters or return value can’t be converted to primitive data types, helper methods can be written inside the SWIG interface file. The example interface file shows two helper methods to manipulate an ostream object. The first method creates an ostream object. The second method uses the ostream object to flush the stream. Here is how these two methods can be used in
Example Java code:
/* call an interface helper method to create an ostream object */
SWIGTYPE_p_std__ostream file = SpecUtilsSwig.openFile("data_generatedFile.pcf");
/* use the ostream object by calling a method inside the C++ code */
info.write_csv(file);
/* call an interface helper method to flush the stream */
SpecUtilsSwig.closeFile(file);
C++ operators, such as operator=, must be assigned to a Java method. This happens inside the SWIG interface file. The example interface file wraps operator= to a method named operatorEqual.
C++ vectors must be assigned to a Java class. This happens inside the SWIG interface file. The example interface file wraps vector<std::string> to a Java class named StringVector. Swig will generate the StringVector class. The class has properties and methods to manipulate the vector.