From 4d2a61ee3c510adc5a80d3e9d5cb20a6a53e460f Mon Sep 17 00:00:00 2001
From: "biao716.wang" This is a technical overview of the C++0x/C++11 support for the Swig.
+This area of Swig is a work in progress. Initial C++0x/C++11 support for
+Swig was written during the Google Summer of Code 2009 period by
+Matevž Jekovec. branches/gsoc2009-matevz Wikipedia article: http://en.wikipedia.org/wiki/C%2B%2B0x
+ The Rvalues are used in practice to speed up the move operations
+on different containers. In the following example, we want to swap the given elements:
+This can now be solved using the new function std::move():
+For the move function to take effect, user needs to reimplement the
+move constructor (taking ClassType&& as an argument) and
+operator=(ClassType&&):
+In practice, the Rvalues are used for temporaries (when passing the
+result of one function as an argument to another). Done: Added type&& to Swig parser. Added testcase
+cpp11_rvalue_reference.i. Operator && is treated the same as
+operator &. R11450 Article:
+http://www.artima.com/cppsource/rvalue.html In C++11 you can define functions as constant expressions.
+Functions need to return constant value in form "return expr",
+where expr is a constant expression.
+ A keyword "constexpr" is introduced for this. eg.:
+constexpr int getNumber() { return 5; } const int MY_CONSTANT =
+getNumber();
+ Constants are treated as normal variables in interpreted languages
+because they are not compiled into the executable. Java "final"
+constants are defined runtime as well. C++ constants need to be
+declared in the header file and defined in the implementation file,
+so swig doesn't need to know about the constant values when parsing
+the header file.
+ Done: Added the âconstexpr â keyword to Swig. Added testcase
+cpp11_constexpr. R11322 Problem: No compilers were known to support constexpr yet, so the
+testcase was temporarily commented out in common.mk.
+ Extern template forces the GCC compiler to not instantiate the
+template in the translation unit at that time. It's a feature
+specifically aimed at compilers to speed up the compilation process.
+ Done: Added support for 'extern template class
+std::vector<MyClass>;'. Added testcase cpp11_template_explicit.
+R11385 , R11386 Initializer list is a new type in standard library:
+std::initializer_list<T>. New symbols {} are introduced for the
+initializer lists.
+ One can now use:
+
+Languages like Java, C# and Python already support direct creation of
+lists natively. Problem: initializer_list cannot be treated as an ordinary list.
+The constructor containing initializer_list can only be accessed by
+assigning the value using the {} brackets. I also don't think there
+is a simple way to convert an ordinary list or a vector to the
+initializer_list. Done: Ignored the constructor having initializer_list as its
+argument. Show warning to the user. Added testcase
+cpp11_initializer_list. R11450 Article:
+http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1919.pdf The new C++11 standard will allow the following:
+The feature works exactly as it did now for POD types only (eg. int
+a[] = {1,2,3};). The following declarations are the same in the new
+C++11:
+The new way of using uniform initialization allows the following:
+The new syntax is specific to C++. Java, C# and scripting languages
+do not support this behaviour, but always need constructors. They
+support {} brackets for declaration of arrays as C does + they add
+support for creation of arrays on-the-fly (what C++11 introduced with
+this feature and more). Done: Added syntax for {} member initialization in class
+constructor. Added testcase cpp11_uniform_initialization. R11413 A new keyword 'auto' is introduced in C++11:
+The type of a1 and a2 is automatically determined according to the
+initialization value during the semantic phase of the compiler. Another macro 'decltype()' is introduced. The macro takes the
+concrete object as an argument and returns its type. User could use
+this as:
+Calling operators are allowed as well:
+Done: Added support for decltype() syntax. Test cases for normal
+decltype members and alternate function members work fine. Currently
+only syntax in form decltype(variable name) work. No support for
+custom expresions eg. decltype(i+j) yet. R11525 TODO: William proposed to support the hidden variables as well
+(ones not parsed by Swig and added to symbol table). This also allows
+Swig to parse custom expressions like decltype(i+j). The idea is to
+introduce a new SwigType for this. This feature is always present inside the implementation block
+only.
+ C++11 introduces lambda functions defined as:
+If the lambda function contains a single return statement only or the
+function doesn't return any type, the return type '->' can be
+omitted. Lambda functions are function objects. The following example prints the number of items stored in a list:
+Parameters inside the [] are the visible parameters of the lambda
+functions. These can be & (references), = (copies), variable name
+(variable copy), &variable name (variable reference) or this
+(copy of the current object). Lambda functions can be stored using:
+Proposal: Lambda functions are most commonly used inside the function
+block to quickly define how the sort, find and similar functions
+should work (the other way would be overriding a class â the Java
+style). The latest GCC does not support lambda functions yet so it is
+difficult to test the feature once implemented. I would implement the
+syntax support for this feature, but produce no wrapper code. Lambda
+functions still work inside the function block though. Article:
+http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2550.pdf Done: Added syntax support for the lambda functions. Added
+testcase cpp11_lambda_functions.i. R11491, R11492 The problem with decltype() is that the parameters need to be
+defined before the decltype. The following syntax is not valid,
+because lhs and rhs hasn't been defined at the time of decltype:
+The solution C++11 offers is the combination of the 'auto' keyword
+before and '-> rettype' after the function declaration:
+The new syntax only makes the job for the C++ compilers easier when
+parsing such functions. The new syntax can be used for ordinary
+functions as well:
+Done: Added support for the 'auto' return type. Added support for the
+'-> type' after the funtion declaration. Added testcases
+cpp11_alternate_function_syntax.i and
+cpp11_alternate_function_syntax_runme.py. R11414 In C++ there is a common problem when you use a template in the
+class which doesn't support all the operations the functions in the
+class actually do on the type. Compiler errors are usually very long
+and unreadable. C++11 adds support for the "concepts". The
+idea is to define what operations and attributes should the template
+have. In contrast to class inheritance and polimorphism, all lookups
+are done in compile-time.
+ Basic syntax (note LessThanComparable?
+instead of "class" or "typename"):
+
+Extended syntax (requires conditions are separated with &&,
+|| or !):
+
+Definition of the concepts:
+
+Concept maps allow usage of a specific type:
+
+Concept maps can act as mini-types, with function definitions and
+other constructs commonly associated with classes:
+
+Axioms are a facility pertaining to concepts supplied by C++11 to
+express the semantic properties of concepts. For example, the concept
+Semigroup can be defined with an axiom Associativity as:
+
+Axioms are more like hints to the compiler to speed-up the process of
+compilation.
+ Ignored: Concepts and axioms were removed from the C++11 standard.
+ This feature allows classes constructors to call other
+constructors with different arguments (similar to Java and C#
+behaviour).
+ The syntax is as follows:
+
+Also when using the inheritance, the feature introduces inheritance
+of all superclass constructors without being defined separately in
+the inherited class:
+
+Swig already correctly parses and produces the correct wrapper for
+the âusingâ keyword. Done: Added testcase cpp11_constructors.i which covers both
+constructor delegation and constructor inheritance. R11532 Problem: Constructor delegation and constructor inheritance is not
+supported by any compiler yet, so it's impossible to try and test
+this feature. nullptr is part of the standard library.
+ It's defined as typedef decltype(nullptr) nullptr_t;
+ nullptr_t is defined in <cstddef>.
+ As far as the C++ is compatible with 0 as the pointer value, swig
+values will work for the C++. And the other way around, nullptr
+behaves as the ordinary pointer (false, if empty, true, if not
+empty), so it's ok for swig to compare it. Done: Written a testcase cpp11_null_pointer_constant.i and
+cpp11_null_pointer_constant_runme.py to prove the nullptr
+functionality. R11484 C++11 introduces a new syntax for strongly typed enum declaration:
+
+Typing if (Val4 == 101) will result in compilation error.
+ The enum itself can now be explicitely of type int, long, unsigned
+int etc.:
+
+And it can be forward declared as well:
+
+Done: Added syntax 'enum class Name' and forward declarators 'enum
+Name : inherited type' or 'enum class Name : inherited type' in
+R11449. TODO: Add semantic support for enum elements not clashing with
+enum elements in other enum classes. See cpp11_strongly_typed_enums.i
+warnings. Problem: Swig currently doesn't support nested classes. This
+feature should be implemented using a new nested class when using
+âenum classâ with a single anonymous âenum {elements}â
+element inside. For example:
+should be mapped to Support for right angled brackets was implemented using the
+following article as a base:
+http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1757.html
+ Done: Added support for angle brackets. Used the preferred
+"Approach 1". Added a testcase named
+cpp11_template_double_brackets. R11245 This is used when converting one type to another (eg. if
+(myObject) {}, where myObject is your custom class converted to
+bool).
+ Requires both operator and function overloading which is not
+supported in any target language (eg. python, php).
+ Done: Swig already supports the keyword "explicit" for
+function types as well. Added test case
+cpp11_explicit_conversion_operators. R11323 The new C++11 will allow creation of wrapper around the template.
+For example, if we want to do this:
+This is still illegal! But we can now use the new syntax for
+achieving the same effect:
+Here we created a new wrapper TypedefName taking one template
+argument <second> which creates a type SomeType<OtherType,
+second, 5>. OtherType and 5 are predefined here and hidden from
+the user â the user only uses TypedefName type. The same goes for the following example:
+Swig supports parsing typedefs for templates as well for example:
+Done: Expanded support for the new 'using' syntax and template
+aliasing. Added testcase cpp11_template_typedefs. R11533 TODO: Make Swig aware of the newly defined typedef. The TYPEDEF
+keyword is part of the storage_class rule and type+declarator (see
+c_decl rule) is the right part of the definition â for example void
+(*PFD)(double) cannot be transformed to void *(double) easily. To
+fully support the new 'using' form, we'll probably have to change the
+type, type_right rules and declarator, direct_declarator,
+notso_direct_declarator etc., which is PITA. C++ currently offers usage of unions for types with trivial
+constructors only. The new C++11 standard allows usage of types with
+non-trivial constructors as well:
+Swig already parses the given syntax. Done: Added testcase cpp11_unrestricted_unions. R11435, R11447 Problem: GCC doesn't support unrestricted unions yet so there is
+no way to actually test, if it works. The new C++11 offers the following syntax:
+This can be used for example:
+The ... is used in two cases. One is in the template header where it
+marks on the left the keywords 'typename' or 'class' and a type name
+on the right. The second case is usually in the function block to
+decompose typename on the left of the ... . For example:
+The tricky part is that variadic templates can unpack actually
+anywhere â including the class inheritance :(
+A new extension to sizeof is also introduced with this feature. The
+... after sizeof returns number of arguments:
+Done: Added syntax support for 'typename' or 'class' + ... + id.
+Added testcase cpp11_variadic_templates. R11458 Done: Added syntax support for BaseClass + ..., type + ... + id in
+parameters and baseclass + ... for intializers after constructor.
+Extended Swig syntax to support sizeof...(Args). R11467 Done: Fixed %template to support variadic number of templates. TODO: Only (if present) first variadically defined argument is
+currently used in %template directive. The next ones are ignored. Beside the implementation, the new C++11 Unicode and custom
+delimeter constants can occur in templates in the header file.
+ Done: Added symbols 'u', 'u8' and 'U' to mark the beginning of the
+UTF string. Also added test case cpp11_raw_string_literals. R11327 Done: Added R"DELIMITER[, ]DELIMITER" for a custom
+delimiter for the beginning/end of the string. R11328 TODO: Fix the Swig's C++ preprocessor bug when parsing an odd
+number of â inside the string brackets. See
+Source/Preprocessor/cpp.c. C++ has different suffix literals. eg. 12.5f marks the number 12.5
+as float.
+ C++11 allows user to define his own suffix for the strings always
+starting with the underscore (_). eg. int a = "hello"_mySuffix;
+ The syntax is similar to other operator overloading functions:
+
+The null terminated const char* is the string between the "".
+The _mySuffix is the name of the suffix operator. And the OutputType
+is the outputType the operator returns.
+ Other forms are:
+
+Another possibility is to use variadic templates:
+
+This instantiates the literal processing function as
+operator""_Suffix<'1', '2', '3', '4'>. In this form,
+there is no terminating null character to the string. The main
+purpose to doing this is to use C++11's constexpr keyword and the
+compiler to allow the literal to be transformed entirely at compile
+time, assuming OutputType is a constexpr-constructable and copyable
+type, and the literal processing function is a constexpr function. Article:
+http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2765.pdf Done: Added syntax support for userdefined literals. Added
+testcase cpp11_userdefined_literals.i. R11494 TODO: %rename doesn't parse operatorââ yet. New C++11 introduces keyword "thread_local" which marks
+the following variable dynamically located depending on the current
+thread when using the address-of (&) operator.
+ Syntax:
+
+Done: Add "thread_local" keyword to Swig. Added testcase
+cpp11_thread_local. R11393 C++ automatically creates default constructor with empty
+parameters, copy constructor, operator= and destructor for any class.
+Sometimes user wants to explicitly remove one of them or enable them
+(eg. default constructor with empty parameters doesn't work any more,
+if any other constructor is defined).
+ Words "default" and "delete" are introduced.
+The syntax is similar to declaration of pure virtual function:
+
+User has the ability by using keyword delete to disallow calling of
+the standard functions brought by C++ itself.
+
+Ignored: Swig already parses the keywords "= delete" and "=
+default". These keywords are used for built-in functions (copy
+constructor, operator= etc.), which are ignored by Swig anyway. Done: Added testcase cpp11_default_delete. R11535 Type long long int is an integer type that has at least 64 useful
+bits. C99 added it to its standard, but the C++ didn't adopt it until
+C++11. Most C++ compilers supported it though.
+ Done: Swig already parses the C code including the long long type.
+ static_assert() can be used at class scope as well eg.:
+
+Done: Added syntax support for "static_assert()". Added
+test case cpp11_static_assert. R11369 C++11 allows calls of sizeof to concrete objects as well:
+
+This kind of syntax is already supported by Swig. Done: Added testcase cpp11_sizeof_objects. R11538
+ C++11 will add the following classes to the standard library:
+
+Ignored: No changes to the language itself is made.
+ Tuple is array of various types. C++11 introduced this feature
+using variadic templates. Tuple is defined as:
+Constructor is automatically generated filling the tuple elements.
+get<X> function is introduced to get the Xth element in the
+tuple.
+Tuples can be copied to each other, if all the elements are copiable:
+TODO: Implement wrappers for the tuplet<> class. C++11 introduces the "unordered" version of existing
+types, which in practice work faster than the linear types:
+
+Swig should use the "unordered" types exactly the same as
+the original linear types. Problem: Unordered types do not contain exactly same members as
+ordered ones (eg. _Hashtable_iterator does not offer operator--() and
+constructor with compare function which is required). So simply
+aliasing unordered classes to ordered ones doesn't work. TODO: Implement wrappers for unordered_ types. Initial work is
+already done in Lib/std/unordered_*.i files. Two new classes are introduced in C++11: basic_regex and
+match_results. Both are defined in regex header file.
+ Ignored: The new feature extends the standardy library only. No
+changes to Swig needed.
+ This feature deprecates auto_ptr and adds shared_ptr, weak_ptr and
+unique_ptr to the standard library.
+ This feature only adds the smart pointers to the standard library
+and doesn't effect the C++ syntax. Done: Added test case which uses all three smart pointers in the
+class. R11394 Problem: GCC standard library doesn't contain the new smart
+pointers yet.
+ This feature standardize the pseudo random number algorithm
+(currently, the random number generator was dependent on the
+platform/compiler). It adds functions linear_congruential,
+subtract_with_carry and mersenne_twister and symbols
+uniform_int_distribution, bernoulli_distribution,
+geometric_distribution, poisson_distribution, binomial_distribution,
+uniform_real_distribution, exponential_distribution,
+normal_distribution and gamma_distribution to the standard library.
+ Ignored: The new feature extends the standardy library only. No
+changes to Swig needed.
+ This feature adds ref and cref classes to the standard library
+(#include <utility>) usually used in tempalte functions.
+ Ignored: The new feature extends the standardy library only. No
+changes to Swig needed.
+ Two features are introduced:
+ The function template wrapper:
+ and the function object:
+
+Swig already supports the two. Done: Added a runtime testcase for function objects
+cpp11_function_objects. R11419. C++11 adds a new header file <type_traits> which includes
+helper functions to determine the template type while initializing
+the object at compile time.
+ Swig already supports the following code:
+
+Functions is_convertible, is_integral, is_integral_const etc. are
+part of the new header:
+
+Swig correctly parses the syntax for template<bool>,
+template<class T> and template<>.
+ Ignored: Swig requires explicitly defined template class
+(%template directive) to export it to the target language. The template function is introduced: std::result_of() which
+depends on decltype:
+
+Swig correctly parses the result_of class. TODO: The return type (the result_of::type member) is not
+calculated by Swig. This needs a much more complex semantic parser. Done: Added testcase cpp11_result_of. R11534
@@ -360,7 +360,7 @@ need to link in the Allegro shared library. The library you create from
the C++ wrapper will be what you then load into Allegro CL.
@@ -373,21 +373,21 @@ swig -allegrocl [ options ] filename
-identifier-converter [name] - Binds the variable swig:*swig-identifier-convert*
in the generated .cl file to name.
- This function is used to generate symbols
- for the lisp side of the interface.
+ This function is used to generate symbols
+ for the lisp side of the interface.
-cwrap - [default] Generate a .cxx file containing C wrapper function when
wrapping C code. The interface generated is similar to what is
- done for C++ code.
+ done for C++ code.
-nocwrap - Explicitly turn off generation of .cxx wrappers for C code. Reasonable
for modules with simple interfaces. Can not handle all legal enum
- and constant constructs, or take advantage of SWIG customization features.
+ and constant constructs, or take advantage of SWIG customization features.
-isolate - With this command-line argument, all lisp helper functions are defined
in a unique package named swig.<module-name> rather than
- swig. This prevents conflicts when the module is
- intended to be used with other swig generated interfaces that may,
- for instance, make use of different identifier converters.
+ swig. This prevents conflicts when the module is
+ intended to be used with other swig generated interfaces that may,
+ for instance, make use of different identifier converters.
{ void b() {}; };
+ template { void b() {} };
%template(MyTConcrete) X< ::S >;
plus probably some other corner case usage of ::.
@@ -3135,7 +4545,7 @@ Version 1.3.37 (13 January 2009)
in Allegro CL
2008-07-19: wsfulton
- Fix building of Tcl examples/test-suite on Mac OSX reported by Gideon Simpson.
+ Fix building of Tcl examples/test-suite on Mac OS X reported by Gideon Simpson.
2008-07-17: wsfulton
Fix SF #2019156 Configuring with --without-octave or --without-alllang
@@ -3199,7 +4609,7 @@ Version 1.3.36 (24 June 2008)
06/19/2008: wsfulton
[Java, C#] C# and Java keywords will be renamed instead of just issuing a warning
- and then generating uncompileable code. Warning 314 gives the new name when a
+ and then generating uncompilable code. Warning 314 gives the new name when a
keyword is found.
06/19/2008: wsfulton
@@ -3302,8 +4712,8 @@ Version 1.3.36 (24 June 2008)
Makefile target being generated when generating makefiles with the -M family
of options. For example:
- $ swig -java -MM -MT overiddenname -c++ example.i
- overiddenname: \
+ $ swig -java -MM -MT overriddenname -c++ example.i
+ overriddenname: \
example.i \
example.h
@@ -3642,7 +5052,7 @@ Version 1.3.34 (27 February 2008)
11/30/2007: wsfulton
Fix using statements using a base class method where the methods were overloaded.
Depending on the order of the using statements and method declarations, these
- were previously generating uncompileable wrappers, eg:
+ were previously generating uncompilable wrappers, eg:
struct Derived : Base {
virtual void funk();
@@ -3780,7 +5190,7 @@ Version 1.3.32 (November 15, 2007)
%attributeref(Class, AttributeType, AttributeName, AccessorMethod)
10/16/2007: olly
- [Tcl] Fix several ocurrences of "warning: deprecated conversion
+ [Tcl] Fix several occurrences of "warning: deprecated conversion
from string constant to 'char*'" from GCC 4.2 in generated C/C++
code.
@@ -4730,7 +6140,7 @@ Version 1.3.30 (November 13, 2006)
10/03/2006: wsfulton
[Ruby] Fix #1527885 - Overloaded director virtual methods sometimes produced
- uncompileable code when used with the director:except feature.
+ uncompilable code when used with the director:except feature.
10/03/2006: wsfulton
Directors: Directors are output in the order in which they are declared in
@@ -5205,7 +6615,7 @@ Version 1.3.29 (March 21, 2006)
6146 _std_containers.so
174 _std_containers.so.hidden
- Excecution times:
+ Execution times:
real 0m0.050s user 0m0.039s sys 0m0.005s _std_containers.so
real 0m0.039s user 0m0.026s sys 0m0.007s _std_containers.so.hidden
@@ -5291,7 +6701,7 @@ Version 1.3.29 (March 21, 2006)
protected methods by default.
In previous releases, you needed to use the 'dirprot'
- option to acheive the same.
+ option to achieve the same.
If you want, you can disable the new default behaviour,
use the 'nodirprot' option:
@@ -5618,7 +7028,7 @@ Version 1.3.28 (February 12, 2006)
%rename("%(utitle)s",%$isfunction,%$ismember) "";
- to avoid clashings with other swig macros/directives.
+ to avoid clashes with other swig macros/directives.
01/14/2006: cfisavage
[Ruby]
@@ -6639,7 +8049,7 @@ Version 1.3.28 (February 12, 2006)
12/10/2005: mmatus
[UTF]
- - Fix unneccessary calls to SWIG_TypeQuery for 'char *'
+ - Fix unnecessary calls to SWIG_TypeQuery for 'char *'
and 'wchar_t *', problem found by Clay Culver while
profiling the PyOgre project.
@@ -8928,7 +10338,7 @@ Version 1.3.23 (November 11, 2004)
wrapper method only and not the extra overloaded methods that SWIG generates.
For example:
- %feature("except") void hello(int i=0, double d=0.0);
+ %feature("except") hello(int i=0, double d=0.0);
void hello(int i=0, double d=0.0);
will apply the feature to all three wrapper methods, that is:
@@ -8939,7 +10349,7 @@ Version 1.3.23 (November 11, 2004)
If the default arguments are not specified in the feature:
- %feature("except") void hello(int i, double d);
+ %feature("except") hello(int i, double d);
void hello(int i=0, double d=0.0);
then the feature will only apply to this wrapper method:
@@ -9546,7 +10956,7 @@ Version 1.3.23 (November 11, 2004)
- Remove the ability to share type information by using c linking.
All type sharing happens through a global variable in the target language.
+ Remove SWIG_NOIMPORT, SWIG_RUNTIME, and related defines.
- + Depreciate -runtime, -noruntime command line options
+ + Deprecate -runtime, -noruntime command line options
+ Update test-suite common.mk to correctly build multicpptest
+ Remove reference to precommon.swg
+ Update the guile_gh interface to share data by a global var instead
@@ -9974,7 +11384,7 @@ Version 1.3.23 (November 11, 2004)
now if you have
- %pythonnondynamic(1) A;
+ %pythonnondynamic A;
struct A {
int a;
@@ -9992,11 +11402,11 @@ Version 1.3.23 (November 11, 2004)
Since this is a feature, you can use
- %pythonnondynamic(1);
+ %pythonnondynamic;
or
- %pythondynamic(0); [ Note: %pythondynamic since deprecated ]
+ %pythondynamic; [ Note: %pythondynamic since deprecated ]
to force all the wrapped classes to be "nondynamic" ones.
@@ -10314,7 +11724,7 @@ Version 1.3.22 (September 4, 2004)
...
}
- Previously, none of BIG, LARGE or BAR would have produced compileable code
+ Previously, none of BIG, LARGE or BAR would have produced compilable code
when using %javaconst(1).
06/27/2004: wsfulton
@@ -11721,7 +13131,7 @@ Version 1.3.20 (December 17, 2003)
11/30/2003: cheetah (William Fulton)
[Java] Fixed [ 766409 ] missing symbol SWIG_JavaThrowException during module load
- SWIGs internal functions are all static as there is no need for different SWIG
+ SWIG's internal functions are all static as there is no need for different SWIG
generated modules to share any code at runtime.
11/30/2003: beazley
@@ -11956,7 +13366,7 @@ Version 1.3.20 (December 17, 2003)
Suggested by Kerim Borchaev.
11/11/2003: beazley
- Configuration changes to make SWIG work on Mac OSX 10.3.x (Panther).
+ Configuration changes to make SWIG work on Mac OS X 10.3.x (Panther).
Tested with Python, Tcl, Perl, and Ruby---all of which seem to work.
11/08/2003: cheetah (William Fulton)
@@ -19706,13 +21116,13 @@ Version 1.3.6 (July 9, 2001)
class TestClass
{
public:
- TestClass() {};
- TestClass(int a) {};
- ~TestClass() {};
- unsigned long xyz(short k) {};
- unsigned long xyz(int n) {};
- static void static_func() {};
- static void static_func(int a) {};
+ TestClass() {}
+ TestClass(int a) {}
+ ~TestClass() {}
+ unsigned long xyz(short k) {}
+ unsigned long xyz(int n) {}
+ static void static_func() {}
+ static void static_func(int a) {}
};
void delete_TestClass(int a);
@@ -20788,9 +22198,9 @@ Version 1.3 Alpha 1 (February 11, 2000)
*** POTENTIAL INCOMPATIBILITY ***
1/30/00 : loic
- Conditionaly compile experimental code with --enable-experiment
+ Conditionally compile experimental code with --enable-experiment
configure flag.
- Fix .cvsignore to ignore configrue & yacc generated files
+ Fix .cvsignore to ignore configure & yacc generated files
1/28/00 : loic
Apply automake everywhere
@@ -21302,7 +22712,7 @@ Version 1.1 Patch 4 (January 4, 1998)
12/29/97: Fixed configure script and a few makefiles to support Python 1.5
12/29/97: Added 'embed15.i' library file. This file should be used to
- staticly link versions of Python 1.5. To make it the default,
+ statically link versions of Python 1.5. To make it the default,
simply copy 'swig_lib/python/embed15.i' to 'swig_lib/python/embed.i'
Version 1.1 Patch 3 (November 24, 1997)
@@ -22362,7 +23772,7 @@ Version 1.1b5 (March 12, 1997)
2/23/97 : Modified Python module to be better behaved under Windows
- Module initialization function is now properly exported.
- It should not be neccessary to explicitly export this function
+ It should not be necessary to explicitly export this function
yourself.
- Bizarre compilation problems when compiling the SWIG wrapper
diff --git a/CHANGES.current b/CHANGES.current
index d55bb97..b5b4567 100644
--- a/CHANGES.current
+++ b/CHANGES.current
@@ -2,68 +2,44 @@ Below are the changes for the current release.
See the CHANGES file for changes in older releases.
See the RELEASENOTES file for a summary of changes in each release.
-Version 2.0.12 (9 Feb 2014)
-===========================
-
-2014-01-16: wsfulton
- [PHP] Fix compilation error in ZTS mode (64 bit windows) due to incorrect placement
- of TSRMLS_FETCH() in SWIG_Php_GetModule() as reported by Mark Dawson-Butterworth.
-
-2014-01-13: kwwette
- [Octave] update support to Octave version 3.8.0
-
- - Octave 3.8.0 no longer defines OCTAVE_API_VERSION_NUMBER, but 3.8.1
- will define OCTAVE_{MAJOR,MINOR,PATCH}_VERSION instead: see
- http://hg.savannah.gnu.org/hgweb/octave/rev/b6b6e0dc700e
- So we now use a new macro SWIG_OCTAVE_PREREQ(major,minor,patch) to
- enable features requiring Octave version major.minor.patch or later.
-
- For Octave versions prior to 3.8.1, we reconstruct values for
- OCTAVE_{MAJOR,MINOR,PATCH}_VERSION based on OCTAVE_API_VERSION_NUMBER,
- extracted from Octave's ChangeLogs. An additional hack is needed to
- distinguish between Octave <= 3.2.x and 3.8.0, neither of which define
- OCTAVE_API_VERSION_NUMBER.
-
- - Octave 3.8.0 deprecates symbol_table::varref(), so remove its use
- for this and future versions of Octave.
-
- - Octave 3.8.0 removes octave_value::is_real_nd_array(), used in
- octave_swig_type::dims(). Its use is not required here, so remove it.
-
- - Retested against Octave versions 3.0.5, 3.2.4, 3.4.3, 3.6.4, and 3.8.0.
-
- - Updated Octave documentation with tested Octave versions, and added a
- warning against using versions <= 3.x.x, which are no longer tested.
-
-2013-12-22: wsfulton
- C++11 support for new versions of erase and insert in the STL containers.
-
- The erase and insert methods in the containers use const_iterator instead
- of iterator in C++11. There are times when the methods wrapped must match
- the parameters exactly. Specifically when full type information for
- template types is missing or SWIG fails to look up the type correctly,
- for example:
-
- %include C++0x/C++11 support for SWIG
+Summary
+SVN branch
+New C++11 features status
+Rvalue reference and move semantics [done]
+template <class T> swap(T& a, T& b) {
+ T tmp(a); // now we have two copies of a
+ a = b; // now we have two copies of b
+ b = tmp; // now we have two copies of tmp (aka a)
+}
template <class T> swap(T& a, T& b) {
+ T tmp(std::move(a));
+ a = std::move(b);
+ b = std::move(tmp);
+}
class MyClass {
+ MyClass(MyClass&& p) : ptr(p.ptr) {p.ptr = 0;}
+ MyClass& operator=(MyClass&& p) {
+ std::swap(ptr, p.ptr);
+ return *this;
+ }
+};
Generalized constant expressions [done]
+Extern template [done]
+Initializer lists [done]
+ class A {
+ public:
+ A( std::initializer_list<int> );
+ };
+ A a1 = {1,2,3,4};
Uniform initialization [done]
+struct IdString {
+ std::string name;
+ int identifier;
+};
+
+IdString GetString() {
+ return {"SomeName", 4}; //Note the lack of explicit type.
+}
IdString str1 = {âSomeNameâ, 4};
+IdString str2{âSomeNameâ, 4};
struct BasicStruct {
+ int x;
+ double y;
+};
+
+struct AltStruct {
+ AltStruct(int x, double y) : x_{x}, y_{y} {}
+
+private:
+ int x_;
+ double y_;
+};
+
+BasicStruct var1{5, 3.2}; // only fills the struct components
+AltStruct var2{2, 4.3}; // calls the constructor
Type inference [partially done]
+auto a1 = 100;
+auto a2 = myFunc();
int i = 100;
+decltype(i) j = 200; // decltype(i) = int
decltype(i+j) k = 300;
Range-based for-loop [ignored]
+Lambda functions and expressions [done]
+[](int x, int y) -> int { return x + y; }
std::vector<int> someList;
+int total = 0;
+std::for_each( someList.begin(), someList.end(), [&total](int x) {total += x} );
+std::cout << total;
auto myLambdaFunc = [this]() { this->SomePrivateMemberFunction() };
Alternate function syntax [done]
+template< typename LHS, typename RHS>
+ decltype(lhs+rhs) AddingFunc(const LHS &lhs, const RHS &rhs) {return lhs + rhs;} //Not legal C++11
template< typename LHS, typename RHS>
+ auto AddingFunc(const LHS &lhs, const RHS &rhs) -> decltype(lhs+rhs) {return lhs + rhs;}
struct SomeStruct {
+ auto FuncName(int x, int y) -> int;
+};
+
+auto SomeStruct::FuncName(int x, int y) -> int {
+ return x + y;
+}
Concepts, Axioms [ignored]
+ template<LessThanComparable? T>
+ const T& min(const T &x, const T &y) {
+ return y < x ? y : x;
+ }
template< typename T> requires LessThanComparable?<T>
+ const T& min(const T &x, const T &y) {
+ return y < x ? y : x;
+ }
concept LessThanComparable?< typename T > {
+ bool operator<(T,T);
+ requires GreaterThanComparable?<T>;
+ typename value_type;
+ typename reference;
+ };
template< typename T>
+ concept_map InputIterator?<T*> {
+ typedef T value_type ;
+ typedef T& reference ;
+ typedef T* pointer ;
+ typedef std::ptrdiff_t difference_type ;
+ };
concept Stack< typename X> {
+ typename value_type;
+ void push(X&, const value_type&);
+ void pop(X&);
+ value_type top(const X&);
+ bool empty(const X&);
+ };
+ template< typename T>
+ concept_map Stack<std::vector<T> > {
+ typedef T value_type;
+ void push(std::vector<T>& v, const T& x) { v.push_back(x); }
+ void pop(std::vector<T>& v) { v.pop_back(); }
+ T top(const std::vector<T>& v) { return v.back(); }
+ bool empty(const std::vector<T>& v) { return v.empty(); }
+ };
concept Semigroup< typename Op, typename T> : CopyConstructible?<T> {
+ T operator()(Op, T, T);
+ axiom Associativity(Op op, T x, T y, T z) {
+ op(x, op(y, z)) == op(op(x, y), z);
+ }
+ };
Object construction improvement [done]
+ class SomeType {
+ int number;
+ public:
+ SomeType(int newNumber) : number(newNumber) {}
+ SomeType() : SomeType(42) {}
+ };
class BaseClass {
+ public:
+ BaseClass(int iValue);
+ };
+ class DerivedClass: public BaseClass {
+ public:
+ using BaseClass::BaseClass; // Adds DerivedClass(int) constructor
+ };
Null pointer constant [done]
+Strongly typed enumerations [partially done]
+ enum class Enumeration {
+ Val1,
+ Val2,
+ Val3 = 100,
+ Val4 /* = 101 */
+ };
enum class Enum2 : unsigned int {Val1, Val2};
enum Enum1; //Illegal in C++ and C++11; no size is explicitly specified.
+ enum Enum2 : unsigned int; //Legal in C++11.
+ enum class Enum3; //Legal in C++11, because enum class declarations have a default type of "int".
+ enum class Enum4: unsigned int; //Legal C++11.
+ enum Enum2 : unsigned short; //Illegal in C++11, because Enum2 was previously declared with a different type.
class A { enum class EA { a,b,c,d }; };
class A { class EA { enum {a,b,c,d}; }; };
+Angle bracket [done]
+Explicit conversion operators [done]
+Template typedefs [partially done]
+template< typename first, typename second, int third>
+class SomeType;
+
+template< typename second>
+typedef SomeType<OtherType, second, 5> TypedefName; //Illegal in C++
template< typename first, typename second, int third>
+class SomeType;
+
+template< typename second>
+using TypedefName = SomeType<OtherType, second, 5>;
typedef void (*PFD)(double); // Old style
+using PF = void (*)(double); // New introduced syntax
typedef List<int> intList;
Unrestricted unions [done]
+ struct point {
+ point() {}
+ point(int x, int y): x_(x), y_(y) {}
+ int x_, y_;
+ };
+ union P {
+ int z;
+ double w;
+ point p; // Illegal in C++; point has a non-trivial constructor. However, this is legal in C++11.
+ } p1;
Variadic templates [partially done]
+template<typename... Values> class tuple;
class tuple<int, std::vector<int>, std::map<std::string, std::vector<int>>> someInstanceName;
void printf(const char *s) {
+ while (*s) {
+ if (*s == '%' && *(++s) != '%')
+ throw std::runtime_error("invalid format string: missing arguments");
+ std::cout << *s++;
+ }
+}
+
+template<typename T, typename... Args>
+void printf(const char* s, T value, Args... args) { // recursive action â split previous args to value + args
+ while (*s) {
+ if (*s == '%' && *(++s) != '%') {
+ std::cout << value;
+ printf(*s ? ++s : s, args...); // call even when *s == 0 to detect extra arguments
+ return;
+ }
+ std::cout << *s++;
+ }
+ throw std::logic_error("extra arguments provided to printf");
+}
template <typename... BaseClasses> class ClassName : public BaseClasses... {
+public:
+
+ ClassName (BaseClasses&&... baseClasses) : BaseClasses(baseClasses)... {}
+}
template<typename ...Args> struct SomeStruct {
+ static const int size = sizeof...(Args);
+}
+// SomeStruct<Type1, Type2>::size is 2 and SomeStruct<>::size is 0
New string literals [partially done]
+User-defined literals [partially done]
+ OutputType operator "" _mySuffix(const char * string_values);
OutputType operator "" _mySuffix(const char * string_values, size_t num_chars);
+ OutputType operator "" _mySuffix(const wchar_t * string_values, size_t num_chars);
+ OutputType operator "" _mySuffix(const char16_t * string_values, size_t num_chars);
+ OutputType operator "" _mySuffix(const char32_t * string_values, size_t num_chars);
+ OutputType operator "" _mySuffix(int value); /* cooked version - ie. atoi() of string */
template<char...> OutputType operator "" _mySuffix();
+ OutputType someVariable = "1234"_mySuffix;
Thread-local storage [done]
+
+ struct A {
+ thread_local int val;
+ };
Defaulting/deleting of standard functions on C++ objects [done]
+ struct NonCopyable {
+ NonCopyable & operator=(const NonCopyable&) = delete; /* Removes operator= */
+ NonCopyable(const NonCopyable&) = delete; /* Removed copy constructor */
+ NonCopyable() = default; /* Explicitly allows the empty constructor */
+ void *operator new(std::size_t) = delete; /* Removes new NonCopyable */
+ };
struct A1 {
+ void f(int i);
+ void f(double i) = delete; /* Don't cast double to int. Compiler returns an error */
+ };
+ struct A2 {
+ void f(int i);
+ template<class T> void f(T) = delete; /* Only accept int */
+ };
Type long long int [done]
+Static assertions [done]
+ template <typename T>
+ struct Check {
+ static_assert(sizeof(int) <= sizeof(T), "not big enough");
+ };
Allow sizeof to work on members of classes without an explicit
+object [done]
+ struct A { int member; };
+ sizeof(A::member); //Does not work with C++03. Okay with C++11
Threading facilities [ignored]
+ * std::thread
+ * std::mutex, std::recursive_mutex
+ * std::condition_variable, std::condition_variable_any
+ * std::lock_guard, std::unique_lock
+ * std::packaged_task
Tuple types [TODO]
+template <class ...Types> class tuple;
typedef tuple< int, double, long &, const char * > test_tuple ;
+long lengthy = 12 ;
+test_tuple proof( 18, 6.5, lengthy, "Ciao!" ) ;
+lengthy = get<0>(proof) ; // Assign to 'lengthy' the value 18.
+get<3>(proof) = " Beautiful!" ; // Modify the tupleâs fourth element.
typedef tuple< int , double, string > tuple_1 t1 ;
+typedef tuple< char, short , const char * > tuple_2 t2( 'X', 2, "Hola!" ) ;
+t1 = t2 ; // Ok, first two elements can be converted,
+ // the third one can be constructed from a 'const char *'.
Hash tables [TODO]
+ - unordered set
+ - unordered multiset
+ - unordered map
+ - unordered multimap
Regular expressions [ignored]
+General-purpose smart pointers [done]
+Extensible random number facility [ignored]
+Wrapper reference [ignored]
+Polymorphous wrappers for function objects [done]
+
+
+ function<int ( int, int )> pF;
+
+
+ struct Test {
+ bool operator()( short x, short y );
+ };
Type traits for metaprogramming [ignored]
+ template< int B, int N >
+ struct Pow {
+ // recursive call and recombination.
+ enum{ value = B*Pow< B, N-1 >::value };
+ };
+ template< int B > struct Pow< B, 0 > // N == 0 condition of termination.
+ {
+ enum{ value = 1 };
+ };
+ int quartic_of_three = Pow< 3, 4 >::value ;
// First way of operating.
+template< bool B > struct algorithm {
+ template< class T1, class T2 > int do_it( T1 &, T2 & ) { /*...*/ }
+};
+// Second way of operating.
+template<> struct algorithm<true> {
+ template< class T1, class T2 > int do_it( T1, T2 ) { /*...*/ }
+};
+// Instantiating 'elaborate' will automatically instantiate the correct way to operate.
+template< class T1, class T2 > int elaborate( T1 A, T2 B ) {
+ // Use the second way only if 'T1' is an integer and if 'T2' is
+ // in floating point, otherwise use the first way.
+ return algorithm< is_integral<T1>::value && is_floating_point<T2>::value >::do_it( A, B );
+}
Uniform method for computing return type of function objects
+[partially done]
+template< class Obj >
+class calculus_ver2 {
+ public:
+ template< class Arg >
+ typename std::result_of<Obj(Arg)>::type operator()( Arg& a ) const {
+ return member(a);
+ }
+ private:
+ Obj member;
+};
@@ -844,7 +844,7 @@ Returns a type object corresponding to the type string produced by the Swig_cloc
This function is the inverse of the clocal() function. Given a type and a name,
it produces a string containing the code needed to cast/convert the type produced by
-Swig_clocal() back into it's original type.
+Swig_clocal() back into its original type.
diff --git a/Doc/Devel/tree.html b/Doc/Devel/tree.html
index db3c6fe..73a49ed 100644
--- a/Doc/Devel/tree.html
+++ b/Doc/Devel/tree.html
@@ -185,7 +185,7 @@ this function merely records that those attributes did not exist in the original
This function is similar to Swig_save() except that adds additional attribute checking. There are different interpretations
of the attribute names. A name of "attr" merely requests that the function check for the presence of an attribute. If the attribute is missing, SWIG will exit with a failed assertion. An attribute name of "?attr" specifies that the attribute "attr" is optional and
-that it's old value must be saved (if any). An attribute name of "*attr" specifies that the attribute is required and that
+that its old value must be saved (if any). An attribute name of "*attr" specifies that the attribute is required and that
its value must be saved. The saving of attributes is performed in the same manner as with Swig_save(). Here is an example:
diff --git a/Doc/Manual/Allegrocl.html b/Doc/Manual/Allegrocl.html
index 12b915e..4b6bad4 100644
--- a/Doc/Manual/Allegrocl.html
+++ b/Doc/Manual/Allegrocl.html
@@ -1,14 +1,14 @@
-
-
+
17 SWIG and Allegro Common Lisp
+18 SWIG and Allegro Common Lisp
@@ -135,10 +135,10 @@ be unhappy to see some enterprising folk use this work to add
to it.
-
17.1 Basics
+18.1 Basics
-17.1.1 Running SWIG
+18.1.1 Running SWIG
17.1.2 Command Line Options
+18.1.2 Command Line Options
@@ -436,7 +436,7 @@ Note that the block %{ ... %} is effectively a shortcut for
-@@ -446,7 +446,7 @@ New users to SWIG are encouraged to read interested in generating an interface to C++.
-@@ -472,7 +472,7 @@ interested in generating an interface to C++. | Foreign Code | What we're generating an interface to. |______________| | - | + | _______v______ | | (foreign side) | Wrapper code | extern "C" wrappers calling C++ @@ -484,22 +484,22 @@ interested in generating an interface to C++. | FFI Layer | Low level lisp interface. ff:def-foreign-call, |______________| ff:def-foreign-variable | - +---------------------------- + +---------------------------- _______v______ _______v______ | | | | (lisp side) | Defuns | | Defmethods | wrapper for overloaded |______________| |______________| functions or those with (lisp side) | defaulted arguments - Wrapper for non-overloaded | - functions and methods _______v______ - | | (lisp side) - | Defuns | dispatch function - |______________| to overloads based - on arity + Wrapper for non-overloaded | + functions and methods _______v______ + | | (lisp side) + | Defuns | dispatch function + |______________| to overloads based + on arity -
@@ -512,7 +512,7 @@ interested in generating an interface to C++. typemap.
-@@ -593,7 +593,7 @@ char *xxx(); ff:def-foreign-call's.
-@@ -606,7 +606,7 @@ char *xxx(); this function can be manipulated via the lout typemap.
-@@ -622,7 +622,7 @@ char *xxx(); can be manipulated via the lout typemap.
-@@ -635,7 +635,7 @@ char *xxx(); into the foreign module.
-@@ -657,7 +657,7 @@ char *xxx(); foreign function interface.
-@@ -665,7 +665,7 @@ char *xxx(); translated into lisp.
-@@ -742,13 +742,13 @@ namespace car { function such as (car '(1 2 3).
-Constants, as declared by the preprocessor #define macro or SWIG - %constant directive, are included in SWIGs parse tree + %constant directive, are included in SWIG's parse tree when it can be determined that they are, or could be reduced to, a literal value. Such values are translated into defconstant forms in the generated lisp wrapper when the -nocwrap command-line @@ -799,11 +799,11 @@ namespace car {
- Users are cautioned to get to know their constants before use, or - not use the -nocwrap command-line option. + Users are cautioned to get to know their constants before use, or + not use the -nocwrap command-line option.
-@@ -881,13 +881,13 @@ globalvar> (globalvar.nnn::glob_float) -
In C, an enumeration value is an integer value, while in C++ an enumeration value is implicitly convertible to an integer value, - but can also be distinguished by it's enum type. For each enum + but can also be distinguished by its enum type. For each enum declaration a def-foreign-type is generated, assigning the enum a default type of :int. Users may adjust the foreign type of enums via SWIG typemaps. @@ -901,13 +901,13 @@ globalvar> (globalvar.nnn::glob_float) of it not being necessary to probe into foreign space to retrieve enum values. When generating a .cxx wrapper file, a more general solution is employed. A wrapper variable is created in the module_wrap.cxx file, and - a ff:def-foreign-variable call is generated to retrieve it's value into lisp. + a ff:def-foreign-variable call is generated to retrieve its value into lisp.
For example, the following header file
-enum COL { RED, GREEN, BLUE }; +enum COL { RED, GREEN, BLUE }; enum FOO { FOO1 = 10, FOO2, FOO3 };
@@ -1105,10 +1105,10 @@ namespace BAR { -
@@ -1123,7 +1123,7 @@ namespace BAR { integer values.
-@@ -1131,12 +1131,12 @@ namespace BAR { inheritance of the classes in foreign code, with the ff:foreign-pointer class at its root. ff:foreign-pointer is a thin wrapper for pointers that is made available by the foreign function - interface. It's key benefit is that it may be passed as an argument + interface. Its key benefit is that it may be passed as an argument to any ff:def-foreign-call that is expecting a pointer as the parameter.
-@@ -1152,7 +1152,7 @@ namespace BAR { the interface does nothing for friend directives,
-@@ -1170,34 +1170,34 @@ namespace BAR { use the more robust wrapper functions.
-- SWIG provides support for dealing with templates, but by - default, it will not generate any member variable or function - wrappers for templated classes. In order to create these - wrappers, you need to explicitly tell SWIG to instantiate - them. This is done via the - %template - directive. -
++SWIG provides support for dealing with templates, but by +default, it will not generate any member variable or function +wrappers for templated classes. In order to create these +wrappers, you need to explicitly tell SWIG to instantiate +them. This is done via the +%template +directive. +
-- While no wrapper code is generated for accessing member - variables, or calling member functions, type code is generated - to include these templated classes in the foreign-type and CLOS - class schema. -
++While no wrapper code is generated for accessing member +variables, or calling member functions, type code is generated +to include these templated classes in the foreign-type and CLOS +class schema. +
-@@ -1243,7 +1243,7 @@ int zzz(A *inst = 0); /* return inst->x + inst->y */ definition, we generate a form that expands to:
The result is that all references to synonym types in foreign @@ -1277,7 +1277,7 @@ synonym> -
@@ -1285,20 +1285,20 @@ synonym> criteria from a set of synonym types.
@@ -1461,7 +1461,7 @@ overload> -
@@ -1472,68 +1472,68 @@ overload>
/* name conversion for overloaded operators. */ #ifdef __cplusplus -%rename(__add__) *::operator+; -%rename(__pos__) *::operator+(); -%rename(__pos__) *::operator+() const; +%rename(__add__) *::operator+; +%rename(__pos__) *::operator+(); +%rename(__pos__) *::operator+() const; -%rename(__sub__) *::operator-; -%rename(__neg__) *::operator-() const; -%rename(__neg__) *::operator-(); +%rename(__sub__) *::operator-; +%rename(__neg__) *::operator-() const; +%rename(__neg__) *::operator-(); -%rename(__mul__) *::operator*; -%rename(__deref__) *::operator*(); -%rename(__deref__) *::operator*() const; +%rename(__mul__) *::operator*; +%rename(__deref__) *::operator*(); +%rename(__deref__) *::operator*() const; -%rename(__div__) *::operator/; -%rename(__mod__) *::operator%; -%rename(__logxor__) *::operator^; -%rename(__logand__) *::operator&; -%rename(__logior__) *::operator|; -%rename(__lognot__) *::operator~(); -%rename(__lognot__) *::operator~() const; +%rename(__div__) *::operator/; +%rename(__mod__) *::operator%; +%rename(__logxor__) *::operator^; +%rename(__logand__) *::operator&; +%rename(__logior__) *::operator|; +%rename(__lognot__) *::operator~(); +%rename(__lognot__) *::operator~() const; -%rename(__not__) *::operator!(); -%rename(__not__) *::operator!() const; +%rename(__not__) *::operator!(); +%rename(__not__) *::operator!() const; -%rename(__assign__) *::operator=; +%rename(__assign__) *::operator=; %rename(__add_assign__) *::operator+=; -%rename(__sub_assign__) *::operator-=; -%rename(__mul_assign__) *::operator*=; -%rename(__div_assign__) *::operator/=; -%rename(__mod_assign__) *::operator%=; +%rename(__sub_assign__) *::operator-=; +%rename(__mul_assign__) *::operator*=; +%rename(__div_assign__) *::operator/=; +%rename(__mod_assign__) *::operator%=; %rename(__logxor_assign__) *::operator^=; %rename(__logand_assign__) *::operator&=; %rename(__logior_assign__) *::operator|=; -%rename(__lshift__) *::operator<<; +%rename(__lshift__) *::operator<<; %rename(__lshift_assign__) *::operator<<=; -%rename(__rshift__) *::operator>>; +%rename(__rshift__) *::operator>>; %rename(__rshift_assign__) *::operator>>=; -%rename(__eq__) *::operator==; -%rename(__ne__) *::operator!=; -%rename(__lt__) *::operator<; -%rename(__gt__) *::operator>; -%rename(__lte__) *::operator<=; -%rename(__gte__) *::operator>=; +%rename(__eq__) *::operator==; +%rename(__ne__) *::operator!=; +%rename(__lt__) *::operator<; +%rename(__gt__) *::operator>; +%rename(__lte__) *::operator<=; +%rename(__gte__) *::operator>=; -%rename(__and__) *::operator&&; -%rename(__or__) *::operator||; +%rename(__and__) *::operator&&; +%rename(__or__) *::operator||; -%rename(__preincr__) *::operator++(); -%rename(__postincr__) *::operator++(int); -%rename(__predecr__) *::operator--(); -%rename(__postdecr__) *::operator--(int); +%rename(__preincr__) *::operator++(); +%rename(__postincr__) *::operator++(int); +%rename(__predecr__) *::operator--(); +%rename(__postdecr__) *::operator--(int); -%rename(__comma__) *::operator,(); -%rename(__comma__) *::operator,() const; +%rename(__comma__) *::operator,(); +%rename(__comma__) *::operator,() const; %rename(__member_ref__) *::operator->; %rename(__member_func_ref__) *::operator->*; -%rename(__funcall__) *::operator(); -%rename(__aref__) *::operator[]; +%rename(__funcall__) *::operator(); +%rename(__aref__) *::operator[];@@ -1607,7 +1607,7 @@ opoverload> -
@@ -1617,7 +1617,7 @@ opoverload> directive. This directive allows you to specify a (finite) argument list which will be inserted into the wrapper in place of the variable length argument indicator. As an example, - consider the function printf(). It's declaration would + consider the function printf(). Its declaration would appear as follows:
@@ -1628,7 +1628,7 @@ opoverload> with other ways such functions can be wrapped. -@@ -1640,7 +1640,7 @@ opoverload> implemented.
-@@ -1652,7 +1652,7 @@ opoverload> newly defined types.
-@@ -1663,7 +1663,7 @@ opoverload> on Typemaps for more information.
-@@ -1728,14 +1728,14 @@ return-val wrapper-name(parm0, parm1, ..., parmN) -
The out typemap is used to generate code to form the return value of the wrapper from the return value of the wrapped function. This code is placed in the <convert and bind result to lresult> - section of the above code diagram. It's default mapping is as follows: + section of the above code diagram. Its default mapping is as follows:
This typemap is not used for code generation, but purely for the transformation of types in the parameter list of the wrapper function. - It's primary use is to handle by-value to by-reference conversion in the + Its primary use is to handle by-value to by-reference conversion in the wrappers parameter list. Its default settings are:
@@ -1784,7 +1784,7 @@ return-val wrapper-name(parm0, parm1, ..., parmN) these common typemaps here. -@@ -1803,7 +1803,7 @@ return-val wrapper-name(parm0, parm1, ..., parmN) 16.3.1 Namespaces for details.
-@@ -1821,32 +1821,32 @@ return-val wrapper-name(parm0, parm1, ..., parmN)
The LIN typemap accepts the following $variable references.
-%typemap(lin) SWIGTYPE "(cl:let (($out $in))\n $body)"; +%typemap(lin) SWIGTYPE "(cl:let (($out $in))\n $body)";
@@ -1858,17 +1858,17 @@ return-val wrapper-name(parm0, parm1, ..., parmN)
The LOUT typemap uses the following $variable
@@ -1959,7 +1959,7 @@ return-val wrapper-name(parm0, parm1, ..., parmN) -
@@ -1983,7 +1983,7 @@ return-val wrapper-name(parm0, parm1, ..., parmN) -
@@ -2017,10 +2017,10 @@ return-val wrapper-name(parm0, parm1, ..., parmN) -
@@ -2041,11 +2041,11 @@ return-val wrapper-name(parm0, parm1, ..., parmN) of arguments.
-Two basic identifier routines have been defined. -
@@ -2054,7 +2054,7 @@ return-val wrapper-name(parm0, parm1, ..., parmN) strings, from which a symbol will be created.
-@@ -2063,7 +2063,7 @@ return-val wrapper-name(parm0, parm1, ..., parmN) same symbol transformations.
-@@ -2072,7 +2072,7 @@ return-val wrapper-name(parm0, parm1, ..., parmN) default naming conventions.
-@@ -2093,7 +2093,7 @@ foreign environment.
The :type keyword argument provides more information on the type of -identifier. It's value is a symbol. This allows the +identifier. Its value is a symbol. This allows the identifier-converter to apply different heuristics when mapping different types of identifiers to symbols. SWIG will generate calls to your identifier-converter using the following types. @@ -2123,12 +2123,12 @@ scope in the specified class.
The :arity keyword argument only appears in swig:swig-defmethod forms -generated for overloaded functions. It's value is an integer +generated for overloaded functions. Its value is an integer indicating the number of arguments passed to the routine indicated by this identifier.
-diff --git a/Doc/Manual/Android.html b/Doc/Manual/Android.html index 4d1be39..8838e67 100644 --- a/Doc/Manual/Android.html +++ b/Doc/Manual/Android.html @@ -1,11 +1,12 @@ - +
The Android chapter is fairly short as support for Android is the same as for Java, where the Java Native Interface (JNI) is used to call from Android Java into C or C++ compiled code. -Everything in the Java chapter applies to generating code for access from Android Java code. +Everything in the Java chapter applies to generating code for access from Android Java code. This chapter contains a few Android specific notes and examples.
--The examples require the Android SDK and Android NDK which can be installed as per instructions in the links. +The examples require the Android SDK and Android NDK which can be installed as per instructions in the links. The Eclipse version is not required for these examples as just the command line tools are used (shown for Linux as the host, but Windows will be very similar, if not identical in most places). Add the SDK tools and NDK tools to your path and create a directory somewhere for your Android projects (adjust PATH as necessary to where you installed the tools):
@@ -56,7 +57,7 @@ Add the SDK tools and NDK tools to your path and create a directory somewhere fo$ export PATH=$HOME/android/android-sdk-linux_x86/tools:$HOME/android/android-sdk-linux_x86/platform-tools:$HOME/android/android-ndk-r6b:$PATH $ mkdir AndroidApps -$ cd AnrdoidApps +$ cd AndroidApps
@@ -209,7 +210,7 @@ When complete your device should be listed in those attached, something like:
$ adb devices List of devices attached -A32-6DBE0001-9FF80000-015D62C3-02018028 device +A32-6DBE0001-9FF80000-015D62C3-02018028 device@@ -221,7 +222,7 @@ This means you are now ready to install the application...
$ adb install bin/SwigSimple-debug.apk 95 KB/s (4834 bytes in 0.049s) - pkg: /data/local/tmp/SwigSimple-debug.apk + pkg: /data/local/tmp/SwigSimple-debug.apk Success@@ -398,7 +399,7 @@ Run the app again and this time you will see the output pictured below, showing
@@ -435,11 +436,11 @@ public: } virtual ~Shape() { nshapes--; - }; + } double x, y; void move(double dx, double dy); - virtual double area(void) = 0; - virtual double perimeter(void) = 0; + virtual double area() = 0; + virtual double perimeter() = 0; static int nshapes; }; @@ -447,18 +448,18 @@ class Circle : public Shape { private: double radius; public: - Circle(double r) : radius(r) { }; - virtual double area(void); - virtual double perimeter(void); + Circle(double r) : radius(r) { } + virtual double area(); + virtual double perimeter(); }; class Square : public Shape { private: double width; public: - Square(double w) : width(w) { }; - virtual double area(void); - virtual double perimeter(void); + Square(double w) : width(w) { } + virtual double area(); + virtual double perimeter(); }; @@ -482,19 +483,19 @@ void Shape::move(double dx, double dy) { int Shape::nshapes = 0; -double Circle::area(void) { +double Circle::area() { return M_PI*radius*radius; } -double Circle::perimeter(void) { +double Circle::perimeter() { return 2*M_PI*radius; } -double Square::area(void) { +double Square::area() { return width*width; } -double Square::perimeter(void) { +double Square::perimeter() { return 4*width; } @@ -746,7 +747,7 @@ Run the app to see the result of calling the C++ code from Java:
@@ -758,7 +759,7 @@ Note that the 'extend' example is demonstrates the directors feature. Normally C++ exception handling and the STL is not available by default in the version of g++ shipped with Android, but this example turns these features on as described in the next section.
-diff --git a/Doc/Manual/Arguments.html b/Doc/Manual/Arguments.html index 1ae9a6d..48ec5c6 100644 --- a/Doc/Manual/Arguments.html +++ b/Doc/Manual/Arguments.html @@ -1,12 +1,13 @@ - +
@@ -50,7 +51,7 @@ This section describes the typemaps.i library file--commonly used to change certain properties of argument conversion.
-@@ -59,7 +60,7 @@ Suppose you had a C function like this:
void add(double a, double b, double *result) { - *result = a + b; + *result = a + b; }
@@ -203,7 +204,7 @@ input value:
-int *INPUT +int *INPUT short *INPUT long *INPUT unsigned int *INPUT @@ -220,7 +221,7 @@ function:@@ -247,7 +248,7 @@ When the function is used in the scripting language interpreter, it will work li result = add(3,4)double add(double *a, double *b) { - return *a+*b; + return *a+*b; }
@@ -272,7 +273,7 @@ These methods can be used as shown in an earlier example. For example, if you ha
void add(double a, double b, double *c) { - *c = a+b; + *c = a+b; }
@@ -338,7 +339,7 @@ A C function that uses this might be something like this:
void negate(double *x) { - *x = -(*x); + *x = -(*x); }
@@ -413,7 +414,7 @@ Typemap declarations are lexically scoped so a typemap takes effect from the poi file or a matching %clear declaration.
-@@ -423,7 +424,7 @@ insure that a value is positive, or that a pointer is non-NULL. This can be accomplished including the constraints.i library file.
-@@ -449,7 +450,7 @@ the arguments violate the constraint condition, a scripting language exception will be raised. As a result, it is possible to catch bad values, prevent mysterious program crashes and so on.
-@@ -465,7 +466,7 @@ NONNULL Non-NULL pointer (pointers only). -
diff --git a/Doc/Manual/CCache.html b/Doc/Manual/CCache.html index 7db5583..d23b0cb 100644 --- a/Doc/Manual/CCache.html +++ b/Doc/Manual/CCache.html @@ -1,12 +1,13 @@ - +
-
@@ -42,7 +43,7 @@ ccache-swig - a fast compiler cache
-
@@ -52,16 +53,16 @@ ccache-swig <compiler> [COMPILER OPTIONS]
<compiler> [COMPILER OPTIONS]
-
-ccache-swig is a compiler cache. It speeds up re-compilation of C/C++/SWIG code +ccache-swig is a compiler cache. It speeds up re-compilation of C/C++/SWIG code by caching previous compiles and detecting when the same compile is being done again. ccache-swig is ccache plus support for SWIG. ccache and ccache-swig are used interchangeably in this document.
-
@@ -81,7 +82,7 @@ Here is a summary of the options to ccache-swig.
-
@@ -98,7 +99,7 @@ statistics are stored spread across the subdirectories of the cache. Using "ccache-swig -s" adds up the statistics across all subdirectories and prints the totals.
-
@@ -123,7 +124,7 @@ rounded down to the nearest multiple of 16 kilobytes.
-
@@ -135,7 +136,7 @@ some specific projects. The second method is most useful for when you wish to use ccache for all your compiles.
To install for usage by the first method just copy ccache-swig to somewhere -in your path. +in your path.
To install for the second method do something like this:
@@ -155,7 +156,7 @@ This will work as long as /usr/local/bin comes before the path to gcc Note! Do not use a hard link, use a symbolic link. A hardlink will cause "interesting" problems.-
16.7 EXTRA OPTIONS
+17.7 EXTRA OPTIONS
@@ -163,7 +164,7 @@ When run as a compiler front end ccache usually just takes the same command line options as the compiler you are using. The only exception to this is the option '--ccache-skip'. That option can be used to tell ccache that the next option is definitely not a input filename, and -should be passed along to the compiler as-is. +should be passed along to the compiler as-is.
The reason this can be important is that ccache does need to parse the command line and determine what is an input filename and what is a @@ -175,7 +176,7 @@ file). By using --ccache-skip you can force an option to not be treated as an input file name and instead be passed along to the compiler as a command line option.
-
16.8 ENVIRONMENT VARIABLES
+17.8 ENVIRONMENT VARIABLES
@@ -247,7 +248,7 @@ each compile.
-
-
@@ -327,18 +328,18 @@ When these limits are reached ccache will reduce the cache to 20% below the numbers you specified in order to avoid doing the cache clean operation too often.
-
-By default on most platforms ccache will compress all files it puts +By default on most platforms ccache will compress all files it puts into the cache using the zlib compression. While this involves a negligible performance slowdown, it significantly increases the number of files that fit in the cache. You can turn off compression setting the CCACHE_NOCOMPRESS environment variable.
-
@@ -363,7 +364,7 @@ compiler output that you would get without the cache. If you ever discover a case where ccache changes the output of your compiler then please let me know.
-
@@ -375,9 +376,9 @@ ccache avoids the compile completely where possible. To use distcc with ccache I recommend using the CCACHE_PREFIX option. You just need to set the environment variable CCACHE_PREFIX to 'distcc' and ccache will prefix the command line used with the -compiler with the command 'distcc'. +compiler with the command 'distcc'.
-
@@ -397,7 +398,7 @@ following conditions need to be met: to 002, this ensures that cached files are accessible to everyone in the group.
-
ccache was inspired by the compilercache shell script script written by Erik Thiele and I would like to thank him for an excellent piece of -work. See +work. See http://www.erikyyy.de/compilercache/ for the Erik's scripts. ccache-swig is a port of the original ccache with support added for use @@ -422,7 +423,7 @@ I wrote ccache because I wanted to get a bit more speed out of a compiler cache and I wanted to remove some of the limitations of the shell-script version.
-
@@ -440,7 +441,7 @@ are:
-
@@ -452,7 +453,7 @@ Thanks to the following people for their contributions to ccache
-
@@ -471,5 +472,3 @@ later. Please see the file COPYING for license details. - - diff --git a/Doc/Manual/CPlusPlus11.html b/Doc/Manual/CPlusPlus11.html new file mode 100644 index 0000000..714845b --- /dev/null +++ b/Doc/Manual/CPlusPlus11.html @@ -0,0 +1,1184 @@ + + +
+This chapter gives you a brief overview about the SWIG +implementation of the C++11 standard. This part of SWIG is still a work in +progress. +
+SWIG supports the new C++ syntax changes with some minor limitations +in some areas such as decltype expressions and variadic templates. Wrappers for the +new STL types (unordered_ containers, result_of, tuples) are incomplete. +The wrappers for the new containers would work much like the C++03 containers and +users are welcome to help by adapting the existing container interface files and submitting them +as a patch for inclusion in future versions of SWIG. +
+ ++SWIG correctly parses the rvalue reference syntax '&&', +for example the typical usage of it in the move constructor and move assignment operator below: +
+ ++class MyClass { +... + std::vector<int> numbers; +public: + MyClass(MyClass &&other) : numbers(std::move(other.numbers)) {} + MyClass & operator=(MyClass &&other) { + numbers = std::move(other.numbers); + return *this; + } +}; +
+Rvalue references are designed for C++ temporaries and so are not very useful when used from non-C++ target languages. +Generally you would just ignore them via %ignore before parsing the class. +For example, ignore the move constructor: +
+ ++%ignore MyClass::MyClass(MyClass &&); +
+The plan is to ignore move constructors by default in a future version of SWIG. Note that both normal assignment operators as well as move assignment operators are ignored by default in most target languages with the following warning: +
+ ++example.i:18: Warning 503: Can't wrap 'operator =' unless renamed to a valid identifier. ++
SWIG parses and identifies the keyword constexpr, but cannot fully utilise it. +These C++ compile time constants are usable as runtime constants from the target languages. +Below shows example usage for assigning a C++ compile time constant from a compile time constant function: +
+ ++constexpr int XXX() { return 10; } +constexpr int YYY = XXX() + 100; +
+When either of these is used from a target language, a runtime call is made to obtain the underlying constant. +
+ +SWIG correctly parses the keywords extern template. +However, this template instantiation suppression in a translation unit has no relevance outside of the C++ compiler and so is not used by SWIG. +SWIG only uses %template for instantiating and wrapping templates.
+ ++template class std::vector<int>; // C++03 explicit instantiation in C++ +extern template class std::vector<int>; // C++11 explicit instantiation suppression in C++ +%template(VectorInt) std::vector<int>; // SWIG instantiation +
+Initializer lists are very much a C++ compiler construct and are not very accessible from wrappers as +they are intended for compile time initialization of classes using the special std::initializer_list type. +SWIG detects usage of initializer lists and will emit a special informative warning each time one is used: +
+ ++example.i:33: Warning 476: Initialization using std::initializer_list. ++
+Initializer lists usually appear in constructors but can appear in any function or method. +They often appear in constructors which are overloaded with alternative approaches to initializing a class, +such as the std container's push_back method for adding elements to a container. +The recommended approach then is to simply ignore the initializer-list constructor, for example: +
+ ++%ignore Container::Container(std::initializer_list<int>); +class Container { +public: + Container(std::initializer_list<int>); // initializer-list constructor + Container(); + void push_back(const int &); + ... +}; +
Alternatively you could modify the class and add another constructor for initialization by some other means, +for example by a std::vector:
+ ++%include <std_vector.i> +class Container { +public: + Container(const std::vector<int> &); + Container(std::initializer_list<int>); // initializer-list constructor + Container(); + void push_back(const int &); + ... +}; +
And then call this constructor from your target language, for example, in Python, the following will call the constructor taking the std::vector:
+ ++>>> c = Container( [1,2,3,4] ) +
+If you are unable to modify the class being wrapped, consider ignoring the initializer-list constructor and using +%extend to add in an alternative constructor: +
+ ++%include <std_vector.i> +%extend Container { + Container(const std::vector<int> &elements) { + Container *c = new Container(); + for (int element : elements) + c->push_back(element); + return c; + } +} + +%ignore Container::Container(std::initializer_list<int>); + +class Container { +public: + Container(std::initializer_list<int>); // initializer-list constructor + Container(); + void push_back(const int &); + ... +}; +
+The above makes the wrappers look is as if the class had been declared as follows: +
+ ++%include <std_vector.i> +class Container { +public: + Container(const std::vector<int> &); +// Container(std::initializer_list<int>); // initializer-list constructor (ignored) + Container(); + void push_back(const int &); + ... +}; +
+std::initializer_list is simply a container that can only be initialized at compile time. +As it is just a C++ type, it is possible to write typemaps for a target language container to map onto +std::initializer_list. However, this can only be done for a fixed number of elements as +initializer lists are not designed to be constructed with a variable number of arguments at runtime. +The example below is a very simple approach which ignores any parameters passed in and merely initializes +with a fixed list of fixed integer values chosen at compile time: +
+ ++%typemap(in) std::initializer_list<int> { + $1 = {10, 20, 30, 40, 50}; +} +class Container { +public: + Container(std::initializer_list<int>); // initializer-list constructor + Container(); + void push_back(const int &); + ... +}; +
+Any attempt at passing in values from the target language will be ignored and be replaced by {10, 20, 30, 40, 50}. +Needless to say, this approach is very limited, but could be improved upon, but only slightly. +A typemap could be written to map a fixed number of elements on to the std::initializer_list, +but with values decided at runtime. +The typemaps would be target language specific. +
+ ++Note that the default typemap for std::initializer_list does nothing but issue the warning +and hence any user supplied typemaps will override it and suppress the warning. +
+ +The curly brackets {} for member initialization are fully +supported by SWIG:
+ ++struct BasicStruct { + int x; + double y; +}; + +struct AltStruct { + AltStruct(int x, double y) : x_{x}, y_{y} {} + + int x_; + double y_; +}; + +BasicStruct var1{5, 3.2}; // only fills the struct components +AltStruct var2{2, 4.3}; // calls the constructor +
Uniform initialization does not affect usage from the target language, for example in Python:
+ ++>>> a = AltStruct(10, 142.15) +>>> a.x_ +10 +>>> a.y_ +142.15 +
SWIG supports decltype() with some limitations. Single +variables are allowed, however, expressions are not supported yet. For +example, the following code will work:
++int i; +decltype(i) j; +
However, using an expression inside the decltype results in syntax error:
++int i; int j; +decltype(i+j) k; // syntax error +
This feature is part of the implementation block only. SWIG +ignores it.
+ +SWIG correctly parses most of the Lambda functions syntax. For example:
++auto val = [] { return something; }; +auto sum = [](int x, int y) { return x+y; }; +auto sum = [](int x, int y) -> int { return x+y; }; +
The lambda functions are removed from the wrappers for now, because of the lack of support +for closures (scope of the lambda functions) in the target languages.
+ ++Lambda functions used to create variables can also be parsed, but due to limited support of auto when +the type is deduced from the expression, the variables are simply ignored. +
+ ++auto six = [](int x, int y) { return x+y; }(4, 2); +
+Better support should be available in a later release. +
+ +SWIG fully supports the new definition of functions. For example:
++struct SomeStruct { + int FuncName(int x, int y); +}; +
can now be written as in C++11:
+ ++struct SomeStruct { + auto FuncName(int x, int y) -> int; +}; + +auto SomeStruct::FuncName(int x, int y) -> int { + return x + y; +} +
The usage in the target languages remains the same, for example in Python:
+ ++>>> a = SomeStruct() +>>> a.FuncName(10,5) +15 +
SWIG will also deal with type inference for the return type, as per the limitations described earlier. For example:
++auto square(float a, float b) -> decltype(a); +
+There are three parts to object construction improvement. +The first improvement is constructor delegation such as the following: +
+ ++class A { +public: + int a; + int b; + int c; + + A() : A(10) {} + A(int aa) : A(aa, 20) {} + A(int aa, int bb) : A(aa, bb, 30) {} + A(int aa, int bb, int cc) { a=aa; b=bb; c=cc; } +}; +
+where peer constructors can be called. SWIG handles this without any issue. +
+ ++The second improvement is constructor inheritance via a using declaration. +This is parsed correctly, but the additional constructors are not currently added to the derived proxy class in the target language. +An example is shown below: + +
+ ++class BaseClass { +public: + BaseClass(int iValue); +}; + +class DerivedClass: public BaseClass { + public: + using BaseClass::BaseClass; // Adds DerivedClass(int) constructor +}; +
+The final part is member initialization at the site of the declaration. +This kind of initialization is handled by SWIG. +
+ ++class SomeClass { +public: + SomeClass() {} + explicit SomeClass(int new_value) : value(new_value) {} + + int value = 5; +}; +
+The special identifiers final and override can be used on methods and destructors, +such as in the following example: +
+ ++struct BaseStruct { + virtual void ab() const = 0; + virtual void cd(); + virtual void ef(); + virtual ~BaseStruct(); +}; +struct DerivedStruct : BaseStruct { + virtual void ab() const override; + virtual void cd() final; + virtual void ef() final override; + virtual ~DerivedStruct() override; +}; +
The nullptr constant is mostly unimportant in wrappers. In the few places it has an effect, it is treated like NULL.
+ +SWIG supports strongly typed enumerations and parses the new enum class syntax and forward declarator for the enums, such as:
++enum class MyEnum : unsigned int; +
+Strongly typed enums are often used to avoid name clashes such as the following: +
+ ++struct Color { + enum class RainbowColors : unsigned int { + Red, Orange, Yellow, Green, Blue, Indigo, Violet + }; + + enum class WarmColors { + Yellow, Orange, Red + }; + + // Note normal enum + enum PrimeColors { + Red=100, Green, Blue + }; +}; +
+There are various ways that the target languages handle enums, so it is not possible to precisely state how they are handled in this section. +However, generally, most scripting languages mangle in the strongly typed enumeration's class name, +but do not use any additional mangling for normal enumerations. For example, in Python, the following code +
+ ++print Color.RainbowColors_Red, Color.WarmColors_Red, Color.Red +
+results in +
+ ++0 2 100 +
+The strongly typed languages often wrap normal enums into an enum class and so treat normal enums and strongly typed enums the same. +The equivalent in Java is: +
+ ++System.out.println(Color.RainbowColors.Red.swigValue() + " " + Color.WarmColors.Red.swigValue() + " " + Color.PrimeColors.Red.swigValue()); +
SWIG correctly parses the symbols >> as closing the +template block, if found inside it at the top level, or as the right +shift operator >> otherwise.
+ ++std::vector<std::vector<int>> myIntTable; +
SWIG correctly parses the keyword explicit for operators in addition to constructors now. +For example:
+ ++class U { +public: + int u; +}; + +class V { +public: + int v; +}; + +class TestClass { +public: + //implicit converting constructor + TestClass(U const &val) { t=val.u; } + + // explicit constructor + explicit TestClass(V const &val) { t=val.v; } + + int t; +}; + +struct Testable { + // explicit conversion operator + explicit operator bool() const { + return false; + } +}; +
+The effect of explicit constructors and operators has little relevance for the proxy classes as target +languages don't have the same concepts of implicit conversions as C++. +Conversion operators either with or without explicit need renaming to a valid identifier name in order to make +them available as a normal proxy method. +
+ ++The following is an example of an alias template: + +
+template< typename T1, typename T2, int > +class SomeType { +public: + T1 a; + T2 b; + int c; +}; + +template< typename T2 > +using TypedefName = SomeType<char*, T2, 5>; +
+These are partially supported as SWIG will parse these and identify them, however, they are ignored as they are not added to the type system. A warning such as the following is issued: +
+ ++example.i:13: Warning 342: The 'using' keyword in template aliasing is not fully supported yet. ++
+Similarly for non-template type aliasing: +
+ ++using PFD = void (*)(double); // New introduced syntax +
+A warning will be issued: +
+ ++example.i:17: Warning 341: The 'using' keyword in type aliasing is not fully supported yet. ++
The equivalent old style typedefs can be used as a workaround:
+ ++typedef void (*PFD)(double); // The old style +
SWIG fully supports any type inside a union even if it does not +define a trivial constructor. For example, the wrapper for the following +code correctly provides access to all members in the union:
+ ++struct point { + point() {} + point(int x, int y) : x_(x), y_(y) {} + int x_, y_; +}; + +#include <new> // For placement 'new' in the constructor below +union P { + int z; + double w; + point p; // Illegal in C++03; legal in C++11. + // Due to the point member, a constructor definition is required. + P() { + new(&p) point(); + } +} p1; +
SWIG supports the variadic templates syntax (inside the <> +block, variadic class inheritance and variadic constructor and +initializers) with some limitations. The following code is correctly parsed:
+ ++template <typename... BaseClasses> class ClassName : public BaseClasses... { +public: + ClassName (BaseClasses &&... baseClasses) : BaseClasses(baseClasses)... {} +} +
+For now however, the %template directive only accepts one parameter substitution +for the variable template parameters. +
+ ++%template(MyVariant1) ClassName<> // zero argument not supported yet +%template(MyVariant2) ClassName<int> // ok +%template(MyVariant3) ClassName<int, int> // too many arguments not supported yet +
Support for the variadic sizeof() function is correctly parsed:
+ ++const int SIZE = sizeof...(ClassName<int, int>); +
+In the above example SIZE is of course wrapped as a constant. +
+ +SWIG supports wide string and Unicode string constants and raw string literals.
+ ++// New string literals +wstring aa = L"Wide string"; +const char *bb = u8"UTF-8 string"; +const char16_t *cc = u"UTF-16 string"; +const char32_t *dd = U"UTF-32 string"; + +// Raw string literals +const char *xx = ")I'm an \"ascii\" \\ string."; +const char *ee = R"XXX()I'm an "ascii" \ string.)XXX"; // same as xx +wstring ff = LR"XXX(I'm a "raw wide" \ string.)XXX"; +const char *gg = u8R"XXX(I'm a "raw UTF-8" \ string.)XXX"; +const char16_t *hh = uR"XXX(I'm a "raw UTF-16" \ string.)XXX"; +const char32_t *ii = UR"XXX(I'm a "raw UTF-32" \ string.)XXX"; +
+Non-ASCII string support varies quite a bit among the various target languages though. +
+ ++Note: There is a bug currently where SWIG's preprocessor incorrectly parses an odd number of double quotes +inside raw string literals. +
+ ++SWIG parses the declaration of user-defined literals, that is, the operator "" _mysuffix() function syntax. +
+ ++Some examples are the raw literal: +
++OutputType operator "" _myRawLiteral(const char * value); +
+numeric cooked literals: +
++OutputType operator "" _mySuffixIntegral(unsigned long long); +OutputType operator "" _mySuffixFloat(long double); +
+and cooked string literals: +
++OutputType operator "" _mySuffix(const char * string_values, size_t num_chars); +OutputType operator "" _mySuffix(const wchar_t * string_values, size_t num_chars); +OutputType operator "" _mySuffix(const char16_t * string_values, size_t num_chars); +OutputType operator "" _mySuffix(const char32_t * string_values, size_t num_chars); +
+Like other operators that SWIG parses, a warning is given about renaming the operator in order for it to be wrapped: +
+ ++example.i:27: Warning 503: Can't wrap 'operator "" _myRawLiteral' unless renamed to a valid identifier. +
+If %rename is used, then it can be called like any other wrapped method. +Currently you need to specify the full declaration including parameters for %rename: +
+ ++%rename(MyRawLiteral) operator"" _myRawLiteral(const char * value); +
+Or if you just wish to ignore it altogether: +
+ ++%ignore operator "" _myRawLiteral(const char * value); +
+Note that use of user-defined literals such as the following still give a syntax error: +
+ ++OutputType var1 = "1234"_suffix; +OutputType var2 = 1234_suffix; +OutputType var3 = 3.1416_suffix; +
SWIG correctly parses the thread_local keyword. For example, variables +reachable by the current thread can be defined as:
+ ++struct A { + static thread_local int val; +}; +thread_local int global_val; +
+The use of the thread_local storage specifier does not affect the wrapping process; it does not modify +the wrapper code compared to when it is not specified. +A variable will be thread local if accessed from different threads from the target language in the +same way that it will be thread local if accessed from C++ code. +
+ +SWIG handles explicitly defaulted functions, that is, = default added to a function declaration. Deleted definitions, which are also called deleted functions, have = delete added to the function declaration. +For example:
+ ++struct NonCopyable { + NonCopyable & operator=(const NonCopyable &) = delete; /* Removes operator= */ + NonCopyable(const NonCopyable &) = delete; /* Removes copy constructor */ + NonCopyable() = default; /* Explicitly allows the empty constructor */ +}; +
+Wrappers for deleted functions will not be available in the target language. +Wrappers for defaulted functions will of course be available in the target language. +Explicitly defaulted functions have no direct effect for SWIG wrapping as the declaration is handled +much like any other method declaration parsed by SWIG. +
+ ++Deleted functions are also designed to prevent implicit conversions when calling the function. +For example, the C++ compiler will not compile any code which attempts to use an int as the type of the parameter passed to f below: +
+ ++struct NoInt { + void f(double i); + void f(int) = delete; +}; +
+This is a C++ compile time check and SWIG does not make any attempt to detect if the target language is using an int instead of a double though, +so in this case it is entirely possible to pass an int instead of a double to f from Java, Python etc. +
+ +SWIG correctly parses and uses the new long long type already introduced in C99 some time ago.
+ ++SWIG correctly parses the new static_assert declarations. +This is a C++ compile time directive so there isn't anything useful that SWIG can do with it. +
+ ++template <typename T> +struct Check { + static_assert(sizeof(int) <= sizeof(T), "not big enough"); +}; +
+SWIG can parse the new sizeof() on types as well as on objects. For example: +
+ ++struct A { + int member; +}; + +const int SIZE = sizeof(A::member); // does not work with C++03. Okay with C++11 +
In Python:
++>>> SIZE +8 +
+C++11 added in the noexcept specification to exception specifications to indicate that a function simply may or may not throw an exception, without actually naming any exception. +SWIG understands these, although there isn't any useful way that this information can be taken advantage of by target languages, +so it is as good as ignored during the wrapping process. +Below are some examples of noexcept in function declarations: +
+ ++static void noex1() noexcept; +int noex2(int) noexcept(true); +int noex3(int, bool) noexcept(false); +
+An alignof operator is used mostly within C++ to return alignment in number of bytes, but could be used to initialize a variable as shown below. +The variable's value will be available for access by the target language as any other variable's compile time initialised value. + +
+const int align1 = alignof(A::member); +
+The alignas specifier for variable alignment is not yet supported. +Example usage: +
+ ++struct alignas(16) S { + int num; +}; +alignas(double) unsigned char c[sizeof(double)]; +
+Use the preprocessor to work around this for now: +
+ ++#define alignas(T) +
+Attributes such as those shown below, are not yet supported and will give a syntax error. +
+ ++int [[attr1]] i [[attr2, attr3]]; + +[[noreturn, nothrow]] void f [[noreturn]] (); +
SWIG does not currently wrap or use any of the new threading +classes introduced (thread, mutex, locks, condition variables, task). The main reason is that +SWIG target languages offer their own threading facilities so there is limited use for them. +
+ ++SWIG does not provide library files for the new tuple types yet. +Variadic template support requires further work to provide substantial tuple wrappers. +
+ ++The new hash tables in the STL are unordered_set, unordered_multiset, unordered_map, unordered_multimap. +These are not available in SWIG, but in principle should be easily implemented by adapting the current STL containers. +
+ ++While SWIG could provide wrappers for the new C++11 regular expressions classes, there is little need as the target languages have their own regular expression facilities. +
+ ++SWIG provides special smart pointer handling for std::shared_ptr in the same way it has support for boost::shared_ptr. +Please see the shared_ptr smart pointer library section. +There is no special smart pointer handling available for std::weak_ptr and std::unique_ptr yet. +
+ +This feature extends and standardizes the standard library only and does not effect the C++ language nor SWIG.
+ ++Wrapper references are similar to normal C++ references but are copy-constructible and copy-assignable. +They could conceivably be used in public APIs. +There is no special support for std::reference_wrapper in SWIG though. +Users would need to write their own typemaps if wrapper references are being used and these would be similar to the plain C++ reference typemaps. +
+ + ++SWIG supports functor classes in a few languages in a very natural way. +However nothing is provided yet for the new std::function template. +SWIG will parse usage of the template like any other template. +
+ ++%rename(__call__) Test::operator(); // Default renaming used for Python + +struct Test { + bool operator()(int x, int y); // function object +}; + +#include <functional> +std::function<void (int, int)> pF = Test; // function template wrapper + +
+Example of supported usage of the plain functor from Python is shown below. +It does not involve std::function. +
+ ++t = Test() +b = t(1,2) # invoke C++ function object +
The type_traits functions to support C++ metaprogramming is useful at compile time and is aimed specifically at C++ development:
+ ++#include <type_traits> + +// First way of operating. +template< bool B > struct algorithm { + template< class T1, class T2 > static int do_it(T1 &, T2 &) { /*...*/ return 1; } +}; + +// Second way of operating. +template<> struct algorithm<true> { + template< class T1, class T2 > static int do_it(T1, T2) { /*...*/ return 2; } +}; + +// Instantiating 'elaborate' will automatically instantiate the correct way to operate, depending on the types used. +template< class T1, class T2 > int elaborate(T1 A, T2 B) { + // Use the second way only if 'T1' is an integer and if 'T2' is a floating point, + // otherwise use the first way. + return algorithm< std::is_integral<T1>::value && std::is_floating_point<T2>::value >::do_it(A, B); +} +
+SWIG correctly parses the template specialization, template types etc. +However, metaprogramming and the additional support in the type_traits header is really for compile time and is not much use at runtime for the target languages. +For example, as SWIG requires explicit instantiation of templates via %template, there isn't much that std::is_integral<int> is going to provide by itself. +However, template functions using such metaprogramming techniques might be useful to wrap. +For example, the following instantiations could be made: +
+ ++%template(Elaborate) elaborate<int, int>; +%template(Elaborate) elaborate<int, double>; +
+Then the appropriate algorithm can be called for the subset of types given by the above %template instantiations from a target language, such as Python: +
+ ++>>> Elaborate(0, 0) +1 +>>> Elaborate(0, 0.0) +2 +
+The new std::result_of class introduced in the <functional> header provides a generic way to obtain the return type of a function type via std::result_of::type. +There isn't any library interface file to support this type. +With a bit of work, SWIG will deduce the return type of functions when used in std::result_of using the approach shown below. +The technique basically forward declares the std::result_of template class, then partially specializes it for the function types of interest. +SWIG will use the partial specialization and hence correctly use the std::result_of::type provided in the partial specialization. +
+ ++%inline %{ +#include <functional> +typedef double(*fn_ptr)(double); +%} + +namespace std { + // Forward declaration of result_of + template<typename Func> struct result_of; + // Add in a partial specialization of result_of + template<> struct result_of< fn_ptr(double) > { + typedef double type; + }; +} + +%template() std::result_of< fn_ptr(double) >; + +%inline %{ + +double square(double x) { + return (x * x); +} + +template<class Fun, class Arg> +typename std::result_of<Fun(Arg)>::type test_result_impl(Fun fun, Arg arg) { + return fun(arg); +} +%} + +%template(test_result) test_result_impl< fn_ptr, double >; +%constant double (*SQUARE)(double) = square; +
+Note the first use of %template which SWIG requires to instantiate the template. +The empty template instantiation suffices as no proxy class is required for std::result_of<Fun(Arg)>::type as this type is really just a double. +The second %template instantiates the template function which is being wrapped for use as a callback. +The %constant can then be used for any callback function as described in Pointers to functions and callbacks. +
+ ++Example usage from Python should give the not too surprising result: +
+ ++>>> test_result(SQUARE, 5.0) +25.0 +
+Phew, that is a lot of hard work to get a callback working. +You could just go with the more attractive option of just using double as the return type in the function declaration instead of result_of! +
+ + + diff --git a/Doc/Manual/CSharp.html b/Doc/Manual/CSharp.html index 6df2594..26f0c74 100644 --- a/Doc/Manual/CSharp.html +++ b/Doc/Manual/CSharp.html @@ -1,15 +1,20 @@ - +@@ -66,10 +71,70 @@ SWIG C# works equally well on non-Microsoft operating systems such as Linux, Sol
To get the most out of this chapter an understanding of interop is required. The Microsoft Developer Network (MSDN) has a good reference guide in a section titled "Interop Marshaling". -Monodoc, available from the Mono project, has a very useful section titled Interop with native libraries. +Monodoc, available from the Mono project, has a very useful section titled Interop with native libraries. +
+ ++In order to minimize name collisions between names generated based on input to SWIG and names used in the generated code from the .NET framework, SWIG 3 fully qualifies the use of all .NET types. Furthermore, SWIG 3 avoids using directives in generated code. This breaks backwards compatibility with typemaps, pragmas, etc written for use with SWIG 2 that assume the presence of using System; or using System.Runtime.InteropServices; directives in the intermediate class imports, module imports, or proxy imports. SWIG 3 supports backwards compatibility though the use of the SWIG2_CSHARP macro. If SWIG2_CSHARP is defined, SWIG 3 generates using directives in the intermediate class, module class, and proxy class code similar to those generated by SWIG 2. This can be done without modifying any of the input code by passing the -DSWIG2_CSHARP commandline parameter when executing swig. +
+ + ++The following table lists the additional commandline options available for the C# module. They can also be seen by using: +
+ ++swig -csharp -help +
C# specific options | +|
---|---|
-dllimport <dl> | +Override DllImport attribute name to <dl> | +
-namespace <nm> | +Generate wrappers into C# namespace <nm> | +
-noproxy | +Generate the low-level functional interface instead of proxy classes | +
-oldvarnames | +Old intermediary method names for variable wrappers | +
-outfile <file> | +Write all C# into a single <file> located in the output directory + | +
+The -outfile option combines all the generated C# code into a single output file instead of creating multiple C# files. +The default, when this option is not provided, is to generate separate .cs files for the module class, +intermediary class and each of the generated proxy and type wrapper classes. +Note that the file extension (.cs) will not be automatically added and needs to be provided. +Due to possible compiler limits it is not advisable to use -outfile for large projects.
-@@ -168,6 +233,7 @@ javabody -> csbody javafinalize -> csfinalize javadestruct -> csdestruct javadestruct_derived -> csdestruct_derived +javainterfacecode -> csinterfacecode
-%typemap(imtype, out="IntPtr") char * "string" +%typemap(imtype, out="global::System.IntPtr") char * "string" char * function(char *);
-public static extern IntPtr function(string jarg1); +public static extern global::System.IntPtr function(string jarg1);
%typemap(imtype, - inattributes="[MarshalAs(UnmanagedType.LPStr)]", - outattributes="[return: MarshalAs(UnmanagedType.LPStr)]") const char * "String" + inattributes="[global::System.Runtime.InteropServices.MarshalAs(UnmanagedType.LPStr)]", + outattributes="[return: global::System.Runtime.InteropServices.MarshalAs(UnmanagedType.LPStr)]") const char * "String" const char * GetMsg() {} void SetMsg(const char *msg) {} @@ -310,12 +379,12 @@ The intermediary class will then have the marshalling as specified by everythingclass examplePINVOKE { ... - [DllImport("example", EntryPoint="CSharp_GetMsg")] - [return: MarshalAs(UnmanagedType.LPStr)] + [global::System.Runtime.InteropServices.DllImport("example", EntryPoint="CSharp_GetMsg")] + [return: global::System.Runtime.InteropServices.MarshalAs(UnmanagedType.LPStr)] public static extern String GetMsg(); - [DllImport("example", EntryPoint="CSharp_SetMsg")] - public static extern void SetMsg([MarshalAs(UnmanagedType.LPStr)]String jarg1); + [global::System.Runtime.InteropServices.DllImport("example", EntryPoint="CSharp_SetMsg")] + public static extern void SetMsg([global::System.Runtime.InteropServices.MarshalAs(UnmanagedType.LPStr)]String jarg1); }
[ThreadSafe] -public class AClass : IDisposable { +public class AClass : global::System.IDisposable { ... [ThreadSafe(false)] public AClass(double a) ... @@ -392,9 +461,9 @@ An example for attaching attributes to the enum and enum values is shown below.--%typemap(csattributes) Couleur "[System.ComponentModel.Description(\"Colours\")]" -%csattributes Rouge "[System.ComponentModel.Description(\"Red\")]" -%csattributes Vert "[System.ComponentModel.Description(\"Green\")]" +%typemap(csattributes) Couleur "[global::System.ComponentModel.Description(\"Colours\")]" +%csattributes Rouge "[global::System.ComponentModel.Description(\"Red\")]" +%csattributes Vert "[global::System.ComponentModel.Description(\"Green\")]" %inline %{ enum Couleur { Rouge, Orange, Vert }; %} @@ -407,12 +476,12 @@ which will result in the following C# enum:--[System.ComponentModel.Description("Colours")] +[global::System.ComponentModel.Description("Colours")] public enum Couleur { - [System.ComponentModel.Description("Red")] + [global::System.ComponentModel.Description("Red")] Rouge, Orange, - [System.ComponentModel.Description("Green")] + [global::System.ComponentModel.Description("Green")] Vert }@@ -482,7 +551,7 @@ Windows users can also get the examples working using a Cygwin or MinGW environment for automatic configuration of the example makefiles. Any one of the three C# compilers (Portable.NET, Mono or Microsoft) can be detected from within a Cygwin or Mingw environment if installed in your path. -19.3 Void pointers
+20.3 Void pointers
@@ -500,7 +569,7 @@ void * f(void *v);
19.4 C# Arrays
+20.4 C# Arrays
@@ -512,7 +581,7 @@ with one of the following three approaches; namely the SWIG C arrays library, P/ pinned arrays.
-19.4.1 The SWIG C arrays library
+20.4.1 The SWIG C arrays library
@@ -549,7 +618,7 @@ example.print_array(c.cast()); // Pass to C
19.4.2 Managed arrays using P/Invoke default array marshalling
+20.4.2 Managed arrays using P/Invoke default array marshalling
@@ -618,9 +687,9 @@ marshalling for the arrays:
@@ -668,15 +737,15 @@ and intermediary class method-[DllImport("example", EntryPoint="CSharp_myArrayCopy")] -public static extern void myArrayCopy([In, MarshalAs(UnmanagedType.LPArray)]int[] jarg1, - [Out, MarshalAs(UnmanagedType.LPArray)]int[] jarg2, +[global::System.Runtime.InteropServices.DllImport("example", EntryPoint="CSharp_myArrayCopy")] +public static extern void myArrayCopy([global::System.Runtime.InteropServices.In, global::System.Runtime.InteropServices.MarshalAs(UnmanagedType.LPArray)]int[] jarg1, + [global::System.Runtime.InteropServices.Out, global::System.Runtime.InteropServices.MarshalAs(UnmanagedType.LPArray)]int[] jarg2, int jarg3);-- [DllImport("example", EntryPoint="CSharp_myArraySwap")] - public static extern void myArraySwap([In, Out, MarshalAs(UnmanagedType.LPArray)]int[] jarg1, - [In, Out, MarshalAs(UnmanagedType.LPArray)]int[] jarg2, + [global::System.Runtime.InteropServices.DllImport("example", EntryPoint="CSharp_myArraySwap")] + public static extern void myArraySwap([global::System.Runtime.InteropServices.In, global::System.Runtime.InteropServices.Out, global::System.Runtime.InteropServices.MarshalAs(UnmanagedType.LPArray)]int[] jarg1, + [global::System.Runtime.InteropServices.In, global::System.Runtime.InteropServices.Out, global::System.Runtime.InteropServices.MarshalAs(UnmanagedType.LPArray)]int[] jarg2, int jarg3);19.4.3 Managed arrays using pinning
+20.4.3 Managed arrays using pinning
@@ -743,7 +812,7 @@ As a result, we get the following method in the module class: fixed ( int *swig_ptrTo_sourceArray = sourceArray ) { fixed ( int *swig_ptrTo_targetArray = targetArray ) { { - examplePINVOKE.myArrayCopy((IntPtr)swig_ptrTo_sourceArray, (IntPtr)swig_ptrTo_targetArray, + examplePINVOKE.myArrayCopy((global::System.IntPtr)swig_ptrTo_sourceArray, (global::System.IntPtr)swig_ptrTo_targetArray, nitems); } } @@ -764,14 +833,14 @@ example - the method is expecting an IntPtr as the parameter type.
--[DllImport("example", EntryPoint="CSharp_myArrayCopy")] -public static extern void myArrayCopy(IntPtr jarg1, IntPtr jarg2, int jarg3); +[global::System.Runtime.InteropServices.DllImport("example", EntryPoint="CSharp_myArrayCopy")] +public static extern void myArrayCopy(global::System.IntPtr jarg1, global::System.IntPtr jarg2, int jarg3);19.5 C# Exceptions
+20.5 C# Exceptions
@@ -868,11 +937,11 @@ set so should only be used when a C# exception is not created.
-19.5.1 C# exception example using "check" typemap
+20.5.1 C# exception example using "check" typemap
-Lets say we have the following simple C++ method: +Let's say we have the following simple C++ method:
@@ -1050,7 +1119,7 @@ method and C# code does not handle pending exceptions via the canthrow attribute Actually it will issue this warning for any function beginning with SWIG_CSharpSetPendingException. -19.5.2 C# exception example using %exception
+20.5.2 C# exception example using %exception
@@ -1065,6 +1134,7 @@ try { $action } catch (std::out_of_range e) { SWIG_CSharpSetPendingException(SWIG_CSharpApplicationException, e.what()); + return $null; } %} @@ -1115,7 +1185,7 @@ The managed code generated does check for the pending exception as mentioned ear
@@ -1172,7 +1242,7 @@ SWIGEXPORT void SWIGSTDCALL CSharp_evensonly(int jarg1) { Multiple catch handlers are generated should there be more than one exception specifications declared.
-
@@ -1220,7 +1290,7 @@ the C# code can be generated into the intermediary class using the imclassco
static CustomExceptionDelegate customDelegate =
new CustomExceptionDelegate(SetPendingCustomException);
- [DllImport("$dllimport", EntryPoint="CustomExceptionRegisterCallback")]
+ [global::System.Runtime.InteropServices.DllImport("$dllimport", EntryPoint="CustomExceptionRegisterCallback")]
public static extern
void CustomExceptionRegisterCallback(CustomExceptionDelegate customCallback);
@@ -1264,7 +1334,7 @@ The boiler plate code above must be used in addition to a handcrafted Custom
// Custom C# Exception
-class CustomApplicationException : System.ApplicationException {
+class CustomApplicationException : global::System.ApplicationException {
public CustomApplicationException(string message)
: base(message) {
}
@@ -1306,7 +1376,7 @@ try {
19.6 C# Directors
+20.6 C# Directors
@@ -1319,7 +1389,7 @@ The following sections provide information on the C# director implementation and However, the Java directors section should also be read in order to gain more insight into directors.
-@@ -1440,7 +1510,7 @@ CSharpDerived - UIntMethod(123) -
@@ -1457,20 +1527,17 @@ Below is the generated C# Base director class.
-using System; -using System.Runtime.InteropServices; - -public class Base : IDisposable { - private HandleRef swigCPtr; +public class Base : global::System.IDisposable { + private global::System.Runtime.InteropServices.HandleRef swigCPtr; protected bool swigCMemOwn; - internal Base(IntPtr cPtr, bool cMemoryOwn) { + internal Base(global::System.IntPtr cPtr, bool cMemoryOwn) { swigCMemOwn = cMemoryOwn; - swigCPtr = new HandleRef(this, cPtr); + swigCPtr = new global::System.Runtime.InteropServices.HandleRef(this, cPtr); } - internal static HandleRef getCPtr(Base obj) { - return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr; + internal static global::System.Runtime.InteropServices.HandleRef getCPtr(Base obj) { + return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr; } ~Base() { @@ -1479,12 +1546,12 @@ public class Base : IDisposable { public virtual void Dispose() { lock(this) { - if(swigCPtr.Handle != IntPtr.Zero && swigCMemOwn) { + if(swigCPtr.Handle != global::System.IntPtr.Zero && swigCMemOwn) { swigCMemOwn = false; examplePINVOKE.delete_Base(swigCPtr); } - swigCPtr = new HandleRef(null, IntPtr.Zero); - GC.SuppressFinalize(this); + swigCPtr = new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero); + global::System.GC.SuppressFinalize(this); } } @@ -1511,7 +1578,7 @@ public class Base : IDisposable { examplePINVOKE.Base_director_connect(swigCPtr, swigDelegate0, swigDelegate1); } - private bool SwigDerivedClassHasMethod(string methodName, Type[] methodTypes) { + private bool SwigDerivedClassHasMethod(string methodName, global::System.global::System.Type[] methodTypes) { System.Reflection.MethodInfo methodInfo = this.GetType().GetMethod(methodName, methodTypes); bool hasDerivedMethod = methodInfo.DeclaringType.IsSubclassOf(typeof(Base)); return hasDerivedMethod; @@ -1521,18 +1588,18 @@ public class Base : IDisposable { return UIntMethod(x); } - private void SwigDirectorBaseBoolMethod(IntPtr b, bool flag) { + private void SwigDirectorBaseBoolMethod(global::System.IntPtr b, bool flag) { BaseBoolMethod(new Base(b, false), flag); } internal delegate uint SwigDelegateBase_0(uint x); - internal delegate void SwigDelegateBase_1(IntPtr b, bool flag); + internal delegate void SwigDelegateBase_1(global::System.IntPtr b, bool flag); private SwigDelegateBase_0 swigDelegate0; private SwigDelegateBase_1 swigDelegate1; - private static Type[] swigMethodTypes0 = new Type[] { typeof(uint) }; - private static Type[] swigMethodTypes1 = new Type[] { typeof(Base), typeof(bool) }; + private static global::System.Type[] swigMethodTypes0 = new global::System.Type[] { typeof(uint) }; + private static global::System.Type[] swigMethodTypes1 = new global::System.Type[] { typeof(Base), typeof(bool) }; }
@@ -1674,11 +1741,11 @@ However, a call from C# to CSharpDefaults.DefaultMethod() will of cours should pass the call on to CSharpDefaults.DefaultMethod(int)using the C++ default value, as shown above.
--When using multiple modules it is is possible to compile each SWIG generated wrapper +When using multiple modules it is is possible to compile each SWIG generated wrapper into a different assembly. However, by default the generated code may not compile if generated classes in one assembly use generated classes in another assembly. @@ -1709,7 +1776,7 @@ the [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrows if you don't want users to easily stumble upon these so called 'internal workings' of the wrappers.
-@@ -1755,9 +1822,9 @@ and the following usage from C# after running the code through SWIG: Wheel wheel = new Bike(10).getWheel(); Console.WriteLine("wheel size: " + wheel.size); // Simulate a garbage collection - System.GC.Collect(); - System.GC.WaitForPendingFinalizers(); - Console.WriteLine("wheel size: " + wheel.size); + global::System.GC.Collect(); + global::System.GC.WaitForPendingFinalizers(); + global::System.Console.WriteLine("wheel size: " + wheel.size); @@ -1795,9 +1862,9 @@ is called using the following typemaps. // of dangling C++ pointer. Intended for methods that return pointers or // references to a member variable. %typemap(csout, excode=SWIGEXCODE) Wheel& getWheel { - IntPtr cPtr = $imcall;$excode + global::System.IntPtr cPtr = $imcall;$excode $csclassname ret = null; - if (cPtr != IntPtr.Zero) { + if (cPtr != global::System.IntPtr.Zero) { ret = new $csclassname(cPtr, $owner); ret.addReference(this); } @@ -1813,7 +1880,7 @@ The code in the second typemap constitutes the bulk of the code in the generated
-public class Wheel : IDisposable { +public class Wheel : global::System.IDisposable { ... // Ensure that the GC doesn't collect any Bike instance set from C# private Bike bikeReference; @@ -1822,12 +1889,12 @@ public class Wheel : IDisposable { } } -public class Bike : IDisposable { +public class Bike : global::System.IDisposable { ... public Wheel getWheel() { - IntPtr cPtr = examplePINVOKE.Bike_getWheel(swigCPtr); + global::System.IntPtr cPtr = examplePINVOKE.Bike_getWheel(swigCPtr); Wheel ret = null; - if (cPtr != IntPtr.Zero) { + if (cPtr != global::System.IntPtr.Zero) { ret = new Wheel(cPtr, false); ret.addReference(this); } @@ -1841,7 +1908,7 @@ public class Bike : IDisposable { Note the addReference call. -19.8.2 Memory management for objects passed to the C++ layer
+20.8.2 Memory management for objects passed to the C++ layer
@@ -1904,9 +1971,9 @@ In order to understand why, consider a garbage collection occuring... container.setElement(element); Console.WriteLine("element.value: " + container.getElement().value); // Simulate a garbage collection - System.GC.Collect(); - System.GC.WaitForPendingFinalizers(); - Console.WriteLine("element.value: " + container.getElement().value); + global::System.GC.Collect(); + global::System.GC.WaitForPendingFinalizers(); + global::System.Console.WriteLine("element.value: " + container.getElement().value);
-public class Container : IDisposable { +public class Container : global::System.IDisposable { ... // Ensure that the GC doesn't collect any Element set from C# // as the underlying C++ class stores a shallow copy private Element elementReference; - private HandleRef getCPtrAndAddReference(Element element) { + private global::System.Runtime.InteropServices.HandleRef getCPtrAndAddReference(Element element) { elementReference = element; return Element.getCPtr(element); } @@ -1951,7 +2018,7 @@ The 'cscode' typemap simply adds in the specified code into the C# proxy class. // Ensure that the GC doesn't collect any Element set from C# // as the underlying C++ class stores a shallow copy private Element elementReference; - private HandleRef getCPtrAndAddReference(Element element) { + private global::System.Runtime.InteropServices.HandleRef getCPtrAndAddReference(Element element) { elementReference = element; return Element.getCPtr(element); } @@ -1960,7 +2027,7 @@ The 'cscode' typemap simply adds in the specified code into the C# proxy class.
@@ -2000,7 +2067,7 @@ First let's look at the code that is generated by default, where the C# proxy cl
-public class Action : IDisposable { +public class Action : global::System.IDisposable { ... public Action(CDate dateIn, CDate dateOut) : this(examplePINVOKE.new_Action(CDate.getCPtr(dateIn), CDate.getCPtr(dateOut)), true) { @@ -2081,7 +2148,7 @@ The resulting generated proxy code in the Action class follows:--public class Action : IDisposable { +public class Action : global::System.IDisposable { ... public int doSomething(System.DateTime dateIn, out System.DateTime dateOut) { CDate tempdateIn = new CDate(dateIn.Year, dateIn.Month, dateIn.Day); @@ -2099,7 +2166,7 @@ public class Action : IDisposable { } } - static private IntPtr SwigConstructAction(System.DateTime dateIn, out System.DateTime dateOut) { + static private global::System.IntPtr SwigConstructAction(System.DateTime dateIn, out System.DateTime dateOut) { CDate tempdateIn = new CDate(dateIn.Year, dateIn.Month, dateIn.Day); CDate tempdateOut = new CDate(); try { @@ -2246,7 +2313,7 @@ public class example {19.8.4 A date example demonstrating marshalling of C# properties
+20.8.4 A date example demonstrating marshalling of C# properties
@@ -2299,8 +2366,8 @@ The typemap type required is thus CDate *. Given that the previous sect %typemap(csvarout, excode=SWIGEXCODE2) CDate * %{ /* csvarout typemap code */ get { - IntPtr cPtr = $imcall; - CDate tempDate = (cPtr == IntPtr.Zero) ? null : new CDate(cPtr, $owner);$excode + global::System.IntPtr cPtr = $imcall; + CDate tempDate = (cPtr == global::System.IntPtr.Zero) ? null : new CDate(cPtr, $owner);$excode return new System.DateTime(tempDate.getYear(), tempDate.getMonth(), tempDate.getDay(), 0, 0, 0); } %} @@ -2322,8 +2389,8 @@ public class example { } /* csvarout typemap code */ get { - IntPtr cPtr = examplePINVOKE.ImportantDate_get(); - CDate tempDate = (cPtr == IntPtr.Zero) ? null : new CDate(cPtr, false); + global::System.IntPtr cPtr = examplePINVOKE.ImportantDate_get(); + CDate tempDate = (cPtr == global::System.IntPtr.Zero) ? null : new CDate(cPtr, false); return new System.DateTime(tempDate.getYear(), tempDate.getMonth(), tempDate.getDay(), 0, 0, 0); } @@ -2346,7 +2413,7 @@ Some points to note:
@@ -2389,7 +2456,7 @@ The generated proxy class code will then contain the following wrapper for calli
... - private void SwigDirectorsomeCallback(IntPtr date) { + private void SwigDirectorsomeCallback(global::System.IntPtr date) { System.DateTime tempdate = new System.DateTime(); try { someCallback(out tempdate); @@ -2408,7 +2475,7 @@ Pay special attention to the memory management issues, using these attributes. -19.8.6 Turning wrapped classes into partial classes
+20.8.6 Turning wrapped classes into partial classes
@@ -2432,7 +2499,7 @@ The default C# proxy class generated is:
--public class ExtendMe : IDisposable { +public class ExtendMe : global::System.IDisposable { ... public int Part1() { ... @@ -2468,7 +2535,7 @@ The C# proxy class becomes a partial class:--public partial class ExtendMe : IDisposable { +public partial class ExtendMe : global::System.IDisposable { ... public int Part1() { ... @@ -2483,7 +2550,7 @@ You can then of course declare another part of the partial class elsewhere, for--public partial class ExtendMe : IDisposable { +public partial class ExtendMe : global::System.IDisposable { public int Part2() { return 2; } @@ -2508,7 +2575,7 @@ demonstrating that the class contains methods calling both unmanaged code - The following example is an alternative approach to adding managed code to the generated proxy class. -19.8.7 Extending proxy classes with additional C# code
+20.8.7 Extending proxy classes with additional C# code
@@ -2535,7 +2602,7 @@ The generated C# proxy class will instead be:
--public class ExtendMe : IDisposable { +public class ExtendMe : global::System.IDisposable { ... public int Part3() { return 3; @@ -2547,7 +2614,7 @@ public class ExtendMe : IDisposable {19.8.8 Underlying type for enums
+20.8.8 Underlying type for enums
diff --git a/Doc/Manual/Chicken.html b/Doc/Manual/Chicken.html index 4e43b9b..820d01f 100644 --- a/Doc/Manual/Chicken.html +++ b/Doc/Manual/Chicken.html @@ -1,14 +1,14 @@ - - +
SWIG and Chicken + -20 SWIG and Chicken
+21 SWIG and Chicken
-@@ -55,10 +55,10 @@
-
- generates portable C code
-- includes a customizable interpreter
-- links to C libraries with a simple Foreign Function Interface
-- supports full tail-recursion and first-class continuations
+- generates portable C code
+- includes a customizable interpreter
+- links to C libraries with a simple Foreign Function Interface
+- supports full tail-recursion and first-class continuations
@@ -72,7 +72,7 @@
-20.1 Preliminaries
+21.1 Preliminaries
@@ -89,7 +89,7 @@ directory for the basic steps to run SWIG CHICKEN.
-20.1.1 Running SWIG in C mode
+21.1.1 Running SWIG in C mode
@@ -98,7 +98,7 @@
-% swig -chicken example.i+% swig -chicken example.i@@ -122,7 +122,7 @@ object files and linked into your project.
-20.1.2 Running SWIG in C++ mode
+21.1.2 Running SWIG in C++ mode
@@ -131,7 +131,7 @@
-% swig -chicken -c++ example.i+% swig -chicken -c++ example.i@@ -142,7 +142,7 @@
-% chicken example.scm -output-file oexample.c+% chicken example.scm -output-file oexample.c@@ -151,10 +151,10 @@ object files and linked into your project.
-20.2 Code Generation
+21.2 Code Generation
-20.2.1 Naming Conventions
+21.2.1 Naming Conventions
@@ -170,16 +170,16 @@ %rename SWIG directive in the SWIG interface file.
-20.2.2 Modules
+21.2.2 Modules
The name of the module must be declared one of two ways:
-
- Placing %module example in the SWIG interface - file.
-- Using -module example on the SWIG command - line.
+- Placing %module example in the SWIG interface + file.
+- Using -module example on the SWIG command + line.
@@ -189,10 +189,10 @@
CHICKEN will be able to access the module using the
-(declare - (uses modulename))
CHICKEN Scheme form. + (uses modulename)) CHICKEN Scheme form.20.2.3 Constants and Variables
+21.2.3 Constants and Variables
@@ -200,10 +200,10 @@ the interface file:
-
- -
#define MYCONSTANT1 ...
- -
%constant int MYCONSTANT2 = ...
- -
const int MYCONSTANT3 = ...
- +
enum { MYCONSTANT4 = ... };
- +
#define MYCONSTANT1 ...
- +
%constant int MYCONSTANT2 = ...
- +
const int MYCONSTANT3 = ...
enum { MYCONSTANT4 = ... };
@@ -229,7 +229,7 @@ for info on how to apply the %feature.
-20.2.4 Functions
+21.2.4 Functions
@@ -248,7 +248,7 @@ parameters). The return values can then be accessed with
-(call-with-values)
.20.2.5 Exceptions
+21.2.5 Exceptions
The SWIG chicken module has support for exceptions thrown from @@ -290,16 +290,16 @@
20.3 TinyCLOS
+21.3 TinyCLOS
The author of TinyCLOS, Gregor Kiczales, describes TinyCLOS as: - "Tiny CLOS is a Scheme implementation of a `kernelized' CLOS, with a - metaobject protocol. The implementation is even simpler than - the simple CLOS found in `The Art of the Metaobject Protocol,' - weighing in at around 850 lines of code, including (some) - comments and documentation." + "Tiny CLOS is a Scheme implementation of a `kernelized' CLOS, with a + metaobject protocol. The implementation is even simpler than + the simple CLOS found in `The Art of the Metaobject Protocol,' + weighing in at around 850 lines of code, including (some) + comments and documentation."
@@ -333,7 +333,7 @@
-20.4 Linkage
+21.4 Linkage
@@ -354,7 +354,7 @@
-20.4.1 Static binary or shared library linked at compile time
+21.4.1 Static binary or shared library linked at compile time
We can easily use csc to build a static binary.
@@ -395,7 +395,7 @@ in which case the test script does not need to be linked with example.so. The t be run with csi. -20.4.2 Building chicken extension libraries
+21.4.2 Building chicken extension libraries
Building a shared library like in the above section only works if the library @@ -453,7 +453,7 @@ distributed and used by anyone, even if SWIG is not installed.
See the Examples/chicken/egg directory in the SWIG source for an example that builds two eggs, one using the first method and one using the second method.
-20.4.3 Linking multiple SWIG modules with TinyCLOS
+21.4.3 Linking multiple SWIG modules with TinyCLOS
Linking together multiple modules that share type information using the
-%import
@@ -477,7 +477,7 @@ with(declare (uses ...))
. To create an extension library or an egg, just create a module_load.scm file that(declare (uses ...))
all the modules.20.5 Typemaps
+21.5 Typemaps
@@ -486,7 +486,7 @@ all the modules.
Lib/chicken/chicken.swg
. -20.6 Pointers
+21.6 Pointers
@@ -519,7 +519,7 @@ all the modules.
type. flags is either zero or SWIG_POINTER_DISOWN (see below). -20.6.1 Garbage collection
+21.6.1 Garbage collection
If the owner flag passed to
must be called manually. -SWIG_NewPointerObj
is 1,NewPointerObj
will add a @@ -550,7 +550,7 @@ all the modules.20.7 Unsupported features and known problems
+21.7 Unsupported features and known problems
@@ -560,7 +560,7 @@ all the modules. %feature(compactdefaultargs).
-20.7.1 TinyCLOS problems with Chicken version <= 1.92
+21.7.1 TinyCLOS problems with Chicken version <= 1.92
In Chicken versions equal to or below 1.92, TinyCLOS has a limitation such that generic methods do not properly work on methods diff --git a/Doc/Manual/Contents.html b/Doc/Manual/Contents.html index 77280c8..7107384 100644 --- a/Doc/Manual/Contents.html +++ b/Doc/Manual/Contents.html @@ -1,10 +1,12 @@ - +
SWIG Users Manual + +SWIG Users Manual
@@ -142,8 +144,8 @@
Basic Type Handling Global Variables Constants - A brief word about const - A cautionary tale of char * + A brief word about const + A cautionary tale of char * Pointers and complex objects @@ -158,7 +160,7 @@
- Passing structures by value
- Return by value
- Linking to structure variables -
- Linking to char * +
- Linking to char *
- Arrays
- Creating read-only variables
- Renaming and ignoring declarations @@ -262,7 +264,61 @@
7 Preprocessing
+7 SWIG and C++11
+ + +++ + ++
+- Introduction +
- Core language changes +
+
+- Rvalue reference and move semantics +
- Generalized constant expressions +
- Extern template +
- Initializer lists +
- Uniform initialization +
- Type inference +
- Range-based for-loop +
- Lambda functions and expressions +
- Alternate function syntax +
- Object construction improvement +
- Explicit overrides and final +
- Null pointer constant +
- Strongly typed enumerations +
- Double angle brackets +
- Explicit conversion operators +
- Alias templates +
- Unrestricted unions +
- Variadic templates +
- New string literals +
- User-defined literals +
- Thread-local storage +
- Explicitly defaulted functions and deleted functions +
- Type long long int +
- Static assertions +
- Allow sizeof to work on members of classes without an explicit object +
- Exception specifications and noexcept +
- Control and query object alignment +
- Attributes +
- Standard library changes + +
8 Preprocessing
@@ -285,7 +341,7 @@-8 SWIG library
+9 SWIG library
@@ -311,6 +367,7 @@-std::vector STL exceptions shared_ptr smart pointer + auto_ptr smart pointer Utility Libraries @@ -320,7 +377,7 @@
9 Argument Handling
+10 Argument Handling
@@ -343,7 +400,7 @@-10 Typemaps
+11 Typemaps
@@ -386,6 +443,8 @@-$descriptor(type) $typemap(method, typepattern) + Special variables and typemap attributes + Special variables combined with special variable macros Common typemap methods @@ -423,7 +482,7 @@
- Usage
Typemaps and overloading - More about %apply and %clear + More about %apply and %clear Passing data between typemaps C++ "this" pointer Where to go for more information? @@ -431,7 +490,7 @@ 11 Customization Features
+12 Customization Features
@@ -459,7 +518,7 @@-12 Contracts
+13 Contracts
@@ -472,7 +531,7 @@-13 Variable Length Arguments
+14 Variable Length Arguments
@@ -490,7 +549,7 @@-14 Warning Messages
+15 Warning Messages
@@ -518,7 +577,7 @@-15 Working with Modules
+16 Working with Modules
@@ -534,7 +593,7 @@-16 Using SWIG with ccache - ccache-swig(1) manpage
+17 Using SWIG with ccache - ccache-swig(1) manpage
@@ -560,7 +619,7 @@-17 SWIG and Allegro Common Lisp
+18 SWIG and Allegro Common Lisp
@@ -644,7 +703,7 @@-18 SWIG and Android
+19 SWIG and Android
@@ -662,12 +721,16 @@-19 SWIG and C#
+20 SWIG and C#
--
- Introduction +
- Differences to the Java module
- Void pointers
- C# Arrays @@ -689,7 +752,7 @@
- Directors implementation
- Director caveats
Multiples modules + Multiple modules C# Typemap examples
- Memory management when returning references to member variables @@ -705,7 +768,7 @@
20 SWIG and Chicken
+21 SWIG and Chicken
@@ -743,7 +806,7 @@-21 SWIG and D
+22 SWIG and D
@@ -760,13 +823,13 @@-Code injection typemaps Special variable macros - %features + D and %feature Pragmas D Exceptions D Directors Other features 22 SWIG and Go
+23 SWIG and Go
-23 SWIG and Guile
+24 SWIG and Guile
@@ -843,7 +919,7 @@-24 SWIG and Java
+25 SWIG and Java
@@ -891,6 +967,10 @@-C++ namespaces C++ templates C++ Smart Pointers + Further details on the generated Java classes @@ -917,6 +997,7 @@
+- Proper Java enum classes
- Type unsafe enum classes
Interfaces Cross language polymorphism using directors Accessing protected members Common customization features @@ -987,7 +1069,49 @@ 25 SWIG and Common Lisp
+26 SWIG and Javascript
+ + +++ + ++
+- Overview +
- Preliminaries + +
- Integration + +
- Examples + +
- Implementation + +
27 SWIG and Common Lisp
@@ -1010,7 +1134,7 @@-26 SWIG and Lua
+28 SWIG and Lua
@@ -1029,8 +1153,11 @@-Functions Global variables Constants and enums + Pointers - Structures + Structures C++ classes C++ inheritance Pointers, references, values, and arrays @@ -1041,17 +1168,23 @@ C++ templates C++ Smart Pointers C++ Exceptions + Namespaces + Typemaps - Writing typemaps + Writing typemaps Customization of your Bindings @@ -1069,7 +1202,7 @@ 27 SWIG and Modula-3
+29 SWIG and Modula-3
@@ -1107,7 +1240,7 @@-28 SWIG and MzScheme/Racket
+30 SWIG and MzScheme/Racket
@@ -1119,7 +1252,7 @@-29 SWIG and Ocaml
+31 SWIG and Ocaml
@@ -1159,10 +1292,10 @@-Overriding Methods in Ocaml Director Usage Example Creating director objects - Typemaps for directors, directorin, directorout, directorargout - directorin typemap - directorout typemap - directorargout typemap + Typemaps for directors, directorin, directorout, directorargout + typemap + directorout typemap + directorargout typemap Exceptions @@ -1170,7 +1303,7 @@ 30 SWIG and Octave
+32 SWIG and Octave
@@ -1196,6 +1329,10 @@-Class extension with %extend C++ templates C++ Smart Pointers + Directors (calling Octave from C++ code) Threads Memory management @@ -1206,7 +1343,7 @@ 31 SWIG and Perl5
+33 SWIG and Perl5
@@ -1269,11 +1406,20 @@-Modifying the proxy methods Adding additional Perl code + Cross language polymorphism + 32 SWIG and PHP
+34 SWIG and PHP
@@ -1292,10 +1438,11 @@-Pointers and References Structures and C++ classes PHP Pragmas, Startup and Shutdown code @@ -1313,7 +1460,7 @@ 33 SWIG and Pike
+35 SWIG and Pike
@@ -1337,7 +1484,7 @@-34 SWIG and Python
+36 SWIG and Python
@@ -1370,6 +1517,10 @@-C++ namespaces C++ templates C++ Smart Pointers + C++ reference counted objects Further details on the Python class interface @@ -1406,6 +1557,7 @@ Simple pointers Unbounded C Arrays String handling + Default arguments Typemaps @@ -1437,17 +1589,33 @@
- %feature("docstring")
Python Packages + Python 3 Support 35 SWIG and R
+37 SWIG and R
@@ -1463,7 +1631,7 @@-36 SWIG and Ruby
+38 SWIG and Ruby
@@ -1499,6 +1667,10 @@-C++ STL Functors C++ STL Iterators C++ Smart Pointers + Cross-Language Polymorphism
- Exception Unrolling @@ -1597,7 +1769,76 @@
37 SWIG and Tcl
+39 SWIG and Scilab
+ + +++ + ++
+- Preliminaries +
- Running SWIG + +
- A basic tour of C/C++ wrapping + +
- Type mappings and libraries + +
- Module initialization +
- Building modes + +
- Generated scripts + +
- Other resources +
40 SWIG and Tcl
@@ -1663,7 +1904,7 @@-38 Extending SWIG to support new languages
+41 Extending SWIG to support new languages
diff --git a/Doc/Manual/Contract.html b/Doc/Manual/Contract.html index de390fb..4b49958 100644 --- a/Doc/Manual/Contract.html +++ b/Doc/Manual/Contract.html @@ -1,12 +1,13 @@ - +@@ -240,7 +245,7 @@ Note: This implementation is only intended to illustrate the general idea. To m modify it to handle nested try declarations. -Contract Checking + -12 Contracts
+13 Contracts
-@@ -38,7 +39,7 @@ When one of the rules is violated by a script, a runtime exception is generated rather than having the program continue to execute. -
12.1 The %contract directive
+13.1 The %contract directive
@@ -94,7 +95,7 @@ RuntimeError: Contract violation: require: (arg1>=0)
12.2 %contract and classes
+13.2 %contract and classes
@@ -173,7 +174,7 @@ specified for the derived class all must hold. In the above example, this means that both the arguments to Spam::bar must be positive.
-12.3 Constant aggregation and %aggregate_check
+13.3 Constant aggregation and %aggregate_check
@@ -262,7 +263,7 @@ Regrettably, there is no automatic way to perform similar checks with enums valu release.
-12.4 Notes
+13.4 Notes
diff --git a/Doc/Manual/Customization.html b/Doc/Manual/Customization.html index f420f42..8705534 100644 --- a/Doc/Manual/Customization.html +++ b/Doc/Manual/Customization.html @@ -1,12 +1,13 @@ - +
Customization Features + -11 Customization Features
+12 Customization Features
@@ -136,13 +139,13 @@ To use these functions, functions simply call@@ -45,7 +46,7 @@ of exception handling is presented. Then, a more general-purpose customization mechanism known as "features" is described. -
11.1 Exception handling with %exception
+12.1 Exception handling with %exception
@@ -100,7 +101,7 @@ for exception handling. That directive is deprecated--%exception provides the same functionality, but is substantially more flexible.
-11.1.1 Handling exceptions in C code
+12.1.1 Handling exceptions in C code
@@ -115,16 +116,18 @@ static char error_message[256]; static int error_status = 0; void throw_exception(char *msg) { - strncpy(error_message,msg,256); - error_status = 1; + strncpy(error_message,msg,256); + error_status = 1; } void clear_exception() { - error_status = 0; + error_status = 0; } char *check_exception() { - if (error_status) return error_message; - else return NULL; + if (error_status) + return error_message; + else + return NULL; }
double inv(double x) { - if (x != 0) return 1.0/x; - else { - throw_exception("Division by zero"); - return 0; - } + if (x != 0) + return 1.0/x; + else { + throw_exception("Division by zero"); + return 0; + } } -@@ -151,12 +154,12 @@ as the following (shown for Perl5) :
@@ -166,7 +169,7 @@ Each target language has its own approach to creating a runtime error/exception and for Perl it is the croak method shown above. -%exception { - char *err; - clear_exception(); - $action - if ((err = check_exception())) { - croak(err); - } + char *err; + clear_exception(); + $action + if ((err = check_exception())) { + croak(err); + } }11.1.2 Exception handling with longjmp()
+12.1.2 Exception handling with longjmp()
@@ -206,8 +209,10 @@ Now, within a C program, you can do the following :
@@ -221,17 +226,17 @@ Finally, to create a SWIG exception handler, write the following : %} %exception { - try { - $action - } catch(RangeError) { - croak("Range Error"); - } catch(DivisionByZero) { - croak("Division by zero"); - } catch(OutOfMemory) { - croak("Out of memory"); - } finally { - croak("Unknown exception"); - } + try { + $action + } catch(RangeError) { + croak("Range Error"); + } catch(DivisionByZero) { + croak("Division by zero"); + } catch(OutOfMemory) { + croak("Out of memory"); + } finally { + croak("Unknown exception"); + } }double inv(double x) { - if (x) return 1.0/x; - else throw(DivisionByZero); + if (x) + return 1.0/x; + else + throw(DivisionByZero); }11.1.3 Handling C++ exceptions
+12.1.3 Handling C++ exceptions
@@ -249,17 +254,17 @@ Handling C++ exceptions is also straightforward. For example:
@@ -275,7 +280,7 @@ class OutOfMemory {};%exception { - try { - $action - } catch(RangeError) { - croak("Range Error"); - } catch(DivisionByZero) { - croak("Division by zero"); - } catch(OutOfMemory) { - croak("Out of memory"); - } catch(...) { - croak("Unknown exception"); - } + try { + $action + } catch(RangeError) { + croak("Range Error"); + } catch(DivisionByZero) { + croak("Division by zero"); + } catch(OutOfMemory) { + croak("Out of memory"); + } catch(...) { + croak("Unknown exception"); + } }11.1.4 Exception handlers for variables
+12.1.4 Exception handlers for variables
@@ -300,7 +305,7 @@ The %allowexception feature works like any other feature and so can be
11.1.5 Defining different exception handlers
+12.1.5 Defining different exception handlers
@@ -319,7 +324,7 @@ critical pieces of code. For example:
-%exception { - ... your exception handler ... + ... your exception handler ... } /* Define critical operations that can throw exceptions here */ @@ -437,7 +442,7 @@ declarations. However, it never really worked that well and the new %exception directive is much better. -11.1.6 Special variables for %exception
+12.1.6 Special variables for %exception
@@ -485,12 +490,12 @@ variables are replaced with.
- $parentname +$parentclassname The parent class name (if any) for a method. - @@ -540,14 +545,14 @@ Below shows the expansions for the 1st of the overloaded something wrap$parentsymname +$parentclasssymname The target language parent class name (if any) for a method. 11.1.7 Using The SWIG exception library
+12.1.7 Using The SWIG exception library
The exception.i library file provides support for creating language independent exceptions in your interfaces. To use it, simply put an "%include exception.i" in your interface file. This -creates a function SWIG_exception() that can be used to raise +provides a function SWIG_exception() that can be used to raise common scripting language exceptions in a portable manner. For example :
-@@ -595,7 +600,7 @@ SWIG_NullReferenceError The SWIG_exception() function can also be used in typemaps. -11.2 Object ownership and %newobject
+12.2 Object ownership and %newobject
@@ -752,7 +757,7 @@ char *strdup(const char *s); The results might not be what you expect.
-11.3 Features and the %feature directive
+12.3 Features and the %feature directive
@@ -834,7 +839,7 @@ The following are all equivalent: The syntax in the first variation will generate the { } delimiters used whereas the other variations will not.
-11.3.1 Feature attributes
+12.3.1 Feature attributes
@@ -875,7 +880,7 @@ In the following example, MyExceptionClass is the name of the Java clas Further details can be obtained from the Java exception handling section.
-11.3.2 Feature flags
+12.3.2 Feature flags
@@ -973,7 +978,7 @@ in the swig.swg Library file. The following shows the alternative synta The concept of clearing features is discussed next.
-11.3.3 Clearing features
+12.3.3 Clearing features
@@ -1066,7 +1071,7 @@ The three macros below show this for the "except" feature:
11.3.4 Features and default arguments
+12.3.4 Features and default arguments
@@ -1082,7 +1087,7 @@ For example:
@@ -1105,7 +1110,7 @@ If the default arguments are not specified in the feature:-%feature("except") void hello(int i=0, double d=0.0) { ... } +%feature("except") hello(int i=0, double d=0.0) { ... } void hello(int i=0, double d=0.0);@@ -1141,7 +1146,7 @@ specifying or not specifying default arguments in a feature is not applicable as in SWIG-1.3.23 when the approach to wrapping methods with default arguments was changed. --%feature("except") void hello(int i, double d) { ... } +%feature("except") hello(int i, double d) { ... } void hello(int i=0, double d=0.0);11.3.5 Feature example
+12.3.5 Feature example
diff --git a/Doc/Manual/D.html b/Doc/Manual/D.html index 43fa691..9e8e653 100644 --- a/Doc/Manual/D.html +++ b/Doc/Manual/D.html @@ -1,4 +1,4 @@ - +
SWIG and D @@ -6,7 +6,7 @@ -21 SWIG and D
+22 SWIG and D
-@@ -22,13 +22,13 @@
-- Code injection typemaps
- Special variable macros
%features + D and %feature Pragmas D Exceptions D Directors Other features -
- Extended namespace support (nspace) +
- Extended namespace support (nspace)
- Native pointer support
- Operator overloading
- Running the test-suite @@ -41,7 +41,7 @@ -
21.1 Introduction
+22.1 Introduction
From the D Programming Language web site: D is a systems programming language. Its focus is on combining the power and high performance of C and C++ with the programmer productivity of modern languages like Ruby and Python. [...] The D language is statically typed and compiles directly to machine code. As such, it is not very surprising that D is able to directly interface with C libraries. Why would a SWIG module for D be needed then in the first place?
@@ -50,10 +50,10 @@While these issues can be worked around relatively easy by hand-coding a thin wrapper layer around the C library in question, there is another issue where writing wrapper code per hand is not feasible: C++ libraries. D did not support interfacing to C++ in version 1 at all, and even if extern(C++) has been added to D2, the support is still very limited, and a custom wrapper layer is still required in many cases.
-To help addressing these issues, the SWIG C# module has been forked to support D. Is has evolved quite a lot since then, but there are still many similarities, so if you do not find what you are looking for on this page, it might be worth having a look at the chapter on C# (and also on Java, since the C# module was in turn forked from it).
+To help addressing these issues, the SWIG C# module has been forked to support D. Is has evolved quite a lot since then, but there are still many similarities, so if you do not find what you are looking for on this page, it might be worth having a look at the chapter on C# (and also on Java, since the C# module was in turn forked from it).
-21.2 Command line invocation
+22.2 Command line invocation
To activate the D module, pass the -d option to SWIG at the command line. The same standard command line switches as with any other language module are available, plus the following D specific ones:
@@ -64,7 +64,7 @@By default, SWIG generates code for D1/Tango. Use the -d2 flag to target D2/Phobos instead.
-- -splitproxy
+- -splitproxy
By default, SWIG generates two D modules: the proxy module, named like the source module (either specified via the %module directive or via the module command line switch), which contains all the proxy classes, functions, enums, etc., and the intermediary module (named like the proxy module, but suffixed with _im), which contains all the extern(C) function declarations and other private parts only used internally by the proxy module.
If the split proxy mode is enabled by passing this switch at the command line, all proxy classes and enums are emitted to their own D module instead. The main proxy module only contains free functions and constants in this case.
@@ -83,10 +83,10 @@ -21.3 Typemaps
+22.3 Typemaps
-21.3.1 C# <-> D name comparison
+22.3.1 C# <-> D name comparison
If you already know the SWIG C# module, you might find the following name comparison table useful:
@@ -112,7 +112,7 @@21.3.2 ctype, imtype, dtype
+22.3.2 ctype, imtype, dtype
Mapping of types between the C/C++ library, the C/C++ library wrapper exposing the C functions, the D wrapper module importing these functions and the D proxy code.
@@ -120,26 +120,26 @@The ctype typemap is used to determine the types to use in the C wrapper functions. The types from the imtype typemap are used in the extern(C) declarations of these functions in the intermediary D module. The dtype typemap contains the D types used in the D proxy module/class.
-21.3.3 in, out, directorin, directorout
+22.3.3 in, out, directorin, directorout
Used for converting between the types for C/C++ and D when generating the code for the wrapper functions (on the C++ side).
-The code from the in typemap is used to convert arguments to the C wrapper function to the type used in the wrapped code (ctype->original C++ type), the out typemap is utilized to convert values from the wrapped code to wrapper function return types (original C++ type->ctype).
+The code from the in typemap is used to convert arguments to the C wrapper function to the type used in the wrapped code (ctype->original C++ type), the out typemap is utilized to convert values from the wrapped code to wrapper function return types (original C++ type->ctype).
The directorin typemap is used to convert parameters to the type used in the D director callback function, its return value is processed by directorout (see below).
-21.3.4 din, dout, ddirectorin, ddirectorout
+22.3.4 din, dout, ddirectorin, ddirectorout
Typemaps for code generation in D proxy and type wrapper classes.
-The din typemap is used for converting function parameter types from the type used in the proxy module or class to the type used in the intermediary D module (the $dinput macro is replaced). To inject further parameter processing code before or after the call to the intermediary layer, the pre, post and terminator attributes can be used (please refer to the C# date marshalling example for more information on these).
+The din typemap is used for converting function parameter types from the type used in the proxy module or class to the type used in the intermediary D module (the $dinput macro is replaced). To inject further parameter processing code before or after the call to the intermediary layer, the pre, post and terminator attributes can be used (please refer to the C# date marshalling example for more information on these).
-The dout typemap is used for converting function return values from the return type used in the intermediary D module to the type returned by the proxy function. The $excode special variable in dout typemaps is replaced by the excode typemap attribute code if the method can throw any exceptions from unmanaged code, otherwise by nothing (the $imcall and $owner macros are replaced).
+The dout typemap is used for converting function return values from the return type used in the intermediary D module to the type returned by the proxy function. The $excode special variable in dout typemaps is replaced by the excode typemap attribute code if the method can throw any exceptions from unmanaged code, otherwise by nothing (the $imcall and $owner macros are replaced).
-The code from the ddirectorin and ddirectorout typemaps is used for conversion in director callback functions. Arguments are converted to the type used in the proxy class method they are calling by using the code from ddirectorin, the proxy class method return value is converted to the type the C++ code expects via the ddirectorout typemap (the $dcall and $winput macros are replaced).
+The code from the ddirectorin and ddirectorout typemaps is used for conversion in director callback functions. Arguments are converted to the type used in the proxy class method they are calling by using the code from ddirectorin, the proxy class method return value is converted to the type the C++ code expects via the ddirectorout typemap (the $dcall and $winput macros are replaced).
The full chain of type conversions when a director callback is invoked looks like this:
@@ -157,13 +157,13 @@ dtype DClass.method(dtype a)
Because, unlike many scripting languages supported by SWIG, D does not need any dynamic dispatch helper to access an overloaded function, the purpose of these is merely to issue a warning for overloaded C++ functions that cannot be overloaded in D (as more than one C++ type maps to a single D type).
-These typemaps are used for generating the skeleton of proxy classes for C++ types.
@@ -172,10 +172,10 @@Using dcode and dimports, you can specify additional D code which will be emitted into the class body respectively the imports section of the D module the class is written to.
-dconstructor, ddestructor, ddispose and ddispose_derived are used to generate the class constructor, destructor and dispose() method, respectively. The auxiliary code for handling the pointer to the C++ object is stored in dbody and dbody_derived. You can override them for specific types.
+dconstructor, ddestructor, ddispose and ddispose_derived are used to generate the class constructor, destructor and dispose() method, respectively. The auxiliary code for handling the pointer to the C++ object is stored in dbody and dbody_derived. You can override them for specific types.
-The standard SWIG special variables are available for use within typemaps as described in the Typemaps documentation, for example $1, $input, $result etc.
@@ -197,7 +197,7 @@In code inserted into the generated C/C++ wrapper functions, this variable is replaced by either 0 or nothing at all, depending on whether the function has a return value or not. It can be used to bail out early e.g. in case of errors (return $null;).
This variable is used in din typemaps and is replaced by the expression which is to be passed to C/C++.
For example, this input
@@ -214,7 +214,7 @@ void foo(SomeClass arg) { example_im.foo(SomeClass.getCPointer(arg)); }These variables are used in dout typemaps. $imcall contains the call to the intermediary module which provides the value to be used, and $owner signals if the caller is responsible for managing the object lifetime (that is, if the called method is a constructor or has been marked via %newobject).
Consider the following example:
@@ -243,7 +243,7 @@ SomeClass bar() {These variables are used in the director-specific typemaps ddirectorin and ddirectorout. They are more or less the reverse of the $imcall and $dinput macros: $dcall contains the invocation of the D proxy method of which the return value is to be passed back to C++, $winput contains the parameter value from C++.
These variables are used in the director-specific typemaps ddirectorin and ddirectorout. They are more or less the reverse of the $imcall and $dinput macros: $dcall contains the invocation of the D proxy method of which the return value is to be passed back to C++, $winput contains the parameter value from C++.
This variable is used in dout and dconstructor typemaps and is filled with the contents of the excode typemap attribute if an exception could be thrown from the C++ side. See the C# documentation for details.
This macro is used in the dimports typemap if a dependency on another D type generated by SWIG is added by a custom typemap.
Consider the following code snippet:
@@ -295,7 +295,7 @@ $importtype(AnotherInterface) -The D module defines a number of directives which modify the SWIG features set globally or for a specific declaration:
@@ -325,7 +325,7 @@ struct A { -There are a few SWIG pragmas specific to the D module, which you can use to influence the D code SWIG generates:
@@ -364,7 +364,7 @@ struct A { -Out of the box, C++ exceptions are fundamentally incompatible to their equivalent in the D world and cannot simply be propagated to a calling D method. There is, however, an easy way to solve this problem: Just catch the exception in the C/C++ wrapper layer, pass the contents to D, and make the wrapper code rethrow the exception in the D world.
@@ -374,7 +374,7 @@ struct A {As this feature is implemented in exactly the same way it is for C#, please see the C# documentation for a more detailed explanation.
-When the directors feature is activated, SWIG generates extra code on both the C++ and the D side to enable cross-language polymorphism. Essentially, this means that if you subclass a proxy class in D, C++ code can access any overridden virtual methods just as if you created a derived class in C++.
@@ -383,16 +383,16 @@ struct A { -By default, SWIG flattens all C++ namespaces into a single target language namespace, but as for Java and C#, the nspace feature is supported for D. If it is active, C++ namespaces are mapped to D packages/modules. Note, however, that like for the other languages, free variables and functions are not supported yet; currently, they are all allows written to the main proxy D module.
-Contrary to many of the scripting languages supported by SWIG, D fully supports C-style pointers. The D module thus includes a custom mechanism to wrap C pointers directly as D pointers where applicable, that is, if the type that is pointed to is represented the same in C and D (on the bit-level), dubbed a primitive type below.
@@ -404,7 +404,7 @@ struct A {To determine if a type should be considered primitive, the cprimitive attribute on its dtype attribute is used. For example, the dtype typemap for float has cprimitive="1", so the code from the nativepointer attribute is taken into account e.g. for float ** or the function pointer float (*)(float *).
-The D module comes with basic operator overloading support for both D1 and D2. There are, however, a few limitations arising from conceptual differences between C++ and D:
@@ -416,7 +416,7 @@ struct A {There are also some cases where the operators can be translated to D, but the differences in the implementation details are big enough that a rather involved scheme would be required for automatic wrapping them, which has not been implemented yet. This affects, for example, the array subscript operator, [], in combination with assignments - while operator [] in C++ simply returns a reference which is then written to, D resorts to a separate opIndexAssign method -, or implicit casting (which was introduced in D2 via alias this). Despite the lack of automatic support, manually handling these cases should be perfectly possible.
-As with any other language, the SWIG test-suite can be built for D using the *-d-test-suite targets of the top-level Makefile. By default, D1 is targeted, to build it with D2, use the optional D_VERSION variable, e.g. make check-d-test-suite D_VERSION=2.
@@ -424,14 +424,14 @@ struct A {Note: If you want to use GDC on Linux or another platform which requires you to link libdl for dynamically loading the shared library, you might have to add -ldl manually to the d_compile target in Examples/Makefile, because GDC does not currently honor the pragma(lib,...) statement.
-There are no D-specific typemap examples yet. However, with the above name comparison table, you should be able to get an idea what can be done by looking at the corresponding C# section.
-There are a couple of features which are not implemented yet, but would be very useful and might be added in the near future:
diff --git a/Doc/Manual/Extending.html b/Doc/Manual/Extending.html index 5ea4e51f..14dcbdc 100644 --- a/Doc/Manual/Extending.html +++ b/Doc/Manual/Extending.html @@ -1,12 +1,13 @@ - +@@ -91,7 +92,7 @@ Also, this chapter is not meant to be a hand-holding tutorial. As a starting po you should probably look at one of SWIG's existing modules.
-@@ -121,7 +122,7 @@ obvious, but almost all SWIG directives as well as the low-level generation of wrapper code are driven by C++ datatypes.
-@@ -158,7 +159,7 @@ role in making the system work. For example, both typemaps and declaration anno based on pattern matching and interact heavily with the underlying type system.
-@@ -203,7 +204,7 @@ latter stage of compilation. The next few sections briefly describe some of these stages.
-@@ -284,7 +285,7 @@ been expanded as well as everything else that goes into the low-level construction of the wrapper code.
-@@ -385,7 +386,7 @@ returning a foo and taking types a and b as arguments).
-@@ -640,7 +641,7 @@ $ swig -c++ -python -debug-module 4 example.i
@@ -659,7 +660,7 @@ that matches the name of the target language. For example, python:foo perl:foo.
-@@ -750,7 +751,7 @@ example.i:5. Previous declaration is foo_i(int ) -
@@ -806,7 +807,7 @@ For example, the exception code above is simply stored without any modifications.
-@@ -928,7 +929,7 @@ public : The role of these functions is described shortly.
-@@ -941,7 +942,7 @@ internal data structures, it may be useful to keep XML in the back of your mind as a model.
-@@ -987,7 +988,7 @@ typedef Hash Typetab; -
@@ -1128,7 +1129,7 @@ Returns the number of replacements made (if any). -
@@ -1205,7 +1206,7 @@ Returns the list of hash table keys. -
@@ -1294,7 +1295,7 @@ If t is not a standard object, it is assumed to be a char * and is used to create a String object. -
-int Close(String_or_FILE *f) +There's no explicit function to close a file, just call Delete(f) - +this decreases the reference count, and the file will be closed when the +reference count reaches zero.
-Closes a file. Has no effect on strings.
-The use of the above I/O functions and strings play a critical role in SWIG. It is common to see small code fragments of code generated using code like this: @@ -1529,9 +1529,7 @@ Printf(f, "%s\n", s); Similarly, the preprocessor and parser all operate on string-files.
-@@ -1782,7 +1780,7 @@ the attribute is optional. Swig_restore() must always be called after function. -
@@ -1791,7 +1789,7 @@ pointers, references, and pointers to members. A detailed discussion of type theory is impossible here. However, let's cover the highlights.
-@@ -1892,7 +1890,7 @@ make the final type, the two parts are just joined together using string concatenation.
-@@ -2061,7 +2059,7 @@ Returns the prefix of a type. For example, if ty is ty is unmodified. -
@@ -2148,7 +2146,7 @@ Checks if ty is a varargs type. Checks if ty is a templatized type. -
@@ -2250,7 +2248,7 @@ Fully reduces ty according to typedef rules. Resulting datatype will consist only of primitive typenames. -
@@ -2287,7 +2285,7 @@ Literal y; // type = 'Literal', ltype='p.char' -
@@ -2349,7 +2347,7 @@ SWIG, but is most commonly associated with type-descriptor objects that appear in wrappers (e.g., SWIGTYPE_p_double). -
@@ -2448,7 +2446,7 @@ included. Used to emit prototypes. Returns the number of required (non-optional) arguments in p. -
@@ -2463,7 +2461,7 @@ describes the creation of a minimal Python module. You should be able to extra this to other languages.
-@@ -2473,7 +2471,7 @@ the parsing of command line options, all aspects of code generation are controll different methods of the Language that must be defined by your module.
-@@ -2581,7 +2579,7 @@ that activates your module. For example, swig -python foo.i. The messages from your new module should appear.
-@@ -2640,7 +2638,7 @@ to mark the option as valid. If you forget to do this, SWIG will terminate wit unrecognized command line option error.
-@@ -2689,7 +2687,7 @@ an implementation file python.cxx and a configuration file python.swg.
-@@ -2747,7 +2745,7 @@ int Python::top(Node *n) { -
@@ -2832,7 +2830,6 @@ int Python::top(Node *n) { Delete(f_header); Delete(f_wrappers); Delete(f_init); - Close(f_begin); Delete(f_begin); return SWIG_OK; @@ -2896,7 +2893,7 @@ functionWrapper : void Shape_y_set(Shape *self,double y) -
@@ -3203,7 +3200,7 @@ Discuss the kinds of functions typically needed for SWIG runtime support (e.g. the SWIG files that implement those functions.
-@@ -3222,7 +3219,7 @@ The following are the minimum that are usually supported: Please copy these and modify for any new language.
-@@ -3251,7 +3248,7 @@ during this process, see the section on .
-@@ -3310,7 +3307,7 @@ It is therefore essential that the runtime tests are written in a manner that di but error/exception out with an error message on stderr on failure.
-@@ -3350,10 +3347,10 @@ Note that if a runtime test is available, a message "(with run test)" is display
$ make check-python-test-suite checking python test-suite -checking testcase argcargvtest (with run test) under python -checking testcase python_autodoc under python -checking testcase python_append (with run test) under python -checking testcase callback (with run test) under python +checking python testcase argcargvtest (with run test) +checking python testcase python_autodoc +checking python testcase python_append (with run test) +checking python testcase callback (with run test)
@@ -3496,7 +3493,13 @@ The syntax for setting environment variables varies from one shell to the next, make ret_by_value.ctest SWIG_FEATURES="-debug-tmsearch" -
+There is also a special 'errors' test-suite which is a set of regression tests checking SWIG warning and error messages. +It can be run in the same way as the other language test-suites, replacing [lang] with errors, such as make check-errors-test-suite. +The test cases used and the way it works is described in Examples/test-suite/errors/Makefile.in. +
+ +@@ -3528,7 +3531,7 @@ Some topics that you'll want to be sure to address include: if available. -
@@ -3585,7 +3588,7 @@ should be added should there be an area not already covered by the existing tests.
-@@ -3609,7 +3612,7 @@ The generated C/C++ code should also follow this style as close as possible. How should be avoided as unlike the SWIG developers, users will never have consistent tab settings.
-@@ -3636,7 +3639,7 @@ There are various command line options which can aid debugging a SWIG interface The complete list of command line options for SWIG are available by running swig -help.
-@@ -4044,7 +4047,7 @@ extern "X" { ... } declaration. -
diff --git a/Doc/Manual/Go.html b/Doc/Manual/Go.html index 7a55a43..f25e985 100644 --- a/Doc/Manual/Go.html +++ b/Doc/Manual/Go.html @@ -1,19 +1,21 @@ - +
+Go does not support direct calling of functions written in C/C++. The +cgo program may be used to generate +wrappers to call C code from Go, but there is no convenient way to call C++ +code. SWIG fills this gap. +
+ ++There are (at least) two different Go compilers. The first is the gc compiler +of the Go distribution, normally +invoked via the go tool. +The second Go compiler is the +gccgo compiler, which is a frontend to the GCC compiler suite. +The interface to C/C++ code is completely different for the two Go compilers. +SWIG supports both Go compilers, selected by the -gccgo command line +option. +
+ ++Go is a type-safe compiled language and the wrapper code generated by SWIG is +type-safe as well. In case of type issues the build will fail and hence SWIG's +runtime library and +runtime type checking +are not used. +
+ +-Go is a compiled language, not a scripting language. However, it does -not support direct calling of functions written in C/C++. The cgo -program may be used to generate wrappers to call C code from Go, but -there is no convenient way to call C++ code. SWIG fills this gap. +Working examples can be found in the +SWIG source tree +.
-There are (at least) two different Go compilers. One is the gc -compiler, normally invoked under the names 6g, 8g, or 5g. The other -is the gccgo compiler, which is a frontend to the gcc compiler suite. -The interface to C/C++ code is completely different for the two Go -compilers. SWIG supports both, selected by a command line option. +Please note that the examples in the SWIG source tree use makefiles with the .i +SWIG interface file extension for backwards compatibility with Go 1.
+ ++Most Go programs are built using the go +tool. Since Go 1.1 the go tool has support for SWIG. To use it, give your +SWIG interface file the extension .swig (for C code) or .swigcxx (for C++ code). +Put that file in a GOPATH/src directory as usual for Go sources. Put other +C/C++ code in the same directory with extensions of .c and .cxx. The +go build and go install commands will automatically run SWIG +for you and compile the generated wrapper code. To check the SWIG command line +options the go tool uses run go build -x. To access the automatically +generated files run go build -work. You'll find the files under the +temporary WORK directory. +
+ ++To manually generate and compile C/C++ wrapper code for Go, use the -go +option with SWIG. By default SWIG will generate code for the Go compiler of the +Go distribution. To generate code for gccgo, you should also use the +-gccgo option. +
+ ++When using the -cgo option, SWIG will generate files that can be used +directly by go build. Starting with the Go 1.5 distribution the +-cgo option has to be given. Put your SWIG interface file in a +directory under GOPATH/src, and give it a name that does not end in the +.swig or .swigcxx extension. Typically the SWIG interface file extension is .i +in this case. +
+ ++% swig -go -cgo example.i +% go install +
-Because Go is a type-safe compiled language, SWIG's runtime type -checking and runtime library are not used with Go. This should be -borne in mind when reading the rest of the SWIG documentation. +You will now have a Go package that you can import from other Go packages as +usual.
-+To use SWIG without the -cgo option, more steps are required. Recall +that this only works with Go versions before 1.5. When using Go version 1.2 or +later, or when using gccgo, the code generated by SWIG can be linked directly +into the Go program. A typical command sequence when using the Go compiler of +the Go distribution would look like this: +
++% swig -go example.i +% gcc -c code.c # The C library being wrapped. +% gcc -c example_wrap.c +% go tool 6g example.go +% go tool 6c example_gc.c +% go tool pack grc example.a example.6 example_gc.6 code.o example_wrap.o +% go tool 6g main.go +% go tool 6l main.6 +
-To generate Go code, use the -go option with SWIG. By -default SWIG will generate code for the gc compilers. To generate -code for gccgo, you should also use the -gccgo option. +You can also put the wrapped code into a shared library, and when using the Go +versions before 1.2 this is the only supported option. A typical command +sequence for this approach would look like this:
-+% swig -go -use-shlib example.i +% gcc -c -fpic example.c +% gcc -c -fpic example_wrap.c +% gcc -shared example.o example_wrap.o -o example.so +% go tool 6g example.go +% go tool 6c example_gc.c +% go tool pack grc example.a example.6 example_gc.6 +% go tool 6g main.go # your code, not generated by SWIG +% go tool 6l main.6 +
-These are the command line options for SWIG's GO module. They can +These are the command line options for SWIG's Go module. They can also be seen by using:
@@ -88,15 +193,23 @@ also be seen by using: swig -go -help -Go-specific options | +|||
---|---|---|---|
Go specific options | +-cgo | +Generate files to be used as input for the Go cgo tool. This + option is required for Go 1.5 and later, and works for Go 1.2 and + later. In the future this option will likely become the + default. | |
-intgo-type-size %lt;s%gt; | +-intgosize <s> | Set the size for the Go type int. This controls the size - that the C/C++ code expects to see. The %lt;s%gt; argument should + that the C/C++ code expects to see. The <s> argument should be 32 or 64. This option is currently required during the transition from Go 1.0 to Go 1.1, as the size of int on 64-bit x86 systems changes between those releases (from 32 bits to @@ -108,7 +221,7 @@ swig -go -help | |
-gccgo | Generate code for gccgo. The default is to generate code for - 6g/8g/5g. | + the Go compiler of the Go distribution.||
-soname %lt;name%gt; | +-use-shlib | +Tell SWIG to emit code that uses a shared library. This is only + meaningful for the Go compiler of the Go distribution, which needs to know at + compile time whether a shared library will be used. | +|
-soname <name> | Set the runtime name of the shared library that the dynamic linker
should include at runtime. The default is the package name with
".so" appended. This is only used when generating code for
- 6g/8g/5g; when using gccgo, the equivalent name will be taken from
- the -soname option passed to the linker. |
+ the Go compiler of the Go distribution; when using gccgo, the equivalent name
+ will be taken from the ||
-go-prefix <prefix> | -When generating code for gccgo, set the prefix to use. This - corresponds to the -fgo-prefix option to gccgo. | +-go-pkgpath <pkgpath> | +When generating code for gccgo, set the pkgpath to use. This + corresponds to the -fgo-pkgpath option to gccgo. |
-long-type-size <s> | -Set the size for the C/C++ type long. This controls - whether long is converted to the Go type int32 - or int64. The <s> argument should be 32 or 64. | +-go-prefix <prefix> | +When generating code for gccgo, set the prefix to use. This + corresponds to the -fgo-prefix option to gccgo. + If -go-pkgpath is used, -go-prefix will be + ignored. |
There are two different approaches to generating wrapper files, + controlled by SWIG's -cgo option. The -cgo option + works with Go version 1.2 or later. It is required when using Go + version 1.5 or later.
-When generating Go code, SWIG will generate the following - files:
+With or without the -cgo option, SWIG will generate the + following files when generating wrapper code:
-A typical command sequence would look like this: -
+When neither the -cgo nor the -gccgo option is + used, SWIG will also generate an additional file:
+ +-% swig -go example.i -% gcc -c -fpic example.c -% gcc -c -fpic example_wrap.c -% gcc -shared example.o example_wrap.o -o example.so -% 6g example.go -% 6c example_gc.c -% gopack grc example.a example.6 example_gc.6 -% 6g main.go # your code, not generated by SWIG -% 6l main.6 -
@@ -196,7 +318,7 @@ modifications have to occur. This section briefly covers the essential aspects of this wrapping.
-@@ -206,7 +328,7 @@ directive. You may override this by using SWIG's -package command line option.
-@@ -238,7 +360,7 @@ followed by that name, and the destructor will be named Delete followed by that name.
-@@ -246,7 +368,7 @@ C/C++ constants created via #define or the %constant directive become Go constants, declared with a const declaration. -
@@ -256,7 +378,7 @@ usual). The values of the enumeration will become variables in Go; code should avoid modifying those variables.
-@@ -324,7 +446,7 @@ type MyClass interface { MyMethod() int } -MyClassMyFactoryFunction() MyClass { +func MyClassMyFactoryFunction() MyClass { // swig magic here } @@ -334,7 +456,129 @@ returns a go interface. If the returned pointer can be null, you can check for this by calling the Swigcptr() method.
-
+Calling NewClassName for a C++ class ClassName will allocate
+memory using the C++ memory allocator. This memory will not be automatically
+freed by Go's garbage collector as the object ownership is not tracked. When
+you are done with the C++ object you must free it using
+DeleteClassName.
+
+The most Go idiomatic way to manage the memory for some C++ class is to call
+NewClassName followed by a
+defer of
+the DeleteClassName call. Using defer ensures that the memory
+of the C++ object is freed as soon as the function containing the defer
+statement returns. Furthemore defer works great for short-lived
+objects and fits nicely C++'s RAII idiom. Example:
+
+func UseClassName(...) ... { + o := NewClassName(...) + defer DeleteClassName(o) + // Use the ClassName object + return ... +} ++
+With increasing complexity, especially complex C++ object hierarchies, the +correct placement of defer statements becomes harder and harder as C++ +objects need to be freed in the correct order. This problem can be eased by +keeping a C++ object function local so that it is only available to the function +that creates a C++ object and functions called by this function. Example: +
++func WithClassName(constructor args, f func(ClassName, ...interface{}) error, data ...interface{}) error { + o := NewClassName(constructor args) + defer DeleteClassName(o) + return f(o, data...) +} + +func UseClassName(o ClassName, data ...interface{}) (err error) { + // Use the ClassName object and additional data and return error. +} + +func main() { + WithClassName(constructor args, UseClassName, additional data) +} ++
+Using defer has limitations though, especially when it comes to
+long-lived C++ objects whichs lifetimes are hard to predict. For such C++
+objects a common technique is to store the C++ object into a Go object, and to
+use the Go function runtime.SetFinalizer to add a finalizer which frees
+the C++ object when the Go object is freed. It is strongly recommended to read
+the runtime.SetFinalizer
+ documentation before using this technique to understand the
+runtime.SetFinalizer limitations.
+
+Common pitfalls with runtime.SetFinalizer are: +
++runtime.SetFinalizer Example: +
++import ( + "runtime" + "wrap" // SWIG generated wrapper code +) + +type GoClassName struct { + wcn wrap.ClassName +} + +func NewGoClassName() *GoClassName { + o := &GoClassName{wcn: wrap.NewClassName()} + runtime.SetFinalizer(o, deleteGoClassName) + return o +} + +func deleteGoClassName(o *GoClassName) { + // Runs typically in a different OS thread! + wrap.DeleteClassName(o.wcn) + o.wcn = nil +} + +func (o *GoClassName) Close() { + // If the C++ object has a Close method. + o.wcn.Close() + + // If the GoClassName object is no longer in an usable state. + runtime.SetFinalizer(o, nil) // Remove finalizer. + deleteGoClassName() // Free the C++ object. +} ++
@@ -346,7 +590,7 @@ Doing the reverse will require an explicit type assertion, which will be checked dynamically.
-@@ -354,50 +598,551 @@ In order to use C++ templates in Go, you must tell SWIG to create wrappers for a particular template instantation. To do this, use the %template directive. -
+SWIG's director feature permits a Go type to act as the subclass of a C++ class. +This is complicated by the fact that C++ and Go define inheritance differently. +SWIG normally represents the C++ class inheritance automatically in Go via +interfaces but with a Go type representing a subclass of a C++ class some manual +work is necessary. +
+ ++This subchapter gives a step by step guide how to properly sublass a C++ class +with a Go type. In general it is strongly recommended to follow this guide +completely to avoid common pitfalls with directors in Go. +
+ + ++The step by step guide is based on two example C++ classes. FooBarAbstract is +an abstract C++ class and the FooBarCpp class inherits from it. This guide +explains how to implement a FooBarGo class similar to the FooBarCpp class. +
+ ++FooBarAbstract abstract C++ class: +
+ ++class FooBarAbstract +{ +public: + FooBarAbstract() {}; + virtual ~FooBarAbstract() {}; + + std::string FooBar() { + return this->Foo() + ", " + this->Bar(); + }; + +protected: + virtual std::string Foo() { + return "Foo"; + }; + + virtual std::string Bar() = 0; +}; ++
+FooBarCpp C++ class: +
+ ++class FooBarCpp : public FooBarAbstract +{ +protected: + virtual std::string Foo() { + return "C++ " + FooBarAbstract::Foo(); + } + + virtual std::string Bar() { + return "C++ Bar"; + } +}; ++
+Returned string by the FooBarCpp::FooBar method is: +
+ ++C++ Foo, C++ Bar ++
+The complete example, including the FooBarGoo class implementation, can +be found in the end of the guide. +
+ + ++The director feature is disabled by default. To use directors you must make two +changes to the interface file. First, add the "directors" option to the %module +directive, like this: +
+ ++%module(directors="1") modulename ++
+Second, you must use the %feature("director") directive to tell SWIG which +classes should get directors. In the example the FooBarAbstract class needs the +director feature enabled so that the FooBarGo class can inherit from it, like +this: +
+ ++%feature("director") FooBarAbstract; ++
-SWIG's director feature permits a Go type to act as the subclass of a -C++ class with virtual methods. This is complicated by the fact that -C++ and Go define inheritance differently. In Go, structs can inherit -methods via anonymous field embedding. However, when a method is -called for an embedded struct, if that method calls any other methods, -they are called for the embedded struct, not for the original type. -Therefore, SWIG must use Go interfaces to represent C++ inheritance. +For a more detailed documentation of the director feature and how to enable or +disable it for specific classes and virtual methods see SWIG's Java +documentation on directors. +
+ + ++SWIG creates an additional set of constructor and destructor functions once the +director feature has been enabled for a C++ class. +NewDirectorClassName allows overriding virtual methods on the new +object instance and DeleteDirectorClassName needs to be used to free a +director object instance created with NewDirectorClassName. +More on overriding virtual methods follows later in this guide under +overriding virtual methods.
-In order to use the director feature in Go, you must define a type in -your Go code. You must then add methods for the type. Define a -method in Go for each C++ virtual function that you want to override. -You must then create a value of your new type, and pass a pointer to -it to the function NewDirectorClassName, -where ClassName is the name of the C++ class. That will -return a value of type ClassName. +The default constructor and destructor functions NewClassName and +DeleteClassName can still be used as before so that existing code +doesn't break just because the director feature has been enabled for a C++ +class. The behavior is undefined if the default and director constructor and +destructor functions get mixed and so great care needs to be taken that only one +of the constructor and destructor function pairs is used for any object +instance. Both constructor functions, the default and the director one, return +the same interface type. This makes it potentially hard to know which +destructor function, the default or the director one, needs to be called to +delete an object instance.
-For example: +In theory the DirectorInterface method could be used to +determine if an object instance was created via NewDirectorClassName:
-type GoClass struct { } -func (p *GoClass) VirtualFunction() { } -func MakeClass() ClassName { - return NewDirectorClassName(&GoClass{}) +if o.DirectorInterface() != nil { + DeleteDirectorClassName(o) +} else { + DeleteClassName(o) }
-Any call in C++ code to the virtual function will wind up calling the -method defined in Go. The Go code may of course call other methods on -itself, and those methods may be defined either in Go or in C++. +In practice it is strongly recommended to embed a director object +instance in a Go struct so that a director object instance will be represented +as a distinct Go type that subclasses a C++ class. For this Go type custom +constructor and destructor functions take care of the director constructor and +destructor function calls and the resulting Go class will appear to the user as +any other SWIG wrapped C++ class. More on properly subclassing a C++ class +follows later in this guide under subclass via +embedding. +
+ + ++In order to override virtual methods on a C++ class with Go methods the +NewDirectorClassName constructor functions receives a +DirectorInterface argument. The methods in the +DirectorInterface are a subset of the public and protected virtual methods +of the C++ class. If the DirectorInterface contains a method with a +matching signature to a virtual method of the C++ class then the virtual C++ +method will be overwritten with the Go method. As Go doesn't support protected +methods all overriden protected virtual C++ methods will be public in Go.
-+As an example see part of the FooBarGo class: +
+ ++type overwrittenMethodsOnFooBarAbstract struct { + fb FooBarAbstract +} + +func (om *overwrittenMethodsOnFooBarAbstract) Foo() string { + ... +} + +func (om *overwrittenMethodsOnFooBarAbstract) Bar() string { + ... +} + +func NewFooBarGo() FooBarGo { + om := &overwrittenMethodsOnFooBarAbstract{} + fb := NewDirectorFooBarAbstract(om) + om.fb = fb + ... +} ++
+The complete example, including the FooBarGoo class implementation, can +be found in the end of the guide. In +this part of the example the virtual methods FooBarAbstract::Foo and +FooBarAbstract::Bar have been overwritten with Go methods similarly to +how the FooBarAbstract virtual methods are overwritten by the +FooBarCpp class. +
+ ++The DirectorInterface in the example is implemented by the +overwrittenMethodsOnFooBarAbstract Go struct type. A pointer to a +overwrittenMethodsOnFooBarAbstract struct instance will be given to the +NewDirectorFooBarAbstract constructor function. The constructor return +value implements the FooBarAbstract interface. +overwrittenMethodsOnFooBarAbstract could in theory be any Go type but +in practice a struct is used as it typically contains at least a value of the +C++ class interface so that the overwritten methods can use the rest of the +C++ class. If the FooBarGo class would receive additional constructor +arguments then these would also typically be stored in the +overwrittenMethodsOnFooBarAbstract struct so that they can be used by +the Go methods. +
+ + ++Often a virtual method will be overwritten to extend the original behavior of +the method in the base class. This is also the case for the +FooBarCpp::Foo method of the example code: +
+ ++virtual std::string Foo() { + return "C++ " + FooBarAbstract::Foo(); +} ++
+To use base methods the DirectorClassNameMethodName wrapper functions +are automatically generated by SWIG for public and protected virtual methods. +The FooBarGo.Foo implementation in the example looks like this: +
+ ++func (om *overwrittenMethodsOnFooBarAbstract) Foo() string { + return "Go " + DirectorFooBarAbstractFoo(om.fb) +} ++
+The complete example, including the FooBarGoo class implementation, can +be found in the end of the guide. +
+ + ++As previously mentioned in this guide the +default and director constructor functions return the same interface type. To +properly subclass a C++ class with a Go type the director object instance +returned by the NewDirectorClassName constructor function should be +embedded into a Go struct so that it represents a distinct but compatible type +in Go's type system. This Go struct should be private and the constructor and +destructor functions should instead work with a public interface type so that +the Go class that subclasses a C++ class can be used as a compatible drop in. +
+ ++The subclassing part of the FooBarGo class for an example looks like +this: +
+ ++type FooBarGo interface { + FooBarAbstract + deleteFooBarAbstract() + IsFooBarGo() +} + +type fooBarGo struct { + FooBarAbstract +} + +func (fbgs *fooBarGo) deleteFooBarAbstract() { + DeleteDirectorFooBarAbstract(fbgs.FooBarAbstract) +} + +func (fbgs *fooBarGo) IsFooBarGo() {} + +func NewFooBarGo() FooBarGo { + om := &overwrittenMethodsOnFooBarAbstract{} + fb := NewDirectorFooBarAbstract(om) + om.fb = fb + + return &fooBarGo{FooBarAbstract: fb} +} + +func DeleteFooBarGo(fbg FooBarGo) { + fbg.deleteFooBarAbstract() +} ++
+The complete example, including the FooBarGoo class implementation, can +be found in the end of the guide. In +this part of the example the private fooBarGo struct embeds +FooBarAbstract which lets the fooBarGo Go type "inherit" all the +methods of the FooBarAbstract C++ class by means of embedding. The +public FooBarGo interface type includes the FooBarAbstract +interface and hence FooBarGo can be used as a drop in replacement for +FooBarAbstract while the reverse isn't possible and would raise a +compile time error. Furthemore the constructor and destructor functions +NewFooBarGo and DeleteFooBarGo take care of all the director +specifics and to the user the class appears as any other SWIG wrapped C++ +class. +
+ + ++In general all guidelines for C++ class memory +management apply as well to director classes. One often overlooked +limitation with runtime.SetFinalizer is that a finalizer doesn't run +in case of a cycle and director classes typically have a cycle. The cycle +in the FooBarGo class is here: +
+ ++type overwrittenMethodsOnFooBarAbstract struct { + fb FooBarAbstract +} + +func NewFooBarGo() FooBarGo { + om := &overwrittenMethodsOnFooBarAbstract{} + fb := NewDirectorFooBarAbstract(om) // fb.v = om + om.fb = fb // Backlink causes cycle as fb.v = om! + ... +} ++
+In order to be able to use runtime.SetFinalizer nevertheless the +finalizer needs to be set on something that isn't in a cycle and that references +the director object instance. In the FooBarGo class example the +FooBarAbstract director instance can be automatically deleted by setting +the finalizer on fooBarGo: +
+ ++type fooBarGo struct { + FooBarAbstract +} + +type overwrittenMethodsOnFooBarAbstract struct { + fb FooBarAbstract +} + +func NewFooBarGo() FooBarGo { + om := &overwrittenMethodsOnFooBarAbstract{} + fb := NewDirectorFooBarAbstract(om) + om.fb = fb // Backlink causes cycle as fb.v = om! + + fbgs := &fooBarGo{FooBarAbstract: fb} + runtime.SetFinalizer(fbgs, FooBarGo.deleteFooBarAbstract) + return fbgs +} ++
+Furthermore if runtime.SetFinalizer is in use either the +DeleteClassName destructor function needs to be removed or the +fooBarGo struct needs additional data to prevent double deletion. Please +read the C++ class memory management subchapter +before using runtime.SetFinalizer to know all of its gotchas. +
+ + ++The complete and annotated FooBarGo class looks like this: +
+ ++// FooBarGo is a superset of FooBarAbstract and hence FooBarGo can be used as a +// drop in replacement for FooBarAbstract but the reverse causes a compile time +// error. +type FooBarGo interface { + FooBarAbstract + deleteFooBarAbstract() + IsFooBarGo() +} + +// Via embedding fooBarGo "inherits" all methods of FooBarAbstract. +type fooBarGo struct { + FooBarAbstract +} + +func (fbgs *fooBarGo) deleteFooBarAbstract() { + DeleteDirectorFooBarAbstract(fbgs.FooBarAbstract) +} + +// The IsFooBarGo method ensures that FooBarGo is a superset of FooBarAbstract. +// This is also how the class hierarchy gets represented by the SWIG generated +// wrapper code. For an instance FooBarCpp has the IsFooBarAbstract and +// IsFooBarCpp methods. +func (fbgs *fooBarGo) IsFooBarGo() {} + +// Go type that defines the DirectorInterface. It contains the Foo and Bar +// methods that overwrite the respective virtual C++ methods on FooBarAbstract. +type overwrittenMethodsOnFooBarAbstract struct { + // Backlink to FooBarAbstract so that the rest of the class can be used by + // the overridden methods. + fb FooBarAbstract + + // If additional constructor arguments have been given they are typically + // stored here so that the overriden methods can use them. +} + +func (om *overwrittenMethodsOnFooBarAbstract) Foo() string { + // DirectorFooBarAbstractFoo calls the base method FooBarAbstract::Foo. + return "Go " + DirectorFooBarAbstractFoo(om.fb) +} + +func (om *overwrittenMethodsOnFooBarAbstract) Bar() string { + return "Go Bar" +} + +func NewFooBarGo() FooBarGo { + // Instantiate FooBarAbstract with selected methods overridden. The methods + // that will be overwritten are defined on + // overwrittenMethodsOnFooBarAbstract and have a compatible signature to the + // respective virtual C++ methods. Furthermore additional constructor + // arguments will be typically stored in the + // overwrittenMethodsOnFooBarAbstract struct. + om := &overwrittenMethodsOnFooBarAbstract{} + fb := NewDirectorFooBarAbstract(om) + om.fb = fb // Backlink causes cycle as fb.v = om! + + fbgs := &fooBarGo{FooBarAbstract: fb} + // The memory of the FooBarAbstract director object instance can be + // automatically freed once the FooBarGo instance is garbage collected by + // uncommenting the following line. Please make sure to understand the + // runtime.SetFinalizer specific gotchas before doing this. Furthemore + // DeleteFooBarGo should be deleted if a finalizer is in use or the fooBarGo + // struct needs additional data to prevent double deletion. + // runtime.SetFinalizer(fbgs, FooBarGo.deleteFooBarAbstract) + return fbgs +} + +// Recommended to be removed if runtime.SetFinalizer is in use. +func DeleteFooBarGo(fbg FooBarGo) { + fbg.deleteFooBarAbstract() +} ++
+Returned string by the FooBarGo.FooBar method is: +
+ ++Go Foo, Go Bar ++
+For comparison the FooBarCpp class looks like this: +
+ ++class FooBarCpp : public FooBarAbstract +{ +protected: + virtual std::string Foo() { + return "C++ " + FooBarAbstract::Foo(); + } + + virtual std::string Bar() { + return "C++ Bar"; + } +}; ++
+For comparison the returned string by the FooBarCpp::FooBar method is: +
+ ++C++ Foo, C++ Bar ++
+The complete source of this example can be found under + +SWIG/Examples/go/director/. +
+ + +@@ -454,12 +1199,12 @@ uses a given C/C++ type.
Because of limitations in the way output arguments are processed in swig, @@ -557,7 +1302,7 @@ void f(char *output); -
Often the APIs generated by swig are not very natural in go, especially if @@ -626,9 +1371,174 @@ func (arg SwigcptrWrapped_MyClass) GetAValue() (int, bool) { few, then you might as well define your own struct that includes the swig-wrapped object, instead of adding methods to the swig-generated object.
-This only works if your wrappers do not need to import other go modules. -There is at present no way to insert import statements in the correct place -in swig-generated go. If you need to do that, you must put your go code -in a separate file.
+If you need to import other go packages, you can do this with
+%go_import
. For example,
+%go_import("fmt", _ "unusedPackage", rp "renamed/package") + +%insert(go_wrapper) %{ + +func foo() { + fmt.Println("Some string:", rp.GetString()) +} + +// Importing the same package twice is permitted, +// Go code will be generated with only the first instance of the import. +%go_import("fmt") + +%insert(go_wrapper) %{ + +func bar() { + fmt.Println("Hello world!") +} + +%} ++
+You can use the %typemap directive to modify SWIG's default +wrapping behavior for specific C/C++ types. You need to be familiar +with the material in the general +"Typemaps" chapter. That chapter +explains how to define a typemap. This section describes some +specific typemaps used for Go. +
+ ++In general type conversion code may be written either in C/C++ or in +Go. The choice to make normally depends on where memory should be +allocated. To allocate memory controlled by the Go garbage collector, +write Go code. To allocate memory in the C/C++ heap, write C code. +
+ +Typemap | +Description | +
gotype | ++The Go type to use for a C++ type. This type will appear in the +generated Go wrapper function. If this is not defined SWIG will use a +default as described above. + | +
imtype | ++An intermediate Go type used by the "goin", "goout", "godirectorin", +and "godirectorout" typemaps. If this typemap is not defined for a +C/C++ type, the gotype typemape will be used. This is useful when +gotype is best converted to C/C++ using Go code. + | +
goin | ++Go code to convert from gotype to imtype when calling a C/C++ +function. SWIG will then internally convert imtype to a C/C++ type +and pass it down. If this is not defined, or is the empty string, no +conversion is done. + | +
in | ++C/C++ code to convert the internally generated C/C++ type, based on +imtype, into the C/C++ type that a function call expects. If this is +not defined the value will simply be cast to the desired type. + | +
out | ++C/C++ code to convert the C/C++ type that a function call returns into +the internally generated C/C++ type, based on imtype, that will be +returned to Go. If this is not defined the value will simply be cast +to the desired type. + | +
goout | ++Go code to convert a value returned from a C/C++ function from imtype +to gotype. If this is not defined, or is the empty string, no +conversion is done. + | +
argout | ++C/C++ code to adjust an argument value when returning from a function. +This is called after the real C/C++ function has run. This uses the +internally generated C/C++ type, based on imtype. This is only useful +for a pointer type of some sort. If this is not defined nothing will +be done. + | +
goargout | ++Go code to adjust an argument value when returning from a function. +This is called after the real C/C++ function has run. The value will +be in imtype. This is only useful for a pointer type of some sort. +If this is not defined, or is the empty string, nothing will be done. + | +
directorin | ++C/C++ code to convert the C/C++ type used to call a director method +into the internally generated C/C++ type, based on imtype, that will +be passed to Go. If this is not defined the value will simply be cast +to the desired type. + | +
godirectorin | ++Go code to convert a value used to call a director method from imtype +to gotype. If this is not defined, or is the empty string, no +conversion is done. + | +
godirectorout | ++Go code to convert a value returned from a director method from gotype +to imtype. If this is not defined, or is the empty string, no +conversion is done. + | +
directorout | ++C/C++ code to convert a value returned from a director method from the +internally generated C/C++ type, based on imtype, into the type that +the method should return If this is not defined the value will simply +be cast to the desired type. + | +
This section details guile-specific support in SWIG. -
@@ -61,7 +61,7 @@ improved performance. This is currently not tested with swig so your mileage may vary. To be safe set environment variable GUILE_AUTO_COMPILE to 0 when using swig generated guile code. -
@@ -69,7 +69,7 @@ There are three different concepts of "module" involved, defined separately for SWIG, Guile, and Libtool. To avoid horrible confusion, we explicitly prefix the context, e.g., "guile-module". -
Guile 1.8 and older could be interfaced using two different api's, the SCM @@ -80,7 +80,7 @@ or the GH API. The GH interface to guile is deprecated. Read more about why in version of SWIG that can still generate guile GH wrapper code is 2.0.9. Please use that version if you really need the GH wrapper code. -
@@ -88,7 +88,7 @@ Guile support is complicated by a lack of user community cohesiveness, which manifests in multiple shared-library usage conventions. A set of policies implementing a usage convention is called a linkage. -
@@ -158,8 +158,8 @@ following module-system hack:
(module-map (lambda (sym var) - (module-export! (current-module) (list sym))) - (current-module)) + (module-export! (current-module) (list sym))) + (current-module))
define-module
form and the
SWIG_init
via a preprocessor define to avoid symbol
clashes. For this case, however, passive linkage is available.
-Passive linkage is just like simple linkage, but it generates an @@ -203,7 +203,7 @@ package name (see below).
You should use passive linkage rather than simple linkage when you are using multiple modules. -
SWIG can also generate wrapper code that does all the Guile module @@ -244,7 +244,7 @@ Newer Guile versions have a shorthand procedure for this:
Guile used to support an autoloading facility for object-code @@ -270,7 +270,7 @@ option, SWIG generates an exported module initialization function with an appropriate name. -
@@ -295,7 +295,7 @@ my/lib/libfoo.so.X.Y.Z and friends. This scheme is still very experimental; the (hobbit4d link) conventions are not well understood.
-
@@ -307,7 +307,7 @@ complained so far.
%rename
to specify the Guile name of the wrapped
functions and variables (see CHANGES).
-
@@ -399,7 +399,7 @@ constant will appear as a scheme variable. See Features and the %feature directive for info on how to apply the %feature.
-
@@ -420,7 +420,7 @@ representing the expected pointer type. See also
If the Scheme object passed was not a SWIG smob representing a compatible
pointer, a wrong-type-arg
exception is raised.
-
@@ -439,7 +439,7 @@ structure describing this type. If a generated GOOPS module has been loaded, sm the corresponding GOOPS class.
-Garbage collection is a feature of Guile since version 1.6. As SWIG now requires Guile > 1.8, @@ -453,7 +453,7 @@ is exactly like described in 23.8 Exception Handling +
@@ -462,16 +462,16 @@ mapping:
- MAP(SWIG_MemoryError, "swig-memory-error"); - MAP(SWIG_IOError, "swig-io-error"); - MAP(SWIG_RuntimeError, "swig-runtime-error"); - MAP(SWIG_IndexError, "swig-index-error"); - MAP(SWIG_TypeError, "swig-type-error"); - MAP(SWIG_DivisionByZero, "swig-division-by-zero"); - MAP(SWIG_OverflowError, "swig-overflow-error"); - MAP(SWIG_SyntaxError, "swig-syntax-error"); - MAP(SWIG_ValueError, "swig-value-error"); - MAP(SWIG_SystemError, "swig-system-error"); + MAP(SWIG_MemoryError, "swig-memory-error"); + MAP(SWIG_IOError, "swig-io-error"); + MAP(SWIG_RuntimeError, "swig-runtime-error"); + MAP(SWIG_IndexError, "swig-index-error"); + MAP(SWIG_TypeError, "swig-type-error"); + MAP(SWIG_DivisionByZero, "swig-division-by-zero"); + MAP(SWIG_OverflowError, "swig-overflow-error"); + MAP(SWIG_SyntaxError, "swig-syntax-error"); + MAP(SWIG_ValueError, "swig-value-error"); + MAP(SWIG_SystemError, "swig-system-error");
If invoked with the command-line option For global variables, SWIG creates a single wrapper procedure
@@ -542,7 +542,7 @@ struct members, the procedures SWIG can also generate classes and generic functions for use with
@@ -688,7 +688,7 @@ Notice that <Foo> is used before it is defined. The fix is to just put th
As you can see in the example above, there are potential naming conflicts. The default exported
@@ -725,7 +725,7 @@ guile-modules. For example, The guile-modules generated above all need to be linked together. GOOPS support requires
diff --git a/Doc/Manual/Introduction.html b/Doc/Manual/Introduction.html
index a8d15a5..1c29f47 100644
--- a/Doc/Manual/Introduction.html
+++ b/Doc/Manual/Introduction.html
@@ -1,12 +1,13 @@
-
+
SWIG is a software development tool that simplifies the task of
interfacing different languages to C and C++ programs. In a
nutshell, SWIG is a compiler that takes C/C++ declarations and creates
-the wrappers needed to access those declarations from other languages including
+the wrappers needed to access those declarations from other languages
including Perl, Python, Tcl, Ruby, Guile, and Java. SWIG normally
requires no modifications to existing code and can often be used to
build a usable interface in only a few minutes. Possible applications
@@ -49,7 +50,7 @@ of SWIG include:
@@ -98,7 +99,7 @@ of other libraries).
To address these limitations, many programmers have arrived at the
@@ -143,7 +144,7 @@ it provides a wide variety of customization features that let you change almost
every aspect of the language bindings. This is the main reason why SWIG has such a large
user manual ;-).
-
@@ -157,14 +158,16 @@ following C code:
double My_variable = 3.0;
/* Compute factorial of n */
-int fact(int n) {
- if (n <= 1) return 1;
- else return n*fact(n-1);
+int fact(int n) {
+ if (n <= 1)
+ return 1;
+ else
+ return n*fact(n-1);
}
/* Compute n mod m */
int my_mod(int n, int m) {
- return(n % m);
+ return(n % m);
}
@@ -221,8 +224,7 @@ unix > tclsh
7.5
%
-
+
The swig command produced a new file called
example_wrap.c that should be compiled along with the
example.c file. Most operating systems and scripting
@@ -233,7 +235,7 @@ and variables declared in the SWIG interface. A look at the file
example_wrap.c reveals a hideous mess. However, you
almost never need to worry about it.
-
@@ -244,8 +246,8 @@ any changes type the following (shown for Solaris):
@@ -283,7 +285,7 @@ Type "copyright", "credits" or "license" for more information.
7.5
-
@@ -296,7 +298,7 @@ SWIG on the C header file and specifying a module name as follows
@@ -334,8 +336,7 @@ major features include:
-Currently, the only major C++ feature not supported is nested classes--a limitation
-that should be removed in a future release, but has some workarounds for the moment.
+Most of C++11 is also supported. Details are in the C++11 section.
@@ -345,11 +346,11 @@ not only parses C++, it implements the full C++ type system and it is
able to understand C++ semantics. SWIG generates its wrappers with
full knowledge of this information. As a result, you will find SWIG
to be just as capable of dealing with nasty corner cases as it is in
-wrapping simple C++ code. In fact, SWIG is able handle C++ code that
+wrapping simple C++ code. In fact, SWIG is able to handle C++ code that
stresses the very limits of many C++ compilers.
-
@@ -361,7 +362,7 @@ interface and reuse the code in other applications. It is also
possible to support different types of interfaces depending on the application.
@@ -384,12 +385,12 @@ for further information on this and other Autoconf macros.
-There is growing support for SWIG in some build tools, for example CMake
+There is growing support for SWIG in some build tools, for example CMake
is a cross-platform, open-source build manager with built in support for SWIG. CMake can detect the SWIG executable
and many of the target language libraries for linking against.
CMake knows how to build shared libraries and loadable modules on many different operating systems.
-This allows easy cross platform SWIG development. It also can generate the custom commands necessary for
-driving SWIG from IDE's and makefiles. All of this can be done from a single cross platform input file.
+This allows easy cross platform SWIG development. It can also generate the custom commands necessary for
+driving SWIG from IDEs and makefiles. All of this can be done from a single cross platform input file.
The following example is a CMake input file for creating a python wrapper for the SWIG interface file, example.i:
-procdoc
@@ -514,7 +514,7 @@ like this:
typemap argument
doc
. See Lib/guile/typemaps.i
for
details.
-23.10 Procedures with setters
+24.10 Procedures with setters
(struct-member-get
pointer)
and (struct-member-set pointer
value)
are not generated.
-23.11 GOOPS Proxy Classes
+24.11 GOOPS Proxy Classes
%import "foo.h"
before the %inline
block.
23.11.1 Naming Issues
+24.11.1 Naming Issues
23.11.2 Linking
+24.11.2 Linking
2 Introduction
+2 Introduction
@@ -31,14 +32,14 @@
-
2.1 What is SWIG?
+2.1 What is SWIG?
2.2 Why use SWIG?
+2.2 Why use SWIG?
2.3 A SWIG example
+2.3 A SWIG example
2.3.1 SWIG interface file
+2.3.1 SWIG interface file
@@ -199,7 +202,7 @@ module that will be created by SWIG. The %{ %} block
provides a location for inserting additional code, such as C header
files or additional C declarations, into the generated C wrapper code.
-
2.3.2 The swig command
+2.3.2 The swig command
2.3.3 Building a Perl5 module
+2.3.3 Building a Perl5 module
unix > swig -perl5 example.i
unix > gcc -c example.c example_wrap.c \
- -I/usr/local/lib/perl5/sun4-solaris/5.003/CORE
-unix > ld -G example.o example_wrap.o -o example.so # This is for Solaris
+ -I/usr/local/lib/perl5/sun4-solaris/5.003/CORE
+unix > ld -G example.o example_wrap.o -o example.so # This is for Solaris
unix > perl5.003
use example;
print example::fact(4), "\n";
@@ -259,7 +261,7 @@ unix >
2.3.4 Building a Python module
+2.3.4 Building a Python module
2.3.5 Shortcuts
+2.3.5 Shortcuts
unix > swig -perl5 -module example example.h
unix > gcc -c example.c example_wrap.c \
- -I/usr/local/lib/perl5/sun4-solaris/5.003/CORE
+ -I/usr/local/lib/perl5/sun4-solaris/5.003/CORE
unix > ld -G example.o example_wrap.o -o example.so
unix > perl5.003
use example;
@@ -309,7 +311,7 @@ print $example::My_variable + 4.5, "\n";
7.5
2.4 Supported C/C++ language features
+2.4 Supported C/C++ language features
2.5 Non-intrusive interface building
+2.5 Non-intrusive interface building
2.6 Incorporating SWIG into a build system
+2.6 Incorporating SWIG into a build system
@@ -432,7 +433,7 @@ it allows others to forget about the low-level implementation details.
-@@ -449,7 +450,7 @@ to work with complicated and unusual C/C++ applications.
Ironically, the freedom that SWIG provides is countered by an -extremely conservative approach to code generation. At it's core, SWIG +extremely conservative approach to code generation. At its core, SWIG tries to distill even the most advanced C++ code down to a small well-defined set of interface building techniques based on ANSI C programming. Because of this, you will find that SWIG interfaces can @@ -458,6 +459,12 @@ be used on any platform. Again, this is an important part of staying out of the programmer's way----the last thing any developer wants to do is to spend their time debugging the output of a tool that relies on non-portable or unreliable programming features. +Dependencies are often a source of incompatibilities and problems and so +additional third party libraries are not used in the generated code. +SWIG will also generally avoid generating code that introduces a dependency +on the C++ Standard Template Library (STL). +SWIG will generate code that depends on the C libraries though. +
diff --git a/Doc/Manual/Java.html b/Doc/Manual/Java.html index 0024d60..d3c5926 100644 --- a/Doc/Manual/Java.html +++ b/Doc/Manual/Java.html @@ -1,11 +1,12 @@ - +@@ -191,7 +198,7 @@ Various customisation tips and techniques using SWIG directives are covered. The latter sections cover the advanced techniques of using typemaps for complete control of the wrapping process.
-@@ -208,10 +215,10 @@ The Java module requires your system to support shared libraries and dynamic loa This is the commonly used method to load JNI code so your system will more than likely support this.
-Android uses Java JNI and also works with SWIG. Please read the Android chapter in conjunction with this one if you are targeting Android. +Android uses Java JNI and also works with SWIG. Please read the Android chapter in conjunction with this one if you are targeting Android.
-@@ -270,7 +277,7 @@ The following sections have further practical examples and details on how you mi compiling and using the generated files.
-@@ -307,7 +314,7 @@ swig -java -help Their use will become clearer by the time you have finished reading this section on SWIG and Java.
-@@ -322,7 +329,7 @@ They are usually in directories like this:
The exact location may vary on your machine, but the above locations are typical.
-@@ -331,8 +338,8 @@ Assuming you have code you need to link to in a file called example.c,
$ swig -java example.i -$ gcc -c example_wrap.c -I/usr/java/include -I/usr/java/include/solaris -$ gcc -c example.c +$ gcc -fPIC -c example_wrap.c -I/usr/java/include -I/usr/java/include/solaris +$ gcc -fPIC -c example.c $ ld -G example_wrap.o example.o -o libexample.so
@@ -357,9 +362,9 @@ more aggressive from gcc-4.0 onwards and will result in code that fails with str
The name of the shared library output file is important. If the name of your SWIG module is "example", the name of the corresponding shared library file should be "libexample.so" (or equivalent depending on your machine, see Dynamic linking problems for more information). -The name of the module is specified using the %module directive or -module command line option.
+The name of the module is specified using the %module directive or -module command line option. -@@ -394,7 +399,7 @@ $ If it doesn't work have a look at the following section which discusses problems loading the shared library.
-@@ -460,9 +465,9 @@ If you forget to compile and link in the SWIG wrapper file into your native libr
$ java runme Exception in thread "main" java.lang.UnsatisfiedLinkError: exampleJNI.gcd(II)I - at exampleJNI.gcd(Native Method) - at example.gcd(example.java:12) - at runme.main(runme.java:18) + at exampleJNI.gcd(Native Method) + at example.gcd(example.java:12) + at runme.main(runme.java:18)
@@ -481,7 +486,7 @@ The following section also contains some C++ specific linking problems and solut
-@@ -492,8 +497,7 @@ compiler. For example:
% swig -c++ -java example.i % g++ -c -fpic example.cxx -% g++ -c -fpic example_wrap.cxx -I/usr/java/j2sdk1.4.1/include -I/usr/java/ -j2sdk1.4.1/include/linux +% g++ -c -fpic example_wrap.cxx -I/usr/java/j2sdk1.4.1/include -I/usr/java/j2sdk1.4.1/include/linux % g++ -shared example.o example_wrap.o -o libexample.so
@@ -543,7 +547,7 @@ You will want to produce a DLL that can be loaded by the Java Virtual Machine. This section covers the process of using SWIG with Microsoft Visual C++ 6 although the procedure may be similar with other compilers. In order for everything to work, you will need to have a JDK installed on your machine in order to read the JNI header files.
-@@ -582,7 +586,7 @@ To run the native code in the DLL (example.dll), make sure that it is in your pa If the library fails to load have a look at Dynamic linking problems.
-@@ -627,11 +631,11 @@ CFLAGS = /Z7 /Od /c /nologo JAVA_INCLUDE = -ID:\jdk1.3\include -ID:\jdk1.3\include\win32 java:: - swig -java -o $(WRAPFILE) $(INTERFACE) - $(CC) $(CFLAGS) $(JAVA_INCLUDE) $(SRCS) $(WRAPFILE) - set LIB=$(TOOLS)\lib - $(LINK) $(LOPT) -out:example.dll $(LIBS) example.obj example_wrap.obj - javac *.java + swig -java -o $(WRAPFILE) $(INTERFACE) + $(CC) $(CFLAGS) $(JAVA_INCLUDE) $(SRCS) $(WRAPFILE) + set LIB=$(TOOLS)\lib + $(LINK) $(LOPT) -out:example.dll $(LIBS) example.obj example_wrap.obj + javac *.java
@@ -641,7 +645,7 @@ Of course you may want to make changes for it to work for C++ by adding in the -
-@@ -651,7 +655,7 @@ variables are wrapped with JavaBean type getters and setters and so forth. This section briefly covers the essential aspects of this wrapping.
-@@ -687,7 +691,7 @@ swig -java -package com.bloggs.swig -outdir com/bloggs/swig example.i SWIG won't create the directory, so make sure it exists beforehand.
-@@ -721,7 +725,7 @@ System.out.println(example.fact(4)); -
@@ -808,7 +812,7 @@ extern char *path; // Read-only (due to %immutable) -
@@ -948,7 +952,7 @@ Or if you decide this practice isn't so bad and your own class implements ex
-@@ -962,7 +966,7 @@ The final two approaches use simple integers for each enum item. Before looking at the various approaches for wrapping named C/C++ enums, anonymous enums are considered.
-@@ -1025,7 +1029,7 @@ As in the case of constants, you can access them through either the module class
-@@ -1119,7 +1123,7 @@ When upgrading to JDK 1.5 or later, proper Java enums could be used instead, wit The following section details proper Java enum generation.
-@@ -1172,7 +1176,7 @@ The additional support methods need not be generated if none of the enum items h Simpler Java enums for enums without initializers section.
-@@ -1220,7 +1224,7 @@ Note that unlike typesafe enums, this approach requires users to mostly use diff Thus the upgrade path to proper enums provided in JDK 1.5 is more painful.
-@@ -1239,7 +1243,7 @@ SWIG-1.3.21 and earlier versions wrapped all enums using this approach. The type unsafe approach is preferable to this one and this simple approach is only included for backwards compatibility with these earlier versions of SWIG.
-@@ -1327,7 +1331,7 @@ C-style cast may return a bogus result whereas as the C++-style cast will return a NULL pointer if the conversion can't be performed.
-@@ -1337,7 +1341,7 @@ member variables. For example,
struct Vector { - double x,y,z; + double x,y,z; };
@@ -1558,7 +1562,7 @@ int bar = Spam.getBar(); -
@@ -1619,7 +1623,7 @@ Note that Java does not support multiple inheritance so any multiple inheritance A warning is given when multiple inheritance is detected and only the first base class is used.
-@@ -1674,7 +1678,7 @@ to hold the result and a pointer is returned (Java will release this memory when the returned object's finalizer is run by the garbage collector).
-@@ -1698,7 +1702,7 @@ For spam1 and spam4 above the Java null gets translat The converse also occurs, that is, NULL pointers are translated into null Java objects when returned from a C/C++ function.
-@@ -1813,7 +1817,7 @@ void spam(unsigned short); // Ignored -
@@ -1856,7 +1860,7 @@ Further details on default arguments and how to restore this approach are given
-@@ -1946,7 +1950,7 @@ If the resulting use of the nspace feature and hence packages results in a proxy you will need to open up the visibility for the pointer constructor and getCPtr method from the default 'protected' to 'public' with the SWIG_JAVABODY_PROXY macro. See Java code typemaps.
-@@ -1995,7 +1999,21 @@ Obviously, there is more to template wrapping than shown in this example. More details can be found in the SWIG and C++ chapter.
-+The C++11 standard provides std::shared_ptr which was derived from the Boost +implementation, boost::shared_ptr. +Both of these are available for Java in the SWIG library and usage is outlined +in the shared_ptr smart pointer library section. +
+ + +@@ -2079,7 +2097,7 @@ Foo f = p.__deref__(); // Returns underlying Foo * -
@@ -2094,7 +2112,7 @@ Finally enum classes are covered. First, the crucial intermediary JNI class is considered.
-@@ -2214,7 +2232,7 @@ If name is the same as modulename then the module class name g from modulename to modulenameModule.
-@@ -2271,7 +2289,7 @@ The jniclasscode pragma is quite useful for adding in a static block fo %pragma(java) jniclasscode=%{ static { try { - System.loadLibrary("example"); + System.loadLibrary("example"); } catch (UnsatisfiedLinkError e) { System.err.println("Native code library failed to load. \n" + e); System.exit(1); @@ -2296,7 +2314,7 @@ For example, let's change the intermediary JNI class access to just the default All the methods in the intermediary JNI class will then not be callable outside of the package as the method modifiers have been changed from public access to default access. This is useful if you want to prevent users calling these low level functions.
-@@ -2327,7 +2345,7 @@ example.egg(new Foo()); The primary reason for having the module class wrapping the calls in the intermediary JNI class is to implement static type checking. In this case only a Foo can be passed to the egg function, whereas any long can be passed to the egg function in the intermediary JNI class.
-@@ -2378,7 +2396,7 @@ See The intermediary JNI class pragmas secti
-@@ -2390,8 +2408,8 @@ The default proxy class for our previous example looks like this:
public class Foo { - private long swigCPtr; - protected boolean swigCMemOwn; + private transient long swigCPtr; + protected transient boolean swigCMemOwn; protected Foo(long cPtr, boolean cMemoryOwn) { swigCMemOwn = cMemoryOwn; @@ -2441,7 +2459,7 @@ It also contains all the methods in the C++ class it is proxying plus getters an member variables. These functions call the native methods in the intermediary JNI class. The advantage of having this extra layer is the type safety that the proxy class functions offer. It adds static type checking which leads to fewer surprises at runtime. -For example, you can see that if you attempt to use the spam() +For example, you can see that if you attempt to use the spam() function it will only compile when the parameters passed are an int and a Foo. From a user's point of view, it makes the class work as if it were a Java class: @@ -2454,7 +2472,7 @@ int y = f.spam(5, new Foo());
@@ -2616,7 +2634,7 @@ and
-@@ -2641,8 +2659,8 @@ The base class is generated much like any other proxy class seen so far:
public class Base { - private long swigCPtr; - protected boolean swigCMemOwn; + private transient long swigCPtr; + protected transient boolean swigCMemOwn; protected Base(long cPtr, boolean cMemoryOwn) { swigCMemOwn = cMemoryOwn; @@ -2682,7 +2700,7 @@ The Derived class extends Base mirroring the C++ class inherit-public class Derived extends Base { - private long swigCPtr; + private transient long swigCPtr; protected Derived(long cPtr, boolean cMemoryOwn) { super(exampleJNI.SWIGDerivedUpcast(cPtr), cMemoryOwn); @@ -2732,7 +2750,7 @@ However, true cross language polymorphism can be achieved using the 24.4.3.3 Proxy classes and garbage collection +25.4.3.3 Proxy classes and garbage collection
@@ -2815,7 +2833,7 @@ The section on Java typemaps details how to specify See the How to Handle Java Finalization's Memory-Retention Issues article for alternative approaches to managing memory by avoiding finalizers altogether.
-24.4.3.4 The premature garbage collection prevention parameter for proxy class marshalling
+25.4.3.4 The premature garbage collection prevention parameter for proxy class marshalling
@@ -2937,7 +2955,7 @@ For example: Compatibility note: The generation of this additional parameter did not occur in versions prior to SWIG-1.3.30.
-24.4.3.5 Single threaded applications and thread safety
+25.4.3.5 Single threaded applications and thread safety
@@ -2960,8 +2978,8 @@ and the Java proxy class generated by SWIG:
-public class Test { - private long swigCPtr; - protected boolean swigCMemOwn; + private transient long swigCPtr; + protected transient boolean swigCMemOwn; protected Test(long cPtr, boolean cMemoryOwn) { swigCMemOwn = cMemoryOwn; @@ -3025,7 +3043,7 @@ for (int i=0; i<100000; i++) {24.4.4 Type wrapper classes
+25.4.4 Type wrapper classes
@@ -3034,7 +3052,7 @@ The generated type wrapper class, for say an int *, looks like this:
-public class SWIGTYPE_p_int { - private long swigCPtr; + private transient long swigCPtr; protected SWIGTYPE_p_int(long cPtr, boolean bFutureUse) { swigCPtr = cPtr; @@ -3112,7 +3130,7 @@ public static void spam(SWIGTYPE_p_int x, SWIGTYPE_p_int y, int z) { ... }24.4.5 Enum classes
+25.4.5 Enum classes
@@ -3121,7 +3139,7 @@ The Enumerations section discussed these but om The following sub-sections detail the various types of enum classes that can be generated.
-24.4.5.1 Typesafe enum classes
+25.4.5.1 Typesafe enum classes
@@ -3205,7 +3223,7 @@ The swigValue method is used for marshalling in the other direction. The toString method is overridden so that the enum name is available.
-24.4.5.2 Proper Java enum classes
+25.4.5.2 Proper Java enum classes
@@ -3283,7 +3301,7 @@ These needn't be generated if the enum being wrapped does not have any initializ Simpler Java enums for enums without initializers section describes how typemaps can be used to achieve this.
-24.4.5.3 Type unsafe enum classes
+25.4.5.3 Type unsafe enum classes
@@ -3314,7 +3332,252 @@ public final class Beverage {
24.5 Cross language polymorphism using directors
+25.4.6 Interfaces
+ + ++By default SWIG wraps all C++ classes as Java classes. +As Java only supports derivation from a single base class, SWIG has to ignore all +bases except the first when a C++ class inherits from more than one base class. +However, there is a family of SWIG macros that change the default wrapping and allows a C++ class +to be wrapped as a Java interface instead of a Java class. +These macros provide a way to support some sort of multiple inheritance as there is no limit to +the number of interfaces that a Java class can inherit from. +
+ ++When a C++ class is wrapped as a Java interface, a Java proxy class is still needed. +The swiginterface.i library file provides three macros for marking a C++ class to be +wrapped as a Java interface. +There is more than one macro in order to provide a choice for choosing the Java interface and Java proxy names. +
+ +
Interface Macro Name | +Description | +
%interface(CTYPE) | +Proxy class name is unchanged, interface name has SwigInterface added as a suffix for C++ class CTYPE. | +
%interface_impl(CTYPE) | +Proxy class name has SwigImpl as a suffix, interface name has SwigInterface added as a suffix for C++ class CTYPE. | +
%interface_custom("PROXY", "INTERFACE", CTYPE) | +Proxy class name is given by the string PROXY, interface name is given by the string INTERFACE for C++ class CTYPE. The PROXY and INTERFACE names can use the string formatting functions used in %rename. | +
+The table below has a few examples showing the resulting proxy and interface names. +
+ +Example Usage | +Proxy Class Name | +Interface Class Name | +
%interface(Base) | +Base | +BaseSwigInterface | +
%interface_impl(Base) | +BaseSwigImpl | +Base | +
%interface_custom("BaseProxy", "IBase", Base) | +BaseProxy | +IBase | +
%interface_custom("%sProxy", "IBase", Base) | +BaseProxy | +IBase | +
%interface_custom("%sProxy", "%sInterface", Base) | +BaseProxy | +BaseProxyInterface | +
%interface_custom("%sProxy", "%(rstrip:[Proxy])sInterface", Base) | +BaseProxy | +BaseInterface | +
+The 2nd last example shows the names used in the string formatting functions. +The input for PROXY that "%s" expands to is the proxy name, that is, Base. +The input for INTERFACE that "%s" expands to is the proxy name, that is, BaseProxy. +
++The last example shows rstrip and in this case strips the Proxy suffix and then adds on Interface. +
+ ++Consider the following C++ code: +
+ ++namespace Space { + struct Base1 { + virtual void Method1(); + }; + struct Base2 { + virtual void Method2(); + }; + struct Derived : Base1, Base2 { + }; + void UseBases(const Base1 &b1, const Base2 &b2); +} ++
+By default all classes are wrapped and are available in Java, but, Derived +has all bases ignored except the first. +SWIG generates a warning for the above code: +
+ ++example.i:10: Warning 813: Warning for Derived, base Base2 ignored. +Multiple inheritance is not supported in Java. ++
+If we decide to wrap the two base classes as interfaces and add the following before SWIG parses the above example code: +
+ ++%include <swiginterface.i> +%interface_impl(Space::Base1); +%interface_impl(Space::Base2); ++
+then two interface files are generated, Base1.java and Base2.java in addition to proxy class files, Base1SwigImpl.java and Base2SwigImpl.java. +The contents of interface file Base1.java for Base1 is shown below: +
+ ++public interface Base1 { + long Base1_GetInterfaceCPtr(); + void Method1(); +} ++
+The proxy class in Base1SwigImpl.java for Base1 is as it would have been if %interface was not used, +except the name has changed to Base1SwigImpl and it implements the appropriate base: +
+ ++public class Base1SwigImpl implements Base1 { +... + public long Base1_GetInterfaceCPtr() { + return exampleJNI.Base1SwigImpl_Base1_GetInterfaceCPtr(swigCPtr); + } + + public void Method1() { + exampleJNI.Base1SwigImpl_Method1(swigCPtr, this); + } +... +} ++
+In fact any class deriving from Base will now implement the interface instead of +deriving from it (or ignoring the base in the case of multiple base classes). +Hence the Derived proxy class will now implement both bases: +
+ ++public class Derived implements Base1, Base2 { +... + public long Base1_GetInterfaceCPtr() { + return exampleJNI.Derived_Base1_GetInterfaceCPtr(swigCPtr); + } + + public long Base2_GetInterfaceCPtr() { + return exampleJNI.Derived_Base2_GetInterfaceCPtr(swigCPtr); + } + + public void Method1() { + exampleJNI.Derived_Method1(swigCPtr, this); + } + + public void Method2() { + exampleJNI.Derived_Method2(swigCPtr, this); + } +... +} ++
+Wherever a class marked as an interface is used, such as the UseBases method in the example, +the interface name is used as the type in the Java layer: +
+ ++ public static void UseBases(Base1 b1, Base2 b2) { + exampleJNI.UseBases(b1.Base1_GetInterfaceCPtr(), b1, b2.Base2_GetInterfaceCPtr(), b2); + } ++
+Note that each Java interface has a method added to obtain the correct C++ pointer for passing to the native function - +Base1_GetInterfaceCPtr for Base1. +This method is similar to the getCPtr method in the proxy classes. +In fact, as shown above in the Derived class, the proxy classes implement +this generated interface by calling a native method (Derived_Base1_GetInterfaceCPtr) +which calls an appropriate C++ cast of the pointer up the inheritance chain. +
+ ++The interface macros are implemented using the interface feature and typemaps. +For example: +
+ ++%define %interface(CTYPE...) +%feature("interface", name="%sSwigInterface") CTYPE; +INTERFACE_TYPEMAPS(CTYPE) +%enddef ++
+The feature accepts one attribute called name, which is the name of the Java interface mentioned earlier. +The INTERFACE_TYPEMAPS macro implements the typemaps and can be viewed in the +swiginterface.i file and contain +the usual Java typemaps for generating code plus the javainterfacecode +typemap which is only used when a class is marked with the interface feature. +See Java code typemaps for details. +
+ +@@ -3336,7 +3599,7 @@ The upshot is that C++ classes can be extended in Java and from C++ these extens Neither C++ code nor Java code needs to know where a particular method is implemented: the combination of proxy classes, director classes, and C wrapper functions transparently takes care of all the cross-language method routing.
-@@ -3404,7 +3667,7 @@ public:
@@ -3431,7 +3694,7 @@ If the correct implementation is in Java, the Java API is used to call the metho
-@@ -3449,7 +3712,7 @@ This situation can be optimized by selectively enabling director methods (using
-@@ -3514,7 +3777,7 @@ DirectorDerived::upcall_method() invoked. -
@@ -3534,7 +3797,7 @@ Macros can be defined on the commandline when compiling your C++ code, or altern -
@@ -3555,8 +3818,315 @@ However, if all director methods are expected to usually be overridden by Java s The disadvantage is that invocation of director methods from C++ when Java doesn't actually override the method will require an additional call up into Java and back to C++. As such, this option is only useful when overrides are extremely common and instantiation is frequent enough that its performance is critical.
+
+With directors routing method calls to Java, and proxies routing them
+to C++, the handling of exceptions is an important concern.
+The default behavior from SWIG 3.0
+onwards is to convert the thrown Java exception into a SWIG defined
+DirectorException
C++ exception.
+SWIG 2.0 and earlier versions didn't provide any mechanism to handle the Java director method exceptions in C++.
+
+Converting Java exceptions into C++ exceptions can be done in two different ways using
+the director:except
feature.
+In the simplest approach, a code block is attached to each director method to
+handle the mapping of Java exceptions into C++ exceptions.
+
+%feature("director:except") MyClass::method(int x) { + jthrowable $error = jenv->ExceptionOccurred(); + if ($error) { + jenv->ExceptionClear(); + if (Swig::ExceptionMatches(jenv, $error, "java/lang/IndexOutOfBoundsException")) + throw std::out_of_range(Swig::JavaExceptionMessage(jenv, $error).message()); + if (Swig::ExceptionMatches(jenv, $error, "$packagepath/MyJavaException")) + throw MyCppException(Swig::JavaExceptionMessage(jenv, $error).message()); + throw std::runtime_error("Unexpected exception thrown in MyClass::method"); + } +} + +class MyClass { + /** Throws either a std::out_of_range or MyCppException on error */ + void method(int x); +} ++
+This approach allows a flexible mapping of Java exceptions thrown by director methods into
+C++ exceptions expected by a C++ caller. There
+need not be any C++ exception specifications on the C++ method. The
+utility function Swig::ExceptionMatches
+and class Swig::JavaExceptionMessage
are provided to simplify
+writing code for wrappers that use the director:except
feature. The
+function Swig::ExceptionMatches
matches the type of the
+jthrowable
thrown against a fully qualified JNI style class
+name, such as "java/lang/IOError"
. If the throwable class is the same
+type, or derives from the given type, Swig::ExceptionMatches
will return true. Care must be taken to
+provide the correct fully qualified name, since for wrapped exceptions the
+generated proxy class will have additional package qualification, depending on
+the '-package' argument and use of the nspace
+ feature. The special variable $error
is expanded by SWIG into a unique variable name and
+should be used for the
+assignment of the exception that occurred. The special variable $packagepath
is
+replaced by the outer package provided for SWIG generation by the -package
+option. The utility class Swig::JavaExceptionMessage
is a holder
+providing access to the message from the thrown Java exception.
+The message()
method returns the exception message as a const char *
,
+which is only valid during the lifetime of the holder. Any code using this message
+needs to copy it, for example into a std::string or a newly constructed C++ exception.
+
+Using the above approach to
+write handlers for a large number of methods will require
+repetitive duplication of the director:except
feature code.
+To mitigate this, an alternative approach is provided via typemaps in a
+fashion analagous to
+the "throws" typemap. The
+"throws" typemap provides an approach to automatically map all the C++
+exceptions listed in a method's defined exceptions (either from
+a C++ exception specification or a %catches
+feature) into Java exceptions.
+The "directorthrows" typemap provides the inverse mapping and should contain
+code to convert a suitably matching Java exception into a C++ exception.
+The example below converts a Java java.lang.IndexOutOfBoundsException
exception
+to the typemap's type, that is std::out_of_range
:
+
+
+%typemap(directorthrows) std::out_of_range %{ + if (Swig::ExceptionMatches(jenv, $error, "java/lang/IndexOutOfBoundsException")) { + throw std::out_of_range(Swig::JavaExceptionMessage(jenv, $error).message()); + } +%} ++
+The "directorthrows" typemap is then used in conjunction with the
+director:except
feature if the $directorthrowshandlers
special variable
+is used in the feature code. Consider the following, which also happens to be the default:
+
+%feature("director:except") %{ + jthrowable $error = jenv->ExceptionOccurred(); + if ($error) { + jenv->ExceptionClear(); + $directorthrowshandlers + throw Swig::DirectorException(jenv, $error); + } +%} ++
The code generated using the director:except
feature
+replaces the $directorthrowshandlers
special variable with the code in
+the "directorthrows" typemaps, for each and every exception defined for the method.
+The possible exceptions can be defined either with a C++ exception
+specification or %catches
as described for the
+"throws" typemap.
+
+Consider the following director method: +
+ ++ ... + virtual void doSomething(int index) throw (std::out_of_range); + ... ++
+When combined with the default director:except
feature and the "directorthrows" typemap above,
+the resulting code generated in the director method after calling up to Java will be:
+
+jthrowable swigerror = jenv->ExceptionOccurred(); +if (swigerror) { + jenv->ExceptionClear(); + if (Swig::ExceptionMatches(jenv, swigerror, "java/lang/IndexOutOfBoundsException")) { + throw std::out_of_range(Swig::JavaExceptionMessage(jenv, swigerror).message()); + } + + throw Swig::DirectorException(jenv, swigerror); +} ++
+Note: Beware of using exception specifications as the SWIG director methods +will be generated with the same exception specifications and if the +director method throws an exception that is not specified it is likely +to terminate your program. See the C++ standard for more details. +Using the %catches feature instead to define the handled exceptions does not suffer +this potential fate. +
+ +Because the default code generation maps any unhandled Java exceptions to
+Swig::DirectorException
, any director methods that have exception
+specifications may cause program termination. To simply ignore
+unexpected exceptions, the default handling can be changed with:
+
+%feature("director:except") %{ + jthrowable $error = jenv->ExceptionOccurred(); + if ($error) { + jenv->ExceptionClear(); + $directorthrowshandlers + return $null; // exception is ignored + } +%} ++
Alternatively an exception compatible with the existing director
+method exception specifications can be thrown. Assuming that all
+methods allow std::runtime_error to be thrown,
+the return $null;
could be changed to:
+
+ throw std::runtime_error(Swig::JavaExceptionMessage(jenv, $error).message()); ++
In more complex situations, a separate director:except
feature
+may need to be attached to specific methods.
+
Below is a complete example demonstrating the use +of the "directorthrows" typemaps. In this example, a +generic "directorthrows" typemap is appropriate for all three exceptions - all +take single string constructors. If the exceptions had different constructors, +it would be necessary to have separate typemaps for each exception type. + + + +
+%module(directors="1") example + +%{ + #include <string> + #include <stdexcept> +%} + +// Define exceptions in header section using std::runtime_error +%define DEFINE_EXCEPTION(NAME) +%{ + namespace MyNS { + struct NAME : public std::runtime_error { NAME(const std::string &what) : runtime_error(what) {} }; + } +%} +%enddef + +// Expose C++ exceptions as Java Exceptions by changing the Java base class and providing a getMessage() +%define DECLARE_EXCEPTION(NAME) +%typemap(javabase) MyNS::NAME "java.lang.Exception"; +%rename(getMessage) MyNS::NAME::what; +namespace MyNS { + struct NAME { + NAME(const std::string& what); + const char * what(); + }; +} +%enddef + +DEFINE_EXCEPTION(ExceptionA) +DEFINE_EXCEPTION(ExceptionB) +DEFINE_EXCEPTION(Unexpected) + +// Mark three methods to map director thrown exceptions. +%feature("director:except") MyClass::meth1(int); +%feature("director:except") MyClass::meth2; +%feature("director:except") meth3; + +%typemap(directorthrows) MyNS::ExceptionA, MyNS::ExceptionB, MyNS::Unexpected %{ + if (Swig::ExceptionMatches(jenv, $error, "$packagepath/$javaclassname")) + throw $1_type(Swig::JavaExceptionMessage(jenv, $error).message()); +%} + +DECLARE_EXCEPTION(ExceptionA) +DECLARE_EXCEPTION(ExceptionB) +DECLARE_EXCEPTION(Unexpected) + +%catches(MyNS::ExceptionA, MyNS::ExceptionB, MyNS::Unexpected) MyClass::meth2(); + +%inline { + class MyClass { + public: + virtual void meth1(int x) throw(MyNS::ExceptionA, MyNS::ExceptionB) = 0; + virtual void meth2() = 0; /* throws MyNS::ExceptionA, MyNS::ExceptionB, MyNS::Unexpected */ + virtual void meth3(float x) throw(MyNS::Unexpected) = 0; + virtual ~MyClass() {} + }; +} ++
+In this case the three different "directorthrows" typemaps will be used
+to generate the three different exception handlers for
+meth1
, meth2
and meth3
. The generated
+handlers will have "if" blocks for each exception type specified, in
+the exception specification or %catches
feature.
+
Note that the "directorthrows" typemaps are important
+only if it is important for the the exceptions passed through the C++
+layer to be mapped to distinct C++ exceptions. If director methods
+are being called by C++ code that is itself wrapped in a
+SWIG generated Java wrapper and access is always through this wrapper,
+the default Swig::DirectorException
class provides enough information
+to reconstruct the original exception. In this case removing the
+$directorthrowshandlers
special variable from the
+default director:except
feature and simply always
+throwing a Swig::DirectorException
will achieve the desired result.
+Along with this a generic exception feature is added to convert any
+caught Swig::DirectorException
s back into the underlying
+Java exceptions via the Swig::DirectorException::raiseJavaException
method,
+as demonstrated with %javaexception
below:
+
+%javaexception("Exception") MyClass::myMethod %{ + try { + $action + } catch (Swig::DirectorException &e) { + // raise/throw the Java exception that originally caused the DirectorException + e.raiseJavaException(jenv); + return $null; + } +%} ++
+See the Exception handling with %exception and %javaexception +section for more on converting C++ exceptions to Java exceptions. +
+ +@@ -3652,7 +4222,7 @@ class MyProtectedBase extends ProtectedBase -
@@ -3664,7 +4234,7 @@ be awkward. This section describes some common SWIG features that are used to improve the interface to existing C/C++ code.
-@@ -3730,7 +4300,7 @@ hard to implement. It is possible to improve on this using Java code, typemaps, customization features as covered in later sections, but sometimes helper functions are a quick and easy solution to difficult cases.
-@@ -3793,7 +4363,7 @@ Vector(2,3,4) in any way---the extensions only show up in the Java interface.
-@@ -3866,8 +4436,8 @@ void *malloc(size_t nbytes);
If no declaration name is given to %exception, it is applied to all wrapper functions. -The $action is a SWIG special variable and is replaced by the C/C++ function call being wrapped. -The return $null; handles all native method return types, namely those that have a void return and those that do not. +The $action is a SWIG special variable and is replaced by the C/C++ function call being wrapped. +The return $null; handles all native method return types, namely those that have a void return and those that do not. This is useful for typemaps that will be used in native method returning all return types. See the section on Java special variables for further explanation. @@ -3952,7 +4522,7 @@ to raise exceptions. See the SWIG Library ch The typemap example Handling C++ exception specifications as Java exceptions provides further exception handling capabilities.
-@@ -3978,7 +4548,7 @@ protected static void protect_me() { -
@@ -3988,7 +4558,7 @@ strings and arrays. This chapter discusses the common techniques for solving these problems.
-@@ -4162,7 +4732,7 @@ void foo(Bar *OUTPUT); will not have the intended effect since typemaps.i does not define an OUTPUT rule for Bar.
-@@ -4228,7 +4798,7 @@ System.out.println("3 + 4 = " + result); See the SWIG Library chapter for further details.
-@@ -4295,7 +4865,7 @@ Please be aware that the typemaps in this library are not efficient as all the e There is an alternative approach using the SWIG array library and this is covered in the next section.
-@@ -4440,7 +5010,7 @@ well suited for applications in which you need to create buffers, package binary data, etc.
-@@ -4484,7 +5054,7 @@ len: 5 data: 68 69 0 6a 6b -
@@ -4601,7 +5171,7 @@ model and use these functions in place of malloc and free in your own code.
-@@ -4622,7 +5192,7 @@ Before proceeding, it should be stressed that typemaps are not a required part of using SWIG---the default wrapping behavior is enough in most cases. Typemaps are only used if you want to change some aspect of the generated code. -
@@ -4774,7 +5344,7 @@ However, the mappings allow the full range of values for each C type from Java.
-@@ -4789,7 +5359,7 @@ So in summary, the C/C++ pointer to non-primitive types is cast into the 64 bit The Java type is either the proxy class or type wrapper class.
-@@ -4802,7 +5372,7 @@ Unfortunately it won't of course hold true for JNI code.
-@@ -4925,7 +5495,7 @@ int c = example.count('e',"Hello World"); -
@@ -5183,9 +5753,18 @@ These are listed below:
@@ -5231,7 +5810,7 @@ The "javain" typemap has the optional 'pre', 'post' and 'pgcppname' attributes. Note that when the 'pre' or 'post' attributes are specified and the associated type is used in a constructor, a constructor helper function is generated. This is necessary as the Java proxy constructor wrapper makes a call to a support constructor using a this call. In Java the this call must be the first statement in the constructor body. The constructor body thus calls the helper function and the helper function instead makes the JNI call, ensuring the 'pre' code is called before the JNI call is made. There is a Date marshalling example showing 'pre', 'post' and 'pgcppname' attributes in action.
-@@ -5252,6 +5831,8 @@ For example, $javaclassname is replaced by the proxy classname Foo< expands to the proxy classname when wrapping Foo *&. If the type does not have an associated proxy class, it expands to the type wrapper class name, for example, SWIGTYPE_p_unsigned_short is generated when wrapping unsigned short *. +The class name is fully qualified with the package name when using the +nspace feature.
@@ -5263,7 +5844,7 @@ This special variable is usually used for making calls to a function in the inte
-$null
+$null
Used in input typemaps to return early from JNI functions that have either void or a non-void return type. Example:
-$jniinput, $javacall and $packagepath
+$error, $jniinput, $javacall and $packagepath
These special variables are used in the directors typemaps. See Director specific typemaps for details.
+$javainterfacename
+This special variable is only expanded when the interface feature is applied to a class.
+It works much like $javaclassname, but instead of expanding to the proxy classname,
+it expands to the value in the name attribute in the interface feature.
+For example:
+
+%feature("interface", name="MyInterface") MyClass; +%typemap(jstype) MyClass "$&javainterfacename" +%typemap(jstype) MyClass * "$javainterfacename" +
+will result in the jstype typemap expanding to MyInterface for both +MyClass and MyClass *. +The interface name is fully qualified with the package name when using the +nspace feature. +
+ +
+$interfacename
+This special variable is only expanded when the interface feature is applied to a class.
+It expands to just the interface name and is thus different to $javainterfacename
+in that it is not fully qualified with the package name when using the
+nspace feature.
+
@@ -5419,7 +6029,7 @@ If you do not intend your code to be targeting both C and C++ then your typemaps
-@@ -5515,9 +6125,39 @@ Below shows an example modifying the finalizer, assuming the delete met +
%typemap(javainterfacecode, declaration="...", cptrmethod="...")
++The code in this typemap is added to the body of a Java proxy class but only when a class is +marked with the interface feature. +The typemap is used in the proxy class marked with the interface feature as well as all proxy classes derived from the marked C++ class, +as they are all generated as implementing the Java interface. +The default typemap used in the %interface family of macros mentioned in +the Java interfaces section, +where CTYPE is the C++ class macro argument, +is as follows: +
+ ++%typemap(javainterfacecode, + declaration=" long $interfacename_GetInterfaceCPtr();\n", + cptrmethod="$interfacename_GetInterfaceCPtr") CTYPE %{ + public long $interfacename_GetInterfaceCPtr() { + return $imclassname.$javaclazzname$interfacename_GetInterfaceCPtr(swigCPtr); + } +%} +
+The special variable $interfacename is expanded into the +name specified in the interface feature. +
+Compatibility Note: In SWIG-1.3.21 and earlier releases, typemaps called "javagetcptr" and "javaptrconstructormodifiers" were available. These are deprecated and the "javabody" typemap can be used instead. +The javainterfacecode typemap and interface feature was introduced in SWIG-3.0.9.
@@ -5533,6 +6173,7 @@ In summary the contents of the typemaps make up a proxy class like this: [ javafinalize typemap ] public synchronized void delete() [ javadestruct OR javadestruct_derived typemap ] [ javacode typemap ] +[ javainterfacecode typemap] ... proxy functions ... } @@ -5543,6 +6184,11 @@ Note the delete() methodname and method modifiers are configurab
+The javainterfacecode typemap is only used when bases are marked by the interface +feature and the implements list will also then be expanded to include these Java interfaces. +
+ +The type wrapper class is similar in construction:
@@ -5574,8 +6220,23 @@ The type wrapper class is similar in construction: The "javaimports" typemap is ignored if the enum class is wrapped by an inner Java class, that is when wrapping an enum declared within a C++ class. +The Java interface turned on by the interface feature is fairly simple:
++[ javaimports typemap ] +public interface [ javainterfacename ] { +[ javainterfacecode:cptrmethod typemap attribute ] +... interface declarations ... +} ++
-The defaults can be overridden to tailor these classes. +where javainterfacename is the name attribute in the interface feature. +
+ ++The defaults can be overridden to tailor the generated classes. Here is an example which will change the getCPtr method and constructor from the default public access to protected access. If the classes in one package are not using the classes in another package, then these methods need not be public and removing access to these low level implementation details, is a good thing. If you are invoking SWIG more than once and generating the wrapped classes into different packages in each invocation, then you cannot do this as you will then have different packages. @@ -5584,8 +6245,8 @@ If you are invoking SWIG more than once and generating the wrapped classes into
%typemap(javabody) SWIGTYPE %{ - private long swigCPtr; - protected boolean swigCMemOwn; + private transient long swigCPtr; + protected transient boolean swigCMemOwn; protected $javaclassname(long cPtr, boolean cMemoryOwn) { swigCMemOwn = cMemoryOwn; @@ -5613,7 +6274,7 @@ For the typemap to be used in all type wrapper classes, all the different types-%typemap(javabody) SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) %{ - private long swigCPtr; + private transient long swigCPtr; protected $javaclassname(long cPtr, boolean bFutureUse) { swigCPtr = cPtr; @@ -5635,7 +6296,7 @@ Again this is the same that is in "java.swg", barring the method modifi-When using multiple modules or the nspace feature it is common to invoke SWIG with a different -package +When using multiple modules or the nspace feature it is common to invoke SWIG with a different -package command line option for each module. However, by default the generated code may not compile if generated classes in one package use generated classes in another package. @@ -5657,7 +6318,7 @@ to make the method and constructor public:
24.9.10 Director specific typemaps
+25.9.10 Director specific typemaps
@@ -5701,6 +6362,10 @@ is the package name passed from the SWIG command line and
$javaclassname If the -package commandline option is not used to specify the package, then '$packagepath/' will be removed from the resulting output JNI field descriptor. Do not forget the terminating ';' for JNI field descriptors starting with 'L'. If the ';' is left out, Java will generate a "method not found" runtime error. +Note that the
$packagepath
substitution always uses the path separator '/' when expanded. +The$javaclassname
expansion can be confusing as it is normally expanded using the '.' separator. +However,$javaclassname
is expanded using the path separator '/' in typemap's "descriptor" attribute +as well as in the "directorthrows" typemap.
%typemap(directorthrows)
+
+Conversion of Java exceptions to C++ exceptions in director method's exception handling.
+This typemap is expected to test the $error special variable for a matching Java exception
+and if successful convert and throw it into a C++ exception given by the typemap's type.
+The $error
special variable is of type jthrowable
and is
+substituted with a unique variable name in the generated code.
+
+The example below converts a Java java.lang.IndexOutOfBoundsException
exception
+to the typemap's type, that is std::out_of_range
:
+
+%typemap(directorthrows) std::out_of_range %{ + if (Swig::ExceptionMatches(jenv, $error, "java/lang/IndexOutOfBoundsException")) { + throw std::out_of_range(Swig::JavaExceptionMessage(jenv, $error).message()); + } +%} ++
+The utility function Swig::ExceptionMatches
+and class Swig::JavaExceptionMessage
are helpers available when using directors and are described
+in the Java Exceptions from Directors section.
+
%typemap(javapackage)
@@ -5893,7 +6592,7 @@ the SWIG library.
-@@ -5972,7 +6671,7 @@ This would be done by using the original versions of these typemaps in "enums.sw
-@@ -6097,7 +6796,7 @@ We could alternatively have used %rename to rename what() into
-@@ -6252,7 +6951,7 @@ If we were a martyr to the JNI cause, we could replace the succinct code within If we had, we would have put it in the "in" typemap which, like all JNI and Java typemaps, also supports the 'throws' attribute.
-@@ -6396,7 +7095,7 @@ Lastly the "jni", "jtype" and "jstype" typemaps are also required to specify what Java types to use.
-@@ -6478,7 +7177,7 @@ example.foo(new String[]{"red", "green", "blue", "white"}); -
@@ -6524,7 +7223,7 @@ int spam(double a, double b, double *out1, double *out2) { *out1 = a*10.0; *out2 = b*100.0; return status; -}; +} %} /* @@ -6596,7 +7295,7 @@ $ java runme 1 12.0 340.0 -
@@ -6802,7 +7501,7 @@ SWIG usually generates code which constructs the proxy classes using Java code a Note that the JNI code above uses a number of string lookups to call a constructor, whereas this would not occur using byte compiled Java code.
-@@ -6846,7 +7545,7 @@ System.out.println("foo1? " + foo1.equals(foo2)); -
@@ -6905,7 +7604,7 @@ This example contains some useful functionality which you may want in your code.
@@ -7085,7 +7784,7 @@ The C functional interface has been completely morphed into an object-oriented i the Butler class would behave much like any pure Java class and feel more natural to Java users.
-@@ -7208,7 +7907,7 @@ public class Bike { Note the addReference call.
-@@ -7324,7 +8023,7 @@ The 'javacode' typemap simply adds in the specified code into the Java proxy cla -
@@ -7501,7 +8200,7 @@ A few things to note: -
@@ -7682,10 +8381,10 @@ public abstract class UserVisibleFoo extends Foo {
@@ -7741,7 +8440,7 @@ public class Barmy { -
@@ -7802,7 +8501,7 @@ All destructors have to be called manually for example the delete_Foo(foo)
-@@ -7852,7 +8551,7 @@ This directive is only really useful if you want to mix your own hand crafted JN
-@@ -7873,7 +8572,7 @@ However, you will have to be careful about memory management and make sure that This method normally calls the C++ destructor or free() for C code.
-@@ -7886,7 +8585,7 @@ where it is possible to step from Java code into a JNI method within one environ
Alternatively, debugging can involve placing debug printout statements in the JNI layer using the %exception directive. See the special variables for %exception section. -Many of the default typemaps can also be overidden and modified for adding in extra logging/debug display information. +Many of the default typemaps can also be overridden and modified for adding in extra logging/debug display information.
@@ -7895,7 +8594,7 @@ The -verbose:jni and -verbose:gc are also useful options for monitoring code beh
-diff --git a/Doc/Manual/Javascript.html b/Doc/Manual/Javascript.html new file mode 100644 index 0000000..16f6748 --- /dev/null +++ b/Doc/Manual/Javascript.html @@ -0,0 +1,999 @@ + + +
+ +This chapter describes SWIG's support of Javascript. It does not cover SWIG basics, but only information that is specific to this module.
+ +Javascript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions. Its arguably the most popular language for web development. +Javascript has gone beyond being a browser-based scripting language and with node.js, it is also used as a backend development language.
+Native Javascript extensions can be used for applications that embed a web-browser view or that embed a Javascript engine (such as node.js). Extending a general purpose web-browser is not possible as this would be a severe security issue.
+SWIG Javascript currently supports JavascriptCore, the Javascript engine used by Safari/Webkit
, and v8, which is used by Chromium
and node.js
.
WebKit is a modern browser implementation available as open-source which can be embedded into an application.
+With node-webkit there is a platform which uses Google's Chromium
as Web-Browser widget and node.js
for javascript extensions.
+
Suppose that you defined a SWIG module such as the following:
++%module example +%{ +#include "example.h" +%} +int gcd(int x, int y); +extern double Foo;+
To build a Javascript module, run SWIG using the -javascript
option and a desired target engine -jsc
, -v8
, or -node
. The generator for node
is essentially delegating to the v8
generator and adds some necessary preprocessor definitions.
+$ swig -javascript -jsc example.i+
If building a C++ extension, add the -c++ option:
++$ swig -c++ -javascript -jsc example.i+
The V8 code that SWIG generates should work with most versions from 3.11.10 up to 3.29.14 and later.
+The API headers for V8 >= 4.3.0 define constants which SWIG can use to +determine the V8 version it is compiling for. For versions < 4.3.0, you +need to specify the V8 version when running SWIG. This is specified as a hex +constant, but the constant is read as pairs of decimal digits, so for V8 +3.25.30 use constant 0x032530. This scheme can't represent components > 99, +but this constant is only useful for V8 < 4.3.0, and no V8 versions from +that era had a component > 99. For example:
++$ swig -c++ -javascript -v8 -DV8_VERSION=0x032530 example.i+
If you're targetting V8 >= 4.3.0, you would just run swig like so:
++$ swig -c++ -javascript -v8 example.i+
This creates a C/C++ source file example_wrap.c
or example_wrap.cxx
. The generated C source file contains the low-level wrappers that need to be compiled and linked with the rest of your C/C++ application to create an extension module.
The name of the wrapper file is derived from the name of the input file. For example, if the input file is example.i
, the name of the wrapper file is example_wrap.c
. To change this, you can use the -o option. The wrapped module will export one function which must be called to register the module with the Javascript interpreter. For example, if your module is named example
the corresponding initializer for JavascriptCore would be
+bool example_initialize(JSGlobalContextRef context, JSObjectRef *exports)+
and for v8:
++void example_initialize(v8::Handle<v8::Object> exports)+
+Note: be aware that v8
has a C++ API, and thus, the generated modules must be compiled as C++.
+
The configuration for tests and examples currently supports Linux and Mac only and not MinGW (Windows) yet.
+The default interpreter is node.js
as it is available on all platforms and convenient to use.
Running the examples with JavascriptCore requires libjavascriptcoregtk-1.0
to be installed, e.g., under Ubuntu with
+$ sudo apt-get install libjavascriptcoregtk-1.0-dev+
Running with V8
requires libv8
:
+$ sudo apt-get install libv8-dev+
Examples can be run using
++$ make check-javascript-examples ENGINE=jsc+
ENGINE
can be node
, jsc
, or v8
.
The test-suite can be run using
++$ make check-javascript-test-suite ENGINE=jsc+
You can specify a specific V8
version for running the examples and tests
+$ make check-javascript-examples V8_VERSION=0x032530 ENGINE=v8+
At the moment, the Javascript generators pass all tests syntactically, i.e., the generated source code compiles. However, there are still remaining runtime issues.
+ +Default optional arguments do not work for all targeted interpreters
Multiple output arguments do not work for JSC
C89 incompatibily: the JSC generator might still generate C89 violating code
long long
is not supported
%native
is not supported
Javascript callbacks are not supported
instanceOf
does not work under JSC
The primary development environment has been Linux (Ubuntu 12.04). Windows and Mac OS X have been tested sporadically. Therefore, the generators might have more issues on those platforms. Please report back any problem you observe to help us improving this module quickly.
+ +This chapter gives a short introduction how to use a native Javascript extension: as a node.js
module, and as an extension for an embedded Webkit.
To install node.js
you can download an installer from their web-site for Mac OS X and Windows. For Linux you can either build the source yourself and run sudo checkinstall
or keep to the (probably stone-age) packaged version. For Ubuntu there is a PPA available.
+$ sudo add-apt-repository ppa:chris-lea/node.js +$ sudo apt-get update +$ sudo apt-get install nodejs+
As v8
is written in C++ and comes as a C++ library it is crucial to compile your module using the same compiler flags as used for building v8. To make things easier, node.js
provides a build tool called node-gyp
.
You have to install it using npm
:
+$ sudo npm install -g node-gyp+
node-gyp
expects a configuration file named binding.gyp
which is basically in JSON format and conforms to the same format that is used with Google's build-tool gyp
.
binding.gyp
:
+{ + "targets": [ + { + "target_name": "example", + "sources": [ "example.cxx", "example_wrap.cxx" ] + } + ] +}+
First create the wrapper using SWIG:
++$ swig -javascript -node -c++ example.i+
Then run node-gyp build
to actually create the module:
+$ node-gyp build+
This will create a build
folder containing the native module. To use the extension you need to 'require' it in your Javascript source file:
+require("./build/Release/example")+
A more detailed explanation is given in the Examples section.
+ +This error happens when gyp
is installed as a distribution package. It seems to be outdated. Removing it resolves the problem.
+$ sudo apt-get remove gyp+
Webkit is pre-installed on Mac OS X and available as a library for GTK.
+ +There is general information about programming with WebKit on Apple Developer Documentation. Details about Cocoa
programming are not covered here.
An integration of a native extension 'example' would look like this:
++#import "appDelegate.h" + +extern bool example_initialize(JSGlobalContextRef context, JSObjectRef* exports); + + +@implementation ExampleAppDelegate + +@synthesize webView; + +- (void)addGlobalObject:(JSContextRef) context:(NSString *)objectName:(JSObjectRef) theObject { + JSObjectRef global = JSContextGetGlobalObject(context); + JSStringRef objectJSName = JSStringCreateWithCFString( (CFStringRef) objectName ) + if ( objectJSName != NULL ) { + JSObjectSetProperty(context, global, objectJSName, theObject, kJSPropertyAttributeReadOnly, NULL); + JSStringRelease( objectJSName ); + } +} + +- (void)applicationDidFinishLaunching:(NSNotification *)aNotification { + + // Start a webview with the bundled index.html file + NSString *path = [[NSBundle mainBundle] bundlePath]; + NSString *url = [NSString stringWithFormat: @"file://%@/Contents/Assets/index.html", path]; + + WebFrame *webframe = [webView mainFrame]; + JSGlobalContextRef context = [webframe globalContext]; + + JSObjectRef example; + example_initialize(context, &example); + [self addGlobalObject:context:@"example":example] + + JSObjectSetProperty(context, global, JSStringRef propertyName, example, JSPropertyAttributes attributes, NULL); + + [ [webView mainFrame] loadRequest: + [NSURLRequest requestWithURL: [NSURL URLWithString:url] ] + ]; +} + +@end+
There is general information about programming GTK at GTK documentation and in the GTK tutorial, and for Webkit there is a Webkit GTK+ API Reference.
+An integration of a native extension 'example' would look like this:
++#include <gtk/gtk.h> +#include <webkit/webkit.h> + +extern bool example_initialize(JSGlobalContextRef context); + +int main(int argc, char* argv[]) +{ + // Initialize GTK+ + gtk_init(&argc, &argv); + + ... + + // Create a browser instance + WebKitWebView *webView = WEBKIT_WEB_VIEW(webkit_web_view_new()); + WebFrame *webframe = webkit_web_view_get_main_frame(webView); + JSGlobalContextRef context = webkit_web_frame_get_global_context(webFrame); + JSObjectRef global = JSContextGetGlobalObject(context); + + JSObjectRef exampleModule; + example_initialize(context, &exampleModule); + JSStringRef jsName = JSStringCreateWithUTF8CString("example"); + JSObjectSetProperty(context, global, jsName, exampleModule, kJSPropertyAttributeReadOnly, NULL); + JSStringRelease(jsName); + + ... + + // Load a web page into the browser instance + webkit_web_view_load_uri(webView, "http://www.webkitgtk.org/"); + + ... + + // Run the main GTK+ event loop + gtk_main(); + + return 0; +}+
To get started with node-webkit
there is a very informative set of wiki pages.
Similar to node.js
, node-webkit
is started from command line within a node.js
project directory.
+Native extensions are created in the very same way as for node.js
, except that a customized gyp
derivate has to be used: nw-gyp.
+
+A simple example would have the following structure: +
+ ++- package.json +- app.html +- app.js +- node_modules + / example + ... (as known from node.js) ++
+The configuration file essentially conforms to node.js
syntax.
+It has some extras to configure node-webkit
. See the Manifest specification for more details.
+
+package.json
:
+
+{ + "name": "example", + "main": "app.html", + "window": { + "show": true, + "width": 800, + "height": 600 + } +}+
+The 'main'
property of package.json
specifies a web-page to be rendered in
+the main window.
+app.html
:
+
+<html> + <head> + <script src="app.js"></script> + </head> + <body> + <div> + The greatest common divisor of + <span id="x"></span> and + <span id="y"></span> is + <span id="z"></span>. + </div> + </body> +</html>+
+As known from node.js
one can use require
to load javascript modules.
+Additionally, node-webkit
provides an API that allows to manipulate the window's menu,
+open new windows, and many more things.
+
+app.js
:
+
window.onload = function() { + var example = require("example"); + var x = 18; + var y = 24; + var z = example.gcd(x,y); + document.querySelector('#x').innerHTML = x; + document.querySelector('#y').innerHTML = y; + document.querySelector('#z').innerHTML = z; +};+
Some basic examples are shown here in more detail.
+ +The common example simple
looks like this:
+/* File : example.i */ +%module example + +%inline %{ +extern int gcd(int x, int y); +extern double Foo; +%}+
To make this available as a node extension a binding.gyp
has to be created:
+{ + "targets": [ + { + "target_name": "example", + "sources": [ "example.cxx", "example_wrap.cxx" ] + } + ] +}+
Then node-gyp
is used to build the extension:
+$ node-gyp configure build+
From a 'nodejs` application the extension would be used like this:
++// import the extension via require +var example = require("./build/Release/example"); + +// calling the global method +var x = 42; +var y = 105; +var g = example.gcd(x,y); + +// Accessing the global variable +var f = example.Foo; +example.Foo = 3.1415926;+
First the module example
is loaded from the previously built extension. Global methods and variables are available in the scope of the module.
Note: ECMAScript 5, the currently implemented Javascript standard, does not have modules. node.js
and other implementations provide this mechanism defined by the CommonJS group. For browsers this is provided by Browserify, for instance.
The common example class
defines three classes, Shape
, Circle
, and Square
:
+class Shape { +public: + Shape() { + nshapes++; + } + virtual ~Shape() { + nshapes--; + } + double x, y; + void move(double dx, double dy); + virtual double area(void) = 0; + virtual double perimeter(void) = 0; + static int nshapes; +}; + +class Circle : public Shape { +private: + double radius; +public: + Circle(double r) : radius(r) { } + virtual double area(void); + virtual double perimeter(void); +}; + +class Square : public Shape { +private: + double width; +public: + Square(double w) : width(w) { } + virtual double area(void); + virtual double perimeter(void); +};+
Circle
and Square
inherit from Shape
. Shape
has a static variable nshapes
, a function move
that can't be overridden (non-virtual), and two abstract functions area
and perimeter
(pure virtual) that must be overridden by the sub-classes.
A nodejs
extension is built the same way as for the simple
example.
In Javascript it can be used as follows:
++var example = require("./build/Release/example"); + +// local aliases for convenience +var Shape = example.Shape; +var Circle = example.Circle; +var Square = example.Square; + +// creating new instances using the 'new' operator +var c = new Circle(10); +var s = new Square(10); + +// accessing a static member +Shape.nshapes; + +// accessing member variables +c.x = 20; +c.y = 30; +s.x = -10; +s.y = 5; + +// calling some methods +c.area(); +c.perimeter(); +s.area(); +s.perimeter(); + +// instantiation of Shape is not permitted +new Shape();+
Running these commands in an interactive node shell results in the following output:
++$ node -i +& var example = require("./build/Release/example"); +undefined +& var Shape = example.Shape; +undefined +& var Circle = example.Circle; +undefined +& var Square = example.Square; +undefined +& var c = new Circle(10); +undefined +& var s = new Square(10); +undefined +& Shape.nshapes; +2 +& c.x = 20; +20 +& c.y = 30; +30 +& s.x = -10; +-10 +& s.y = 5; +5 +& c.area(); +314.1592653589793 +& c.perimeter(); +62.83185307179586 +& s.area(); +100 +& s.perimeter(); +40 +& c.move(40, 40) +undefined +& c.x +60 +& c.y +70 +& new Shape() +Error: Class Shape can not be instantiated +at repl:1:2 +at REPLServer.self.eval (repl.js:110:21) +at Interface.<anonymous> (repl.js:239:12) +at Interface.EventEmitter.emit (events.js:95:17) +at Interface._onLine (readline.js:202:10) +at Interface._line (readline.js:531:8) +at Interface._ttyWrite (readline.js:760:14) +at ReadStream.onkeypress (readline.js:99:10) +at ReadStream.EventEmitter.emit (events.js:98:17) +at emitKey (readline.js:1095:12)+
+Note: In ECMAScript 5 there is no concept for classes. Instead each function can be used as a constructor function which is executed by the 'new' operator. Furthermore, during construction the key property prototype
of the constructor function is used to attach a prototype instance to the created object. A prototype is essentially an object itself that is the first-class delegate of a class used whenever the access to a property of an object fails. The very same prototype instance is shared among all instances of one type. Prototypal inheritance is explained in more detail on in Inheritance and the prototype chain, for instance.
+
The Javascript Module implementation has taken a very different approach compared to other language modules in order to support different Javascript interpreters.
+ +The Javascript module is implemented in Source/Modules/javascript.cxx
. It dispatches the code generation to a JSEmitter
instance, V8Emitter
or JSCEmitter
. Additionally there are some helpers: Template
, for templated code generation, and JSEmitterState
, which is used to manage state information during AST traversal. This rough map shall make it easier to find a way through this huge source file:
+// module wide defines + +#define NAME "name" +... + +// ############################### +// # Helper class declarations + +class JSEmitterState { ... }; + +class Template { ... }; + +// ############################### +// # JSEmitter declaration + +class JSEmitter { ... }; + +// Emitter factory declarations + +JSEmitter *swig_javascript_create_JSCEmitter(); +JSEmitter *swig_javascript_create_V8Emitter(); + +// ############################### +// # Javascript module + +// Javascript module declaration + +class JAVASCRIPT:public Language { ... }; + +// Javascript module implementation + +int JAVASCRIPT::functionWrapper(Node *n) { ... } +... + +// Module factory implementation + +static Language *new_swig_javascript() { ... } + +extern "C" Language *swig_javascript(void) { ... } + +// ############################### +// # JSEmitter base implementation + +JSEmitter::JSEmitter() { ... } + +Template JSEmitter::getTemplate(const String *name) { ... } +... + +// ############################### +// # JSCEmitter + +// JSCEmitter declaration + +class JSCEmitter: public JSEmitter { ... }; + +// JSCEmitter implementation + +JSCEmitter::JSCEmitter() { ... } + +void JSCEmitter::marshalInputArgs(Node *n, ParmList *parms, Wrapper *wrapper, MarshallingMode mode, bool is_member, bool is_static) { ... } +... + +// JSCEmitter factory + +JSEmitter *swig_javascript_create_JSCEmitter() { ... } + + +// ############################### +// # V8Emitter + +// V8Emitter declaration + +class V8Emitter: public JSEmitter { ... }; + +// V8Emitter implementation + +V8Emitter::V8Emitter() { ... } + +int V8Emitter::initialize(Node *n) { ... } + +// V8Emitter factory + +JSEmitter *swig_javascript_create_V8Emitter() { ... } + + +// ############################### +// # Helper implementation (JSEmitterState, Template) + +JSEmitterState::JSEmitterState() { ... } +... + +Template::Template(const String *code_) { ... } +...+
All generated code is created on the basis of code templates. The templates for JavascriptCore can be found in Lib/javascript/jsc/javascriptcode.swg
, for v8 in Lib/javascript/v8/javascriptcode.swg
.
To track the originating code template for generated code you can run
++$ swig -javascript -jsc -debug-codetemplates+
which wraps generated code with a descriptive comment
++/* begin fragment("template_name") */ + +...generated code ... + +/* end fragment("template_name") */+
The Template class is used like this:
++Template t_register = getTemplate("jsv8_register_static_variable"); +t_register.replace("$jsparent", state.clazz(NAME_MANGLED)) + .replace("$jsname", state.variable(NAME)) + .replace("$jsgetter", state.variable(GETTER)) + .replace("$jssetter", state.variable(SETTER)) + .trim(). + print(f_init_static_wrappers);+
A code template is registered with the JSEmitter via fragment(name, "template")
, e.g.,
+%fragment ("jsc_variable_declaration", "templates") +%{ + {"$jsname", $jsgetter, $jssetter, kJSPropertyAttributeNone}, +%}+
Template
creates a copy of that string and Template::replace
uses Swig's Replaceall
to replace variables in the template. Template::trim
can be used to eliminate leading and trailing whitespaces. Template::print
is used to write the final template string to a Swig DOH
(based on Printv
). All methods allow chaining.
The Javascript module delegates code generation to a JSEmitter
instance. The following extract shows the essential interface:
+class JSEmitter { + ... + + /** + * Opens output files and temporary output DOHs. + */ + virtual int initialize(Node *n); + + /** + * Writes all collected code into the output file(s). + */ + virtual int dump(Node *n) = 0; + + /** + * Cleans up all open output DOHs. + */ + virtual int close() = 0; + + ... + + /** + * Invoked at the beginning of the classHandler. + */ + virtual int enterClass(Node *); + + /** + * Invoked at the end of the classHandler. + */ + virtual int exitClass(Node *) { + return SWIG_OK; + } + + /** + * Invoked at the beginning of the variableHandler. + */ + virtual int enterVariable(Node *); + + /** + * Invoked at the end of the variableHandler. + */ + virtual int exitVariable(Node *) { + return SWIG_OK; + } + + /** + * Invoked at the beginning of the functionHandler. + */ + virtual int enterFunction(Node *); + + /** + * Invoked at the end of the functionHandler. + */ + virtual int exitFunction(Node *) { + return SWIG_OK; + } + + /** + * Invoked by functionWrapper callback after call to Language::functionWrapper. + */ + virtual int emitWrapperFunction(Node *n); + + /** + * Invoked from constantWrapper after call to Language::constantWrapper. + **/ + virtual int emitConstant(Node *n); + + /** + * Registers a given code snippet for a given key name. + * + * This method is called by the fragmentDirective handler + * of the JAVASCRIPT language module. + **/ + int registerTemplate(const String *name, const String *code); + + /** + * Retrieve the code template registered for a given name. + */ + Template getTemplate(const String *name); + + State &getState(); + + ... + +}+
The module calls initialize
, dump
, and close
from within the top
method:
+int JAVASCRIPT::top(Node *n) { + emitter->initialize(n); + + Language::top(n); + + emitter->dump(n); + emitter->close(); + + return SWIG_OK; +}+
The methods enterClass
and exitClass
are called from within the classHandler
method:
+int JAVASCRIPT::classHandler(Node *n) { + + emitter->enterClass(n); + Language::classHandler(n); + emitter->exitClass(n); + + return SWIG_OK; +}+
In enterClass
the emitter stores state information that is necessary when processing class members. In exitClass
the wrapper code for the whole class is generated.
For storing information during the AST traversal the emitter provides a JSEmitterState
with different slots to store data representing the scopes global, class, function, and variable.
+class JSEmitterState { + +public: + + JSEmitterState(); + + ~JSEmitterState(); + + DOH *global(); + + DOH *global(const char* key, DOH *initial = 0); + + DOH *clazz(bool reset = false); + + DOH *clazz(const char* key, DOH *initial = 0); + + DOH *function(bool reset = false); + + DOH *function(const char* key, DOH *initial = 0); + + DOH *variable(bool reset = false); + + DOH *variable(const char* key, DOH *initial = 0); + + static int IsSet(DOH *val); + + ... +};+
When entering a scope, such as in enterClass
, the corresponding state is reset and new data is stored:
+state.clazz(RESET); +state.clazz(NAME, Getattr(n, "sym:name"));+
State information can be retrieved using state.clazz(NAME)
or with Getattr
on state.clazz()
which actually returns a Hash
instance.
Applications with an embedded JavascriptCore should be able to present detailed exception messages that occur in the Javascript engine. Below is an example derived from code provided by Brian Barnes on how these exception details can be extracted.
++void script_exception_to_string(JSContextRef js_context,JSValueRef exception_value_ref,char* return_error_string, int return_error_string_max_length) +{ + JSObjectRef exception_object; + JSValueRef value_ref; + JSStringRef jsstring_property_name = NULL; + JSValueRef temporary_exception = NULL; + JSStringRef js_return_string = NULL; + size_t bytes_needed; + char* c_result_string = NULL; + exception_object = JSValueToObject(js_context, exception_value_ref, NULL); + + /* source url */ + strcpy(return_error_string,"["); + jsstring_property_name = JSStringCreateWithUTF8CString("sourceURL"); + value_ref = JSObjectGetProperty(js_context, exception_object, jsstring_property_name, &temporary_exception); + JSStringRelease(jsstring_property_name); + js_return_string = JSValueToStringCopy(js_context, value_ref, NULL); + bytes_needed = JSStringGetMaximumUTF8CStringSize(js_return_string); + c_result_string = (char*)calloc(bytes_needed, sizeof(char)); + JSStringGetUTF8CString(js_return_string, c_result_string, bytes_needed); + JSStringRelease(js_return_string); + strncat(return_error_string, c_result_string, return_error_string_max_length-1); + free(c_result_string); + + strncat(return_error_string, ":", return_error_string_max_length-1); + + /* line number */ + + jsstring_property_name = JSStringCreateWithUTF8CString("line"); + value_ref = JSObjectGetProperty(js_context, exception_object, jsstring_property_name, &temporary_exception); + JSStringRelease(jsstring_property_name); + js_return_string = JSValueToStringCopy(js_context, value_ref, NULL); + bytes_needed = JSStringGetMaximumUTF8CStringSize(js_return_string); + c_result_string = (char*)calloc(bytes_needed, sizeof(char)); + JSStringGetUTF8CString(js_return_string, c_result_string, bytes_needed); + JSStringRelease(js_return_string); + strncat(return_error_string, c_result_string, return_error_string_max_length-1); + free(c_result_string); + + strncat(return_error_string, "]", return_error_string_max_length-1); + + /* error message */ + + jsstring_property_name = JSStringCreateWithUTF8CString("message"); + value_ref = JSObjectGetProperty(js_context, exception_object, jsstring_property_name, &temporary_exception); + JSStringRelease(jsstring_property_name); + if(NULL == value_ref) + { + strncat(return_error_string, "Unknown Error", return_error_string_max_length-1); + } + else + { + js_return_string = JSValueToStringCopy(js_context, value_ref, NULL); + bytes_needed = JSStringGetMaximumUTF8CStringSize(js_return_string); + c_result_string = (char*)calloc(bytes_needed, sizeof(char)); + JSStringGetUTF8CString(js_return_string, c_result_string, bytes_needed); + JSStringRelease(js_return_string); + strncat(return_error_string, c_result_string, return_error_string_max_length-1); + free(c_result_string); + } +}+
It would be used in the following way:
++if(js_exception) +{ + char return_error_string[256]; + script_exception_to_string(js_context, js_exception, return_error_string, 256); + printf("Compile error is %s", return_error_string); +}+
@@ -90,7 +92,7 @@ Set the environment variable to hold an alternative library directory. The directories that are searched are displayed when using -verbose commandline option.
-@@ -102,7 +104,7 @@ pointers as class-like objects. Since these functions provide direct access to memory, their use is potentially unsafe and you should exercise caution.
-@@ -318,7 +320,7 @@ In this example, the function int_to_uint() would be used to cast type Note: When working with simple pointers, typemaps can often be used to provide more seamless operation.
-@@ -496,7 +498,7 @@ you should consider using a special array object rather than a bare pointer. used with types of char or char *.
-@@ -657,7 +659,7 @@ Now, in a script:
@@ -759,7 +761,7 @@ char *cdata_name(type* ptr, int nitems) Clearly they are unsafe.
-@@ -779,7 +781,7 @@ morality. The modules in this section provide basic functionality for manipulating raw C strings.
-@@ -820,7 +822,7 @@ interpreter and lead to a crash). Furthermore, the default behavior does not work well with binary data. Instead, strings are assumed to be NULL-terminated.
-@@ -862,7 +864,7 @@ In the wrapper function, the passed string will be expanded to a pointer and len The (char *STRING, int LENGTH) multi-argument typemap is also available in addition to (char *STRING, size_t LENGTH).
-@@ -903,7 +905,7 @@ however, you may need to provide your own "newfree" typemap for other types. See Object ownership and %newobject for more details.
-@@ -1363,7 +1365,7 @@ structure or class instead. -
@@ -1383,6 +1385,7 @@ The following table shows which C++ classes are supported and the equivalent SWI
@@ -1484,7 +1488,7 @@ void foo(string s, const String &t); // std_string typemaps still applie -
@@ -1663,7 +1667,7 @@ if you want to make their head explode. details and the public API exposed to the interpreter vary.
-@@ -1713,13 +1717,28 @@ The %exception directive can be used by placing the following code befo Any thrown STL exceptions will then be gracefully handled instead of causing a crash.
--Some target languages have support for handling the widely used boost::shared_ptr smart pointer. -This smart pointer is also available as std::tr1::shared_ptr before it becomes fully standardized as std::shared_ptr. -The boost_shared_ptr.i library provides support for boost::shared_ptr and std_shared_ptr.i provides support for std::shared_ptr, but if the following macro is defined as shown, it can be used for std::tr1::shared_ptr: +Some target languages have support for handling the shared_ptr reference counted smart pointer. +This smart pointer is available in the standard C++11 library as std::shared_ptr. +It was also in TR1 as std::tr1::shared_ptr before it was fully standardized. +Support for the widely used boost::shared_ptr is also available. +
+ ++In order to use std::shared_ptr, the std_shared_ptr.i library file should be included: +
+ ++%include <std_shared_ptr.i> ++
+The pre-standard std::tr1::shared_ptr can be used by including the following macro before including the std_shared_ptr.i library file:
+In order to use boost::shared_ptr, the boost_shared_ptr.i library file should be included: +
+ ++%include <boost_shared_ptr.i> ++
You can only use one of these variants of shared_ptr in your interface file at a time. and all three variants must be used in conjunction with the %shared_ptr(T) macro, where T is the underlying pointer type equating to usage shared_ptr<T>. @@ -1872,12 +1901,66 @@ Adding the missing %shared_ptr macros will fix this: -Note: There is currently no support for %shared_ptr and the director feature. +
+Note: There is somewhat limited support for %shared_ptr and the director feature +and the degress of success varies among the different target languages. +Please help to improve this support by providing patches with improvements. +
+ + ++While std::auto_ptr is deprecated in C++11, some existing code may +still be using it, so SWIG provides limited support for this class: +std_auto_ptr.i defines the typemaps which apply to the functions +returning objects of this type. Any other use of std_auto_ptr.i is not +directly supported. +
+ ++A typical example of use would be +
++%include <std_auto_ptr.i> + +%auto_ptr(Klass) +%inline %{ +class Klass { +public: + // Factory function creating objects of this class: + static std::auto_ptr<Klass> Create(int value) { + return std::auto_ptr<Klass>(new Klass(value)); + } + + int getValue() const { return m_value; } + +private: + DerivedIntValue(int value) : m_value(value) {} + int m_value; +}; +%} ++
+The returned objects can be used naturally from the target language, e.g. from +C#: +
+ ++Klass k = Klass.Create(17); +int value = k.getValue(); ++
diff --git a/Doc/Manual/Lisp.html b/Doc/Manual/Lisp.html index 01ff3a3..0867ba9 100644 --- a/Doc/Manual/Lisp.html +++ b/Doc/Manual/Lisp.html @@ -1,12 +1,13 @@ - +
@@ -50,7 +51,7 @@ here
-@@ -77,7 +78,7 @@ swig -cffi -module module-name file-name files and the various things which you can do with them.
-@@ -118,11 +119,11 @@ swig -cffi -help -
@@ -219,19 +220,19 @@ The generated SWIG Code will be: (cl:defconstant x (cl:ash 5 -1)) (cffi:defcstruct bar - (p :short) - (q :short) - (a :char) - (b :char) - (z :pointer) - (n :pointer)) + (p :short) + (q :short) + (a :char) + (b :char) + (z :pointer) + (n :pointer)) (cffi:defcvar ("my_struct" my_struct) :pointer) (cffi:defcstruct foo - (a :int) - (b :pointer)) + (a :int) + (b :pointer)) (cffi:defcfun ("pointer_func" pointer_func) :int (ClosureFun :pointer) @@ -247,9 +248,9 @@ The generated SWIG Code will be: (array :pointer)) (cffi:defcenum color - :RED - :BLUE - :GREEN) + :RED + :BLUE + :GREEN)
@@ -284,9 +285,11 @@ Let's edit the interface file such that the C type "div_t*" is changed %feature("export"); %feature("inline") lispsort_double; - %feature("intern_function", "my-lispify") lispsort_double; +%feature("export", package="'some-other-package") lispsort_double; + %rename func123 renamed_cool_func; + %ignore "pointer_func"; %include "test.h" @@ -310,12 +313,13 @@ The feature intern_function ensures that all C names are lispsort_double;, here we are using an additional feature which allows us to use our lispify function.
-The export feature allows us to export the symbols. The inline - feature declaims the declared function as inline. The rename - directive allows us to change the name(it is useful when - generating C wrapper code for handling overloaded - functions). The ignore directive ignores a certain - declaration. +
The export feature allows us to export the symbols. If + the package argument is given, then the symbol will be exported to + the specified Lisp package. The inline feature declaims the + declared function as inline. The rename directive allows us to + change the name(it is useful when generating C wrapper code for handling + overloaded functions). The ignore directive ignores a certain + declaration.
There are several other things which are possible, to see some example of usage of SWIG look at the Lispbuilder and wxCL @@ -332,12 +336,12 @@ The feature intern_function ensures that all C names are (cl:export '#.(swig-lispify "x" 'constant)) (cffi:defcstruct #.(swig-lispify "bar" 'classname) - (#.(swig-lispify "p" 'slotname) :short) - (#.(swig-lispify "q" 'slotname) :short) - (#.(swig-lispify "a" 'slotname) :char) - (#.(swig-lispify "b" 'slotname) :char) - (#.(swig-lispify "z" 'slotname) :pointer) - (#.(swig-lispify "n" 'slotname) :pointer)) + (#.(swig-lispify "p" 'slotname) :short) + (#.(swig-lispify "q" 'slotname) :short) + (#.(swig-lispify "a" 'slotname) :char) + (#.(swig-lispify "b" 'slotname) :char) + (#.(swig-lispify "z" 'slotname) :pointer) + (#.(swig-lispify "n" 'slotname) :pointer)) (cl:export '#.(swig-lispify "bar" 'classname)) @@ -359,8 +363,8 @@ The feature intern_function ensures that all C names are (cl:export '#.(swig-lispify "my_struct" 'variable)) (cffi:defcstruct #.(swig-lispify "foo" 'classname) - (#.(swig-lispify "a" 'slotname) :int) - (#.(swig-lispify "b" 'slotname) :pointer)) + (#.(swig-lispify "a" 'slotname) :int) + (#.(swig-lispify "b" 'slotname) :pointer)) (cl:export '#.(swig-lispify "foo" 'classname)) @@ -381,18 +385,18 @@ The feature intern_function ensures that all C names are (n :int) (array :pointer)) -(cl:export '#.(my-lispify "lispsort_double" 'function)) +(cl:export '#.(my-lispify "lispsort_double" 'function) 'some-other-package) (cffi:defcenum #.(swig-lispify "color" 'enumname) - #.(swig-lispify "RED" 'enumvalue :keyword) - #.(swig-lispify "BLUE" 'enumvalue :keyword) - #.(swig-lispify "GREEN" 'enumvalue :keyword)) + #.(swig-lispify "RED" 'enumvalue :keyword) + #.(swig-lispify "BLUE" 'enumvalue :keyword) + #.(swig-lispify "GREEN" 'enumvalue :keyword)) (cl:export '#.(swig-lispify "color" 'enumname))
This feature to SWIG (for CFFI) is very new and still far from @@ -568,7 +572,7 @@ If you have any questions, suggestions, patches, etc., related to CFFI module feel free to contact us on the SWIG mailing list, and also please add a "[CFFI]" tag in the subject line. -
@@ -608,7 +612,7 @@ Note that the block %{ ... %} is effectively a shortcut for
-@@ -638,7 +642,7 @@ swig -clisp -module module-name file-name interface file for the CLISP module. The CLISP module tries to produce code which is both human readable and easily modifyable.
-@@ -658,33 +662,33 @@ swig -clisp -help
As mentioned earlier the CLISP bindings generated by SWIG may need
- some modifications. The clisp module creates a lisp file with
- the same name as the module name. This
- lisp file contains a 'defpackage' declaration, with the
- package name same as the module name. This package uses the
- 'common-lisp' and 'ffi' packages. Also, package exports all
- the functions, structures and variables for which an ffi
- binding was generated.
- After generating the defpackage statement, the clisp module also
- sets the default language.
+some modifications. The clisp module creates a lisp file with
+the same name as the module name. This
+lisp file contains a 'defpackage' declaration, with the
+package name same as the module name. This package uses the
+'common-lisp' and 'ffi' packages. Also, package exports all
+the functions, structures and variables for which an ffi
+binding was generated.
+After generating the defpackage statement, the clisp module also
+sets the default language.
(defpackage :test @@ -734,18 +738,18 @@ void test123(float x , double y); (ffi:def-call-out pointer_func (:name "pointer_func") (:arguments (ClosureFun (ffi:c-function (:arguments (arg0 (ffi:c-pointer NIL)) - (arg1 (ffi:c-pointer NIL)) - (arg2 (ffi:c-pointer NIL))) - (:return-type NIL))) - (y ffi:int)) + (arg1 (ffi:c-pointer NIL)) + (arg2 (ffi:c-pointer NIL))) + (:return-type NIL))) + (y ffi:int)) (:return-type ffi:int) (:library +library-name+)) (ffi:def-call-out func123 (:name "func123") (:arguments (x (ffi:c-pointer div_t)) - (z (ffi:c-ptr (ffi:c-array (ffi:c-ptr (ffi:c-ptr ffi:int)) 100))) - (y (ffi:c-ptr (ffi:c-ptr (ffi:c-array ffi:int (1000 10)))))) + (z (ffi:c-ptr (ffi:c-array (ffi:c-ptr (ffi:c-ptr ffi:int)) 100))) + (y (ffi:c-ptr (ffi:c-ptr (ffi:c-array ffi:int (1000 10)))))) (:return-type ffi:int) (:library +library-name+)) @@ -753,14 +757,14 @@ void test123(float x , double y); (ffi:def-call-out lispsort_double (:name "lispsort_double") (:arguments (n ffi:int) - (array (ffi:c-ptr DOUBLE-FLOAT))) + (array (ffi:c-ptr DOUBLE-FLOAT))) (:return-type NIL) (:library +library-name+)) (ffi:def-call-out test123 (:name "test") (:arguments (x SINGLE-FLOAT) - (y DOUBLE-FLOAT)) + (y DOUBLE-FLOAT)) (:return-type NIL) (:library +library-name+)) @@ -795,7 +799,7 @@ struct bar {
-The current SWIG implementation is designed to work with Lua 5.0.x, 5.1.x and 5.2.x. It should work with later versions of Lua, but certainly not with Lua 4.0 due to substantial API changes. It is possible to either static link or dynamic link a Lua module into the interpreter (normally Lua static links its libraries, as dynamic linking is not available on all platforms). SWIG also supports eLua and works with eLua 0.8. SWIG generated code for eLua has been tested on Stellaris ARM Cortex-M3 LM3S and Infineon TriCore. +The current SWIG implementation is designed to work with Lua 5.0.x, 5.1.x and 5.2.x. It should work with later versions of Lua, but certainly not with Lua 4.0 due to substantial API changes. It is possible to either static link or dynamic link a Lua module into the interpreter (normally Lua static links its libraries, as dynamic linking is not available on all platforms). SWIG also has support for eLua starting from eLua 0.8. Due to substantial changes between SWIG 2.x and SWIG 3.0 and unavailability of testing platform, eLua status was downgraded to 'experimental'.
-@@ -128,7 +138,7 @@ $ swig -lua -eluac example.i The -elua option puts all the C function wrappers and variable get/set wrappers in rotables. It also generates a metatable which will control the access to these variables from eLua. It also offers a significant amount of module size compression. On the other hand, the -eluac option puts all the wrappers in a single rotable. With this option, no matter how huge the module, it will consume no additional microcontroller SRAM (crass compression). There is a catch though: Metatables are not generated with -eluac. To access any value from eLua, one must directly call the wrapper function associated with that value.
-@@ -159,9 +169,17 @@ swig -lua -help
@@ -184,8 +202,8 @@ int main(int argc,char* argv[]) return 0; } L=lua_open(); - luaopen_base(L); // load basic libs (eg. print) - luaopen_example(L); // load the wrapped module + luaopen_base(L); // load basic libs (eg. print) + luaopen_example(L); // load the wrapped module if (luaL_loadfile(L,argv[1])==0) // load and run the file lua_pcall(L,0,0,0); else @@ -232,7 +250,7 @@ LUALIB_API int ( luaopen_mod )(lua_State *L ); More information on building and configuring eLua can be found here: http://www.eluaproject.net/doc/v0.8/en_building.html
-@@ -240,8 +258,8 @@ Most, but not all platforms support the dynamic loading of modules (Windows &
$ swig -lua example.i -o example_wrap.c -$ gcc -I/usr/include/lua -c example_wrap.c -o example_wrap.o -$ gcc -c example.c -o example.o +$ gcc -fPIC -I/usr/include/lua -c example_wrap.c -o example_wrap.o +$ gcc -fPIC -c example.c -o example.o $ gcc -shared -I/usr/include/lua -L/usr/lib/lua example_wrap.o example.o -o example.so
@@ -300,7 +318,7 @@ Is quite obvious (Go back and consult the Lua documents on how to enable loadlib -
@@ -318,19 +336,19 @@ $ ./my_lua >
By default, SWIG tries to build a very natural Lua interface to your C/C++ code. This section briefly covers the essential aspects of this wrapping.
-The SWIG module directive specifies the name of the Lua module. If you specify `module example', then everything is wrapped into a Lua table 'example' containing all the functions and variables. When choosing a module name, make sure you don't use the same name as a built-in Lua command or standard module name.
-@@ -349,7 +367,10 @@ creates a built-in function example.fact(n) that works exactly like you >
-To avoid name collisions, SWIG create a Lua table which it keeps all the functions and global variables in. It is possible to copy the functions out of this and into the global environment with the following code. This can easily overwrite existing functions, so this must be used with care. +To avoid name collisions, SWIG create a Lua table which keeps all the functions, constants, classes and global variables in. +It is possible to copy the functions, constants and classes (but not variables) out of this and into the global environment with the following code. +This can easily overwrite existing functions, so this must be used with care. +This option is considered deprecated and will be removed in the near future.
> for k,v in pairs(example) do _G[k]=v end @@ -368,7 +389,7 @@ It is also possible to rename the module with an assignment. 24
@@ -456,7 +477,7 @@ If you have used the -eluac option for your eLua module, you will have In general, functions of the form "variable_get()" and "variable_set()" are automatically generated by SWIG for use with -eluac.
-@@ -490,7 +511,64 @@ If you're using eLua and have used -elua or -eluac to generate > print(example.const.SCONST) Hello World -
+Enums are exported into a class table. For example, given some enums: +
+%module example +enum Days { SUNDAY = 0, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }; +struct Test { + enum { TEST1 = 10, TEST2 = 20 }; +#ifdef __cplusplus // There are no static members in C + static const int ICONST = 12; +#endif +}; +
+There is a slight difference in behaviour wrapping C and C++ code due to the different scoping rules of C and C++. +The wrapped C++ code is used as follows from Lua code: +
++> print(example.SUNDAY) +0 +> print(example.Test.TEST1) +10 +> print(example.Test.ICONST) +12 +
Enums within a C struct are in the global namespace and are used as follows from Lua
++> print(example.SUNDAY) +0 +> -- See the difference here +> print(example.TEST1) +10 +
+Compatibility Note: Versions of SWIG prior to SWIG-3.0.0 did not generate the class table members above. +There is no change in the C wrappers, but +the following code was the only way to access these constants/enums when wrapping C++ member constants: +
++> print(example.Test_TEST1) +10 +> print(example.Test_ICONST) +12 +
+The old-style bindings are still generated in addition to the new ones. +If the -no-old-metatable-bindings option is used, then these old-style bindings are not generated. +
++It is worth mentioning, that example.Test.TEST1 and example.Test_TEST1 are different entities and changing one does not change the other. +Given the fact that these are constantes and they are not supposed to be changed, it is up to you to avoid such issues. +
+@@ -528,7 +606,7 @@ Lua enforces the integrity of its userdata, so it is virtually impossible to cor nil -
@@ -551,7 +629,7 @@ is used as follows:
Similar access is provided for unions and the data members of C++ classes.
-C structures are created using a function new_Point(), but for C++ classes are created using just the name Point().
+C structures can be created using a function new_Point(), and both C structures and C++ classes can be created using just the name Point().
If you print out the value of p in the above example, you will see something like this: @@ -632,7 +710,7 @@ For eLua with the -eluac option, structure manipulation has to be perfo In general, functions of the form "new_struct()", "struct_member_get()", "struct_member_set()" and "free_struct()" are automatically generated by SWIG for each structure defined in C. (Please note: This doesn't apply for modules generated with the -elua option)
-@@ -676,12 +754,12 @@ public: };
-In Lua, the static members can be accessed as follows: +In Lua, C++ static members can be accessed as follows:
-> example.Spam_foo() -- calling Spam::foo() -> a=example.Spam_bar -- reading Spam::bar -> example.Spam_bar=b -- writing to Spam::bar +> example.Spam.foo() -- calling Spam::foo() +> a=example.Spam.bar -- reading Spam::bar +> example.Spam.bar=b -- writing to Spam::bar
It is not (currently) possible to access static members of an instance: @@ -692,7 +770,22 @@ It is not (currently) possible to access static members of an instance: -- does NOT work -
+Compatibility Note: In versions prior to SWIG-3.0.0 only the following names would work: +
+ ++> example.Spam_foo() -- calling Spam::foo() +> a=example.Spam_bar -- reading Spam::bar +> example.Spam_bar=b -- writing to Spam::bar +
+Both style names are generated by default now. +However, if the -no-old-metatable-bindings option is used, then the backward compatible names are not generated in addition to ordinary ones. +
+ +@@ -717,7 +810,7 @@ then the function spam() accepts a Foo pointer or a pointer to any clas
It is safe to use multiple inheritance with SWIG.
-@@ -748,7 +841,7 @@ Foo spam7();
then all three functions will return a pointer to some Foo object. Since the third function (spam7) returns a value, newly allocated memory is used to hold the result and a pointer is returned (Lua will release this memory when the return value is garbage collected). The other two are pointers which are assumed to be managed by the C code and so will not be garbage collected.
-@@ -799,7 +892,7 @@ void spam(short);
or
-VOID FOO(bAR *B); +void foo(Bar *b); void foo(Bar &b);@@ -834,7 +927,7 @@ Please refer to the "SWIG and C++" chapter for more information about overloadin
Dealing with the Lua coercion mechanism, the priority is roughly (integers, floats, strings, userdata). But it is better to rename the functions rather than rely upon the ordering.
-26.3.11 C++ operators
+28.3.11 C++ operators
@@ -898,10 +991,10 @@ The current list of operators which can be overloaded (and the alternative funct
+C++ operators are mapped to Lua predefined metafunctions. Class inherits from its bases the following list of metafunctions ( thus inheriting the folloging +operators and pseudo-operators):
+No other lua metafunction is inherited. For example, __gc is not inherited and must be redefined in every class. __tostring is subject to a special handling. If absent in class and in class bases, a default one will be provided by SWIG. +
+@@ -981,7 +1096,7 @@ Now we extend it with some new code return tmp; } bool operator==(const Complex& c) - { return ($self->re()==c.re() && $self->im()==c.im();} + { return ($self->re()==c.re() && $self->im()==c.im());} };
@@ -1002,7 +1117,7 @@ true Extend works with both C and C++ code, on classes and structs. It does not modify the underlying object in any way---the extensions only show up in the Lua interface. The only item to take note of is the code has to use the '$self' instead of 'this', and that you cannot access protected/private members of the code (as you are not officially part of the class).
-If you have a function that allocates memory like this,
@@ -1026,7 +1141,7 @@ char *foo();This will release the allocated memory.
-@@ -1061,7 +1176,7 @@ In Lua:
Obviously, there is more to template wrapping than shown in this example. More details can be found in the SWIG and C++ chapter. Some more complicated examples will appear later.
-
@@ -1113,7 +1228,7 @@ If you ever need to access the underlying pointer returned by operator->(
> f = p:__deref__() -- Returns underlying Foo *
-26.3.16 C++ Exceptions
+28.3.16 C++ Exceptions
@@ -1256,13 +1371,164 @@ and the "Exception handling add exception specification to functions or globally (respectively).
++Since SWIG-3.0.0 C++ namespaces are supported via the %nspace feature. +
+Namespaces are mapped into Lua tables. Each of those tables contains names that were defined within appropriate namespace. Namespaces structure (a.k.a nested namespaces) is preserved. Consider the following C++ code: +
+%module example +%nspace MyWorld::Nested::Dweller; +%nspace MyWorld::World; + +int module_function() { return 7; } +int module_variable = 9; + +namespace MyWorld { + class World { + public: + World() : world_max_count(9) {} + int create_world() { return 17; } + const int world_max_count; // = 9 + }; + namespace Nested { + class Dweller { + public: + enum Gender { MALE = 0, FEMALE = 1 }; + static int count() { return 19; } + }; + } +} +
+Now, from Lua usage is as follows: +
+ ++> print(example.module_function()) +7 +> print(example.module_variable) +9 +> print(example.MyWorld.World():create_world()) +17 +> print(example.MyWorld.World.world_max_count) +9 +> print(example.MyWorld.Nested.Dweller.MALE) +0 +> print(example.MyWorld.Nested.Dweller.count()) +19 +> +
+If SWIG is running in a backwards compatible way, i.e. without the -no-old-metatable-bindings option, then additional old-style names are generated (notice the underscore): +
++9 +> print(example.MyWorld.Nested.Dweller_MALE) +0 +> print(example.MyWorld.Nested.Dweller_count()) +11 +> +
If SWIG is launched without -no-old-metatable-bindings option, then it enters backward-compatible mode. While in this mode, it tries +to generate additional names for static functions, class static constants and class enums. +Those names are in a form $classname_$symbolname and are added to the scope surrounding the class. +If %nspace is enabled, then class namespace is taken as scope. If there is no namespace, or %nspace is disabled, +then module is considered a class namespace.
+Consider the following C++ code
+%module example +%nspace MyWorld::Test; +namespace MyWorld { +class Test { + public: + enum { TEST1 = 10, TEST2 } + static const int ICONST = 12; +}; +class Test2 { + public: + enum { TEST3 = 20, TEST4 } + static const int ICONST2 = 23; +} +
When in backward compatible mode, in addition to the usual names, the following ones will be generated (notice the underscore):
++9 +> print(example.MyWorld.Test_TEST1) -- Test has %nspace enabled +10 +> print(example.MyWorld.Test_ICONST) -- Test has %nspace enabled +12 +> print(example.Test2_TEST3) -- Test2 doesn't have %nspace enabled +20 +> print(example.Test2_ICONST2) -- Test2 doesn't have %nspace enabled +23 +> +
There is a slight difference with enums when in C mode. As per C standard, enums from C structures are exported to +surrounding scope without any prefixing. Pretending that Test2 is a struct, not class, that would be:
++> print(example.TEST3) -- NOT Test2_TEST3 +20 +> +
The internal organization of inheritance has changed. +Consider the following C++ code:
+%module example +class Base { + public: + int base_func() +}; +class Derived : public Base { + public: + int derived_func() +} +
Lets assume for a moment that class member functions are stored in .fn table. Previously, when classes +were exported to Lua during module initialization, for every derived class all service tables ST(i.e. ".fn") +were squashed and added to corresponding derived class ST: Everything from .fn table of class Base +was copied to .fn table of class Derived and so on. This was a recursive procedure, so in the end the whole +inheritance tree of derived class was squashed into derived class.
+That means that any changes done to class Base after module initialization wouldn't affect class Derived:
++base = example.Base() +der = example.Derived() +> print(base.base_func) +function: 0x1367940 +> getmetatable(base)[".fn"].new_func = function (x) return x -- Adding new function to class Base (to class, not to an instance!) +> print(base.new_func) -- Checking this function +function +> print(der.new_func) -- Wouldn't work. Derived doesn't check Base any more. +nil +> +
This behaviour was changed. Now unless -squash-bases option is provided, Derived store a list of it's bases and if some symbol is not found in it's own service tables +then its bases are searched for it. Option -squash-bases will effectively return old behaviour. +
+> print(der.new_func) -- Now it works +function +> +
This section explains what typemaps are and how to use them. The default wrapping behaviour of SWIG is enough in most cases. However sometimes SWIG may need a little additional assistance to know which typemap to apply to provide the best wrapping. This section will be explaining how to use typemaps to best effect
-A typemap is nothing more than a code generation rule that is attached to a specific C datatype. For example, to convert integers from Lua to C, you might define a typemap like this:
@@ -1270,8 +1536,8 @@ add exception specification to functions or globally (respectively).%module example %typemap(in) int { - $1 = (int) lua_tonumber(L,$input); - printf("Received an integer : %d\n",$1); + $1 = (int) lua_tonumber(L,$input); + printf("Received an integer : %d\n",$1); } %inline %{ extern int fact(int n); @@ -1290,7 +1556,7 @@ Received an integer : 6 720
There are many ready written typemaps built into SWIG for all common types (int, float, short, long, char*, enum and more), which SWIG uses automatically, with no effort required on your part.
@@ -1343,7 +1609,7 @@ void swap(int *sx, int *sy);Note: C++ references must be handled exactly the same way. However SWIG will automatically wrap a const int& as an input parameter (since that it obviously input).
-Arrays present a challenge for SWIG, because like pointers SWIG does not know whether these are input or output values, nor @@ -1407,7 +1673,7 @@ and Lua tables to be 1..N, (the indexing follows the norm for the language). In
Note: SWIG also can support arrays of pointers in a similar manner.
-Several C++ libraries use a pointer-pointer functions to create its objects. These functions require a pointer to a pointer which is then filled with the pointer to the new object. Microsoft's COM and DirectX as well as many other libraries have this kind of function. An example is given below:
@@ -1441,7 +1707,7 @@ int Create_Math(iMath** pptr); // its creator (assume it mallocs) ptr=nil -- the iMath* will be GC'ed as normal -This section describes how you can modify SWIG's default wrapping behavior for various C/C++ datatypes using the %typemap directive. This is an advanced topic that assumes familiarity with the Lua C API as well as the material in the "Typemaps" chapter.
@@ -1450,7 +1716,7 @@ ptr=nil -- the iMath* will be GC'ed as normalBefore proceeding, you should read the previous section on using typemaps, and look at the existing typemaps found in luatypemaps.swg and typemaps.i. These are both well documented and fairly easy to read. You should not attempt to write your own typemaps until you have read and can understand both of these files (they may well also give you an idea to base your work on).
-There are many different types of typemap that can be written, the full list can be found in the "Typemaps" chapter. However the following are the most commonly used ones.
@@ -1463,7 +1729,7 @@ ptr=nil -- the iMath* will be GC'ed as normal (the syntax for the typecheck is different from the typemap, see typemaps for details). -This section explains the SWIG specific Lua-C API. It does not cover the main Lua-C api, as this is well documented and not worth covering.
@@ -1512,7 +1778,7 @@ This macro, when called within the context of a SWIG wrapped function, will disp@@ -1521,7 +1787,7 @@ This section covers adding of some small extra bits to your module to add the la -
@@ -1540,7 +1806,7 @@ int native_function(lua_State*L) // my native code The %native directive in the above example, tells SWIG that there is a function int native_function(lua_State*L); which is to be added into the module under the name 'my_func'. SWIG will not add any wrapper for this function, beyond adding it into the function table. How you write your code is entirely up to you.
-@@ -1578,7 +1844,7 @@ Good uses for this feature is adding of new code, or writing helper functions to See Examples/lua/arrays for an example of this code.
-@@ -1589,7 +1855,7 @@ See Examples/lua/arrays for an example of this code.
-@@ -1649,7 +1915,7 @@ end
That way when you call 'a=example.Foo', the interpreter looks at the table 'example' sees that there is no field 'Foo' and calls __index. This will in turn check in '.get' table and find the existence of 'Foo' and then return the value of the C function call 'Foo_get()'. Similarly for the code 'example.Foo=10', the interpreter will check the table, then call the __newindex which will then check the '.set' table and call the C function 'Foo_set(10)'.
-@@ -1729,7 +1995,7 @@ Note: Both the opaque structures (like the FILE*) and normal wrapped classes/str
Note: Operator overloads are basically done in the same way, by adding functions such as '__add' & '__call' to the class' metatable. The current implementation is a bit rough as it will add any member function beginning with '__' into the metatable too, assuming its an operator overload.
-diff --git a/Doc/Manual/Makefile b/Doc/Manual/Makefile index 42149ba..fb5f67c 100644 --- a/Doc/Manual/Makefile +++ b/Doc/Manual/Makefile @@ -9,7 +9,7 @@ # validation. # # Additional html validation can be done using the validate target. -# Additional link checking can be done using the linkchecker target. +# Additional link checking can be done using the linkchecker1 and linkchecker2 target. # # Note the # and " are escaped @@ -19,31 +19,35 @@ HTMLDOC_OPTIONS = "--book --toclevels 4 --no-numbered --toctitle \"Table of Cont all: maketoc check generate -maketoc: CCache.html +maketoc: python maketoc.py +# Use this to regenerate CCache.html should this ever be needed CCache.html: ../../CCache/ccache.yo yodl2html -o CCache.html ../../CCache/ccache.yo +# Tabs in the html files will stop the build as wkhtmltopdf does not expand them correctly - replace them with the appropriate number of tabs # Use htmltidy to warn about some HTML errors. Note that it is not used to clean/tidy the HTML, # it is just used as a primitive HTML checker. # CCache.html is generated by yodl2html and has a few insignificant problems, so we don't put it through tidy check: - tidy -errors --gnu-emacs yes -quiet index.html - tidy -errors --gnu-emacs yes -quiet Sections.html - all=`sed '/^#/d' chapters | grep -v CCache.html`; for a in $$all; do tidy -errors --gnu-emacs yes -quiet $$a; done; + all="index.html Sections.html `sed '/^#/d' chapters | grep -v CCache.html`" && for a in $$all; do echo "Check for tabs $$a" && if grep -P '\t' $$a; then echo "Please delete the tabs from the lines above" && exit 1; fi; done && for a in $$all; do echo "HTML tidy check $$a" && tidy -errors --gnu-emacs yes -quiet $$a; done; -generate: swightml.book swigpdf.book +# Note wkhtmltopdf limitations for generating pdf docs: +# 1)
elements should be expanded to 8 spaces by default, but +# are expanded to just one space and css tab-size is not working. +# 3)-elements do not always select a fixed-width font - try installing the +# Courier font to fix - these have been added to style.css. +generate: SWIGDocumentation.html + wkhtmltopdf --version | grep "with patched qt" || (echo "wkhtmltopdf is not the patched qt version and so cannot be used - download it from http://wkhtmltopdf.org/downloads.html" && false) + wkhtmltopdf --margin-top 20mm --margin-bottom 20mm --margin-left 10mm --margin-right 10mm --header-font-size 6 --footer-font-size 6 --header-spacing 6 --footer-spacing 6 --header-center '[doctitle]' --footer-left '[subsection]' --footer-right '[page]' SWIGDocumentation.html SWIGDocumentation.pdf + +SWIGDocumentation.html: swightml.book htmldoc --batch swightml.book || true - htmldoc --batch swigpdf.book || true python fixstyle.py SWIGDocumentation.html -swigpdf.book: chapters Sections.html - echo "#HTMLDOC 1.8.24" > swigpdf.book - echo -t pdf13 -f SWIGDocumentation.pdf $(HTMLDOC_OPTIONS) --stylesheet style.css >> swigpdf.book - echo "Sections.html" >> swigpdf.book - cat chapters >> swigpdf.book - swightml.book: chapters Sections.html echo "#HTMLDOC 1.8.24" > swightml.book echo -t html -f SWIGDocumentation.html $(HTMLDOC_OPTIONS) >> swightml.book @@ -52,10 +56,9 @@ swightml.book: chapters Sections.html maintainer-clean: clean-baks rm -f swightml.book - rm -f swigpdf.book - rm -f CCache.html rm -f SWIGDocumentation.html rm -f SWIGDocumentation.pdf + rm -rf linkchecker-tmp clean-baks: rm -f *.bak @@ -69,10 +72,18 @@ test: validate: all=`sed '/^#/d' chapters`; for a in $$all; do validate --emacs $$a; done; -# Link checking using linkchecker -linkchecker: +# Link checking using linkchecker of the index.html only file (including anchors) +linkchecker1: @echo ----------------------------------------------------------------------- @echo Note linkchecker versions prior to 6.1 do not work properly wrt anchors @echo ----------------------------------------------------------------------- - linkchecker --config=./linkchecker.config index.html + linkchecker --config=./linkchecker.config --anchors index.html + +# Check for links which don't work including those generated from the individual .html files into SWIGDocumentation.html +linkchecker2: + rm -rf linkchecker-tmp + mkdir linkchecker-tmp + cp SWIGDocumentation.html linkchecker-tmp + cp *.png linkchecker-tmp + (cd linkchecker-tmp && linkchecker --config=../linkchecker.config -F text --no-warnings SWIGDocumentation.html) diff --git a/Doc/Manual/Modula3.html b/Doc/Manual/Modula3.html index 065313f..f324495 100644 --- a/Doc/Manual/Modula3.html +++ b/Doc/Manual/Modula3.html @@ -1,11 +1,12 @@ - +
SWIG and Modula-3 + -27 SWIG and Modula-3
+29 SWIG and Modula-3
-@@ -45,7 +46,7 @@
-This chapter describes SWIG's support of +This chapter describes SWIG's support for Modula-3. You should be familiar with the basics @@ -54,7 +55,7 @@ especially typemaps.
-27.1 Overview
+29.1 Overview
@@ -84,7 +85,7 @@ FFTW -
27.1.1 Motivation
+29.1.1 Motivation
@@ -109,7 +110,7 @@ into exceptions.
If the library API is ill designed -writing appropriate typemaps can be still time-consuming. +writing appropriate typemaps can still be time-consuming. E.g. C programmers are very creative to work-around missing data types like (real) enumerations and sets. You should turn such work-arounds back to the Modula-3 way @@ -120,21 +121,21 @@ otherwise you lose static safety and consistency. Without SWIG you would probably never consider trying to call C++ libraries from Modula-3, but with SWIG this is becomes feasible. SWIG can generate C wrappers to C++ functions and object methods -that may throw exceptions, and then wrap these C wrappers for Module-3. +that may throw exceptions, and then wrap these C wrappers for Modula-3. To make it complete you can then hide the C interface with Modula-3 classes and exceptions.
SWIG allows you to call C and C++ libraries from Modula-3 (even with call back -functions), but it doesn't allow you to easily integrate a Module-3 module into +functions), but it doesn't allow you to easily integrate a Modula-3 module into a C/C++ project.
-27.2 Conception
+29.2 Conception
-27.2.1 Interfaces to C libraries
+29.2.1 Interfaces to C libraries
@@ -283,7 +284,7 @@ and the principal type must be renamed (%typemap).
-27.2.2 Interfaces to C++ libraries
+29.2.2 Interfaces to C++ libraries
@@ -384,10 +385,10 @@ There is no C++ library I wrote a SWIG interface for, so I'm not sure if this is possible or sensible, yet.
-27.3 Preliminaries
+29.3 Preliminaries
-27.3.1 Compilers
+29.3.1 Compilers
@@ -400,7 +401,7 @@ For testing examples I use Critical Mass cm3.
-27.3.2 Additional Commandline Options
+29.3.2 Additional Commandline Options
@@ -477,10 +478,10 @@ Instead generate templates for some basic typemaps. -
27.4 Modula-3 typemaps
+29.4 Modula-3 typemaps
-27.4.1 Inputs and outputs
+29.4.1 Inputs and outputs
@@ -694,7 +695,7 @@ consist of the following parts: -
27.4.2 Subranges, Enumerations, Sets
+29.4.2 Subranges, Enumerations, Sets
@@ -746,7 +747,7 @@ that I'd like to automate.
-27.4.3 Objects
+29.4.3 Objects
@@ -759,7 +760,7 @@ is not really useful, yet.
-27.4.4 Imports
+29.4.4 Imports
@@ -792,7 +793,7 @@ IMPORT M3toC;
27.4.5 Exceptions
+29.4.5 Exceptions
@@ -816,7 +817,7 @@ you should declare %typemap("m3wrapinconv:throws") blah * %{OSError.E%}.
-27.4.6 Example
+29.4.6 Example
@@ -863,10 +864,10 @@ where almost everything is generated by a typemap:
27.5 More hints to the generator
+29.5 More hints to the generator
-27.5.1 Features
+29.5.1 Features
@@ -77,7 +78,7 @@ where you want to create a collection of modules. Each module in the collection is created via separate invocations of SWIG.
-@@ -130,7 +131,7 @@ public:
To create the wrapper properly, module derived_module needs to know about the base class and that its interface is covered in another module. The -line %import "base_module.i" lets SWIG know exactly that. Oftentimes +line %import "base_module.i" lets SWIG know exactly that. Often the .h file is passed to %import instead of the .i, which unfortunately doesn't work for all language modules. For example, Python requires the name of module that the base class exists in so that the proxy classes can fully inherit the @@ -176,7 +177,7 @@ in parallel from multiple threads as SWIG provides no locking - for more on that issue, read on.
-@@ -242,7 +243,7 @@ can peacefully coexist. So the type structures are separated by the is empty. Only modules compiled with the same pair will share type information.
-As described in The run-time type checker, @@ -250,7 +251,9 @@ the functions SWIG_TypeQuery, SWIG_NewPointerObj, and others s to be called. Calling these functions from a typemap is supported, since the typemap code is embedded into the _wrap.c file, which has those declarations available. If you need to call the SWIG run-time functions from another C file, there is one header you need -to include. To generate the header that needs to be included, run the following command: +to include. To generate the header that needs to be included, SWIG can be run in a different +mode via -external-runtime to generate the run-time instead of the normal mode of +processing an input interface file. For example:
$ swig -python -external-runtime <filename> @@ -279,7 +282,7 @@ SWIG_TYPE_TABLE to be the same as the module whose types you are trying to access. -15.5 A word of caution about static libraries
+16.5 A word of caution about static libraries
@@ -290,7 +293,7 @@ into it. This is very often NOT what you want and it can lead to unexpect behavior. When working with dynamically loadable modules, you should try to work exclusively with shared libraries.
-15.6 References
+16.6 References
@@ -298,7 +301,7 @@ Due to the complexity of working with shared libraries and multiple modules, it an outside reference. John Levine's "Linkers and Loaders" is highly recommended.
-15.7 Reducing the wrapper file size
+16.7 Reducing the wrapper file size
diff --git a/Doc/Manual/Mzscheme.html b/Doc/Manual/Mzscheme.html index 3b49a29..c5c1992 100644 --- a/Doc/Manual/Mzscheme.html +++ b/Doc/Manual/Mzscheme.html @@ -1,14 +1,14 @@ - - +
SWIG and MzScheme/Racket + -28 SWIG and MzScheme/Racket
+30 SWIG and MzScheme/Racket
-@@ -24,7 +24,7 @@
-This section contains information on SWIG's support of Racket, formally known as MzScheme. -
28.1 Creating native structures
+30.1 Creating native structures
@@ -56,16 +56,16 @@ Then in scheme, you can use regular struct access procedures like
-- ; suppose a function created a struct foo as - ; (define foo (make-diag-cntrs (#x1 #x2 #x3) (make-inspector)) - ; Then you can do - (format "0x~x" (diag-cntrs-field1 foo)) - (format "0x~x" (diag-cntrs-field2 foo)) - ;etc... + ; suppose a function created a struct foo as + ; (define foo (make-diag-cntrs (#x1 #x2 #x3) (make-inspector)) + ; Then you can do + (format "0x~x" (diag-cntrs-field1 foo)) + (format "0x~x" (diag-cntrs-field2 foo)) + ;etc...28.2 Simple example
+30.2 Simple example
@@ -166,7 +166,7 @@ Some points of interest:
- The above requests mzc to create an extension using the CGC garbage-collector. The alternative -- the 3m collector -- has generally better performance, but work is still required for SWIG to emit code which is compatible with it.
28.3 External documentation
+30.3 External documentation
diff --git a/Doc/Manual/Ocaml.html b/Doc/Manual/Ocaml.html index 127be90..e489c41 100644 --- a/Doc/Manual/Ocaml.html +++ b/Doc/Manual/Ocaml.html @@ -1,12 +1,13 @@ - +
-SWIG and Ocaml +SWIG and Ocaml + - - -29 SWIG and Ocaml
+ + +31 SWIG and Ocaml
-@@ -45,10 +46,10 @@
- Overriding Methods in Ocaml
- Director Usage Example
- Creating director objects -
- Typemaps for directors, directorin, directorout, directorargout -
- directorin typemap -
- directorout typemap -
- directorargout typemap +
- Typemaps for directors, directorin, directorout, directorargout +
- typemap +
- directorout typemap +
- directorargout typemap
- Exceptions @@ -59,74 +60,76 @@
- This chapter describes SWIG's -support of Ocaml. Ocaml is a relatively recent addition to the ML family, -and is a recent addition to SWIG. It's the second compiled, typed -language to be added. Ocaml has widely acknowledged benefits for engineers, -mostly derived from a sophisticated type system, compile-time checking -which eliminates several classes of common programming errors, and good -native performance. While all of this is wonderful, there are well-written -C and C++ libraries that Ocaml users will want to take advantage of as -part of their arsenal (such as SSL and gdbm), as well as their own mature -C and C++ code. SWIG allows this code to be used in a natural, type-safe -way with Ocaml, by providing the necessary, but repetitive glue code -which creates and uses Ocaml values to communicate with C and C++ code. - In addition, SWIG also produces the needed Ocaml source that binds -variants, functions, classes, etc. +This chapter describes SWIG's support of Ocaml. +
+ ++Ocaml is a relatively recent addition to the ML family, +and is a recent addition to SWIG. It's the second compiled, typed +language to be added. Ocaml has widely acknowledged benefits for engineers, +mostly derived from a sophisticated type system, compile-time checking +which eliminates several classes of common programming errors, and good +native performance. While all of this is wonderful, there are well-written +C and C++ libraries that Ocaml users will want to take advantage of as +part of their arsenal (such as SSL and gdbm), as well as their own mature +C and C++ code. SWIG allows this code to be used in a natural, type-safe +way with Ocaml, by providing the necessary, but repetitive glue code +which creates and uses Ocaml values to communicate with C and C++ code. +In addition, SWIG also produces the needed Ocaml source that binds +variants, functions, classes, etc.
If you're not familiar with the Objective Caml language, you can visit -The Ocaml Website. +The Ocaml Website.
-29.1 Preliminaries
+31.1 Preliminaries
- SWIG 1.3 works with Ocaml 3.04 and above. Given the choice, - you should use the latest stable release. The SWIG Ocaml module has -been tested on Linux (x86,PPC,Sparc) and Cygwin on Windows. The -best way to determine whether your system will work is to compile the -examples and test-suite which come with SWIG. You can do this by running -make check from the SWIG root directory after installing SWIG. - The Ocaml module has been tested using the system's dynamic linking (the -usual -lxxx against libxxx.so, as well as with Gerd Stolpmann's -Dl package -. The ocaml_dynamic and ocaml_dynamic_cpp targets in the +SWIG 3.0 works with Ocaml 3.08.3 and above. Given the choice, +you should use the latest stable release. The SWIG Ocaml module has +been tested on Linux (x86,PPC,Sparc) and Cygwin on Windows. The +best way to determine whether your system will work is to compile the +examples and test-suite which come with SWIG. You can do this by running +make check from the SWIG root directory after installing SWIG. +The Ocaml module has been tested using the system's dynamic linking (the +usual -lxxx against libxxx.so, as well as with Gerd Stolpmann's +Dl package. +The ocaml_dynamic and ocaml_dynamic_cpp targets in the file Examples/Makefile illustrate how to compile and link SWIG modules that will be loaded dynamically. This has only been tested on Linux so far.
-29.1.1 Running SWIG
+31.1.1 Running SWIG
- The basics of getting a SWIG Ocaml module up and running - can be seen from one of SWIG's example Makefiles, but is also described - here. To build an Ocaml module, run SWIG using the -ocaml -option. +The basics of getting a SWIG Ocaml module up and running +can be seen from one of SWIG's example Makefiles, but is also described +here. To build an Ocaml module, run SWIG using the -ocaml +option.
---+-+- -%swig -ocaml example.i -+This will produce 3 files. The file example_wrap.c contains + +
This will produce 3 files. The file example_wrap.c contains all of the C code needed to build an Ocaml module. To build the module, -you will compile the file example_wrap.c with ocamlc or +you will compile the file example_wrap.c with ocamlc or ocamlopt to create the needed .o file. You will need to compile the resulting .ml and .mli files as well, and do the final link with -custom -(not needed for native link).
- -29.1.2 Compiling the code
+(not needed for native link). + +31.1.2 Compiling the code
-The OCaml SWIG module now requires you to compile a module (Swig) +The OCaml SWIG module now requires you to compile a module (Swig) separately. In addition to aggregating common SWIG functionality, the Swig module contains the data structure that represents C/C++ values. This allows easier data sharing between modules if two or more are combined, because @@ -134,39 +137,40 @@ the type of each SWIG'ed module's c_obj is derived from Swig.c_obj_t. This also allows SWIG to acquire new conversions painlessly, as well as giving the user more freedom with respect to custom typing. - Use ocamlc or ocamlopt to compile your - SWIG interface like: +Use ocamlc or ocamlopt to compile your SWIG interface like:
- --+ ++- -% swig -ocaml -co swig.mli ; swig -ocaml co swig.ml % ocamlc -c swig.mli ; ocamlc -c swig.ml % ocamlc -c -ccopt "-I/usr/include/foo" example_wrap.c % ocamlc -c example.mli % ocamlc -c example.ml -+ocamlc is aware of .c files and knows how to handle them. Unfortunately, - it does not know about .cxx, .cc, or .cpp files, so when SWIG is invoked - in C++ mode, you must:
- ----% cp example_wrap.cxx example_wrap.cxx.c+ +
% ocamlc -c ... -ccopt -xc++ example_wrap.cxx.c
% ...
-ocamlc is aware of .c files and knows how to handle them. Unfortunately, +it does not know about .cxx, .cc, or .cpp files, so when SWIG is invoked +in C++ mode, you must:
+ ++-+% cp example_wrap.cxx example_wrap.cxx.c +% ocamlc -c ... -ccopt -xc++ example_wrap.cxx.c +% ... +29.1.3 The camlp4 module
+31.1.3 The camlp4 module
The camlp4 module (swigp4.ml -> swigp4.cmo) contains a simple rewriter which -makes C++ code blend more seamlessly with objective caml code. It's use is +makes C++ code blend more seamlessly with objective caml code. Its use is optional, but encouraged. The source file is included in the Lib/ocaml -directory of the SWIG source distribution. You can checkout this file with -"swig -ocaml -co swigp4.ml". You should compile the file with +directory of the SWIG source distribution. You can checkout this file with +"swig -ocaml -co swigp4.ml". You should compile the file with "ocamlc -I `camlp4 -where` -pp 'camlp4o pa_extend.cmo q_MLast.cmo' -c swigp4.ml"
@@ -192,7 +196,7 @@ a '+= b(invoke object) "+=" argument as in
(invoke a) "+=" b- Note that because camlp4 always recognizes << + Note that because camlp4 always recognizes << and >>, they are replaced by lsl and lsr in operator names. - 'unop object as in
@@ -234,21 +238,21 @@ let b = C_string (getenv "PATH")29.1.4 Using your module
+31.1.4 Using your module
You can test-drive your module by building a toplevel ocaml interpreter. Consult the ocaml manual for details.
- +When linking any ocaml bytecode with your module, use the -custom - option to build your functions into the primitive list. This - option is not needed when you build native code. +option to build your functions into the primitive list. This +option is not needed when you build native code.
-29.1.5 Compilation problems and compiling with C++
+31.1.5 Compilation problems and compiling with C++
@@ -259,7 +263,7 @@ liberal with pointer types may not compile under the C++ compiler. Most code meant to be compiled as C++ will not have problems.
-29.2 The low-level Ocaml/C interface
+31.2 The low-level Ocaml/C interface
@@ -273,9 +277,9 @@ In the code as seen by the typemap writer, there is a value, swig_result, that always contains the current return data. It is a list, and must be appended with the caml_list_append function, or with functions and macros provided by -objective caml.
- +
+objective caml.type c_obj = C_void @@ -299,68 +303,67 @@ type c_obj =- A few functions exist which generate and return these: +A few functions exist which generate and return these:
- +-
- caml_ptr_val receives a c_obj and returns a void *. This - should be used for all pointer purposes.
-- caml_long_val receives a c_obj and returns a long. This - should be used for most integral purposes.
-
-- caml_val_ptr receives a void * and returns a c_obj.
-- caml_val_bool receives a C int and returns a c_obj representing - it's bool value.
-- caml_val_(u)?(char|short|int|long|float|double) receives an -appropriate C value and returns a c_obj representing it.
-- caml_val_string receives a char * and returns a string value.
-- caml_val_string_len receives a char * and a length and returns - a string value.
-- caml_val_obj receives a void * and an object type and returns - a C_obj, which contains a closure giving method access.
- +- caml_ptr_val receives a c_obj and returns a void *. This + should be used for all pointer purposes.
+- caml_long_val receives a c_obj and returns a long. This + should be used for most integral purposes.
+- caml_val_ptr receives a void * and returns a c_obj.
+- caml_val_bool receives a C int and returns a c_obj representing + its bool value.
+- caml_val_(u)?(char|short|int|long|float|double) receives an + appropriate C value and returns a c_obj representing it.
+- caml_val_string receives a char * and returns a string value.
+- caml_val_string_len receives a char * and a length and returns + a string value.
+- caml_val_obj receives a void * and an object type and returns + a C_obj, which contains a closure giving method access.
Because of this style, a typemap can return any kind of value it -wants from a function. This enables out typemaps and inout typemaps -to work well. The one thing to remember about outputting values -is that you must append them to the return list with swig_result = caml_list_append(swig_result,v). -
- -- This function will return a new list that has your element - appended. Upon return to caml space, the fnhelper function - beautifies the result. A list containing a single item degrades to - only that item (i.e. [ C_int 3 ] -> C_int 3), and a list - containing more than one item is wrapped in C_list (i.e. [ C_char - 'a' ; C_char 'b' -> C_list [ C_char 'a' ; C_char b - ]). This is in order to make return values easier to handle - when functions have only one return value, such as constructors, - and operators. In addition, string, pointer, and object - values are interchangeable with respect to caml_ptr_val, so you can - allocate memory as caml strings and still use the resulting - pointers for C purposes, even using them to construct simple objects - on. Note, though, that foreign C++ code does not respect the garbage - collector, although the SWIG interface does.
- -- The wild card type that you can use in lots of different ways is - C_obj. It allows you to wrap any type of thing you like as an - object using the same mechanism that the ocaml module - does. When evaluated in caml_ptr_val, the returned value is - the result of a call to the object's "&" operator, taken as a pointer. -
-- You should only construct values using objective caml, or using the - functions caml_val_* functions provided as static functions to a SWIG - ocaml module, as well as the caml_list_* functions. These functions - provide everything a typemap needs to produce values. In addition, - value items pass through directly, but you must make your own type - signature for a function that uses value in this way. -
- -29.2.1 The generated module
+wants from a function. This enables out typemaps and inout typemaps +to work well. The one thing to remember about outputting values +is that you must append them to the return list with swig_result = caml_list_append(swig_result,v). + + ++This function will return a new list that has your element +appended. Upon return to caml space, the fnhelper function +beautifies the result. A list containing a single item degrades to +only that item (i.e. [ C_int 3 ] -> C_int 3), and a list +containing more than one item is wrapped in C_list (i.e. [ C_char +'a' ; C_char 'b' -> C_list [ C_char 'a' ; C_char b +]). This is in order to make return values easier to handle +when functions have only one return value, such as constructors, +and operators. In addition, string, pointer, and object +values are interchangeable with respect to caml_ptr_val, so you can +allocate memory as caml strings and still use the resulting +pointers for C purposes, even using them to construct simple objects +on. Note, though, that foreign C++ code does not respect the garbage +collector, although the SWIG interface does.
+ ++The wild card type that you can use in lots of different ways is +C_obj. It allows you to wrap any type of thing you like as an +object using the same mechanism that the ocaml module +does. When evaluated in caml_ptr_val, the returned value is +the result of a call to the object's "&" operator, taken as a pointer. +
+ ++You should only construct values using objective caml, or using the +functions caml_val_* functions provided as static functions to a SWIG +ocaml module, as well as the caml_list_* functions. These functions +provide everything a typemap needs to produce values. In addition, +value items pass through directly, but you must make your own type +signature for a function that uses value in this way. +
+ +31.2.1 The generated module
@@ -376,7 +379,7 @@ that the keywords are not the same as the C++ ones. You can introduce extra code into the output wherever you like with SWIG. These are the places you can introduce code:
-
- -"header" This code is inserted near the beginning of the + "header" This code is inserted near the beginning of the C wrapper file, before any function definitions. @@ -385,25 +388,25 @@ file. "wrapper" This code is inserted in the function definition section. - "mli" This code is inserted into the caml interface file. Special signatures should be inserted here. "ml" This code is inserted in the caml code defining the + + "ml" This code is inserted in the caml code defining the interface to your C code. Special caml code, as well as any initialization which should run when the module is loaded may be inserted here. - "classtemplate" The "classtemplate" place is special because it describes the output SWIG will generate for class definitions. 29.2.2 Enums
+ +31.2.2 Enums
SWIG will wrap enumerations as polymorphic variants in the output -Ocaml code, as above in C_enum. In order to support all +Ocaml code, as above in C_enum. In order to support all C++-style uses of enums, the function int_to_enum and enum_to_int are provided for ocaml code to produce and consume these values as -integers. Other than that, correct uses of enums will not have -a problem. Since enum labels may overlap between enums, the +integers. Other than that, correct uses of enums will not have +a problem. Since enum labels may overlap between enums, the enum_to_int and int_to_enum functions take an enum type label as an argument. Example:
@@ -416,9 +419,9 @@ enum c_enum_type { a = 1, b, c = 4, d = 8 }; enum c_enum_type { a = 1, b, c = 4, d = 8 };+
The output mli contains: -
++type c_enum_type = [ @@ -435,16 +438,16 @@ type c_enum_tag = [ val int_to_enum c_enum_type -> int -> c_obj val enum_to_int c_enum_type -> c_obj -> c_obj-- So it's possible to do this: +So it's possible to do this:
---+++bash-2.05a$ ocamlmktop -custom enum_test_wrap.o enum_test.cmo -o enum_test_top -bash-2.05a$ ./enum_test_top +bash-2.05a$ ./enum_test_top Objective Caml version 3.04 # open Enum_test ;; @@ -455,9 +458,9 @@ val x : Enum_test.c_obj = C_enum `a # int_to_enum `c_enum_type 4 ;; - : Enum_test.c_obj = C_enum `c-29.2.2.1 Enum typing in Ocaml
+31.2.2.1 Enum typing in Ocaml
@@ -470,10 +473,10 @@ functions imported from different modules. You must convert values to master values using the swig_val function before sharing them with another module.
-29.2.3 Arrays
+31.2.3 Arrays
-29.2.3.1 Simple types of bounded arrays
+31.2.3.1 Simple types of bounded arrays
@@ -485,7 +488,7 @@ distribution.
By including "carray.i", you will get access to some macros that help you -create typemaps for array types fairly easily. +create typemaps for array types fairly easily.
@@ -494,7 +497,7 @@ arrays of simple types with known bounds in your code, but this only works for arrays whose bounds are completely specified.
-29.2.3.2 Complex and unbounded arrays
+31.2.3.2 Complex and unbounded arrays
@@ -507,7 +510,7 @@ SWIG can't predict which of these methods will be used in the array, so you have to specify it for yourself in the form of a typemap.
-29.2.3.3 Using an object
+31.2.3.3 Using an object
@@ -521,7 +524,7 @@ Consider writing an object when the ending condition of your array is complex, such as using a required sentinel, etc.
-29.2.3.4 Example typemap for a function taking float * and int
+31.2.3.4 Example typemap for a function taking float * and int
@@ -541,24 +544,24 @@ into this type of function convenient. #include <stdio.h> void printfloats( float *tab, int len ) { - int i; + int i; - for( i = 0; i < len; i++ ) { - printf( "%f ", tab[i] ); - } + for( i = 0; i < len; i++ ) { + printf( "%f ", tab[i] ); + } - printf( "\n" ); + printf( "\n" ); } %} %typemap(in) (float *tab, int len) { - int i; - /* $*1_type */ - $2 = caml_array_len($input); - $1 = ($*1_type *)malloc( $2 * sizeof( float ) ); - for( i = 0; i < $2; i++ ) { - $1[i] = caml_double_val(caml_array_nth($input,i)); - } + int i; + /* $*1_type */ + $2 = caml_array_len($input); + $1 = ($*1_type *)malloc( $2 * sizeof( float ) ); + for( i = 0; i < $2; i++ ) { + $1[i] = caml_double_val(caml_array_nth($input,i)); + } } void printfloats( float *tab, int len ); @@ -572,30 +575,30 @@ void printfloats( float *tab, int len );
29.2.4 C++ Classes
+31.2.4 C++ Classes
C++ classes, along with structs and unions are represented by C_obj -(string -> c_obj -> c_obj) wrapped closures. These objects +(string -> c_obj -> c_obj) wrapped closures. These objects contain a method list, and a type, which allow them to be used like C++ objects. When passed into typemaps that use pointers, they -degrade to pointers through their "&" method. Every method +degrade to pointers through their "&" method. Every method an object has is represented as a string in the object's method table, -and each method table exists in memory only once. In addition +and each method table exists in memory only once. In addition to any other operators an object might have, certain builtin ones are -provided by SWIG: (all of these take no arguments (C_void)) +provided by SWIG: (all of these take no arguments (C_void))
@@ -615,7 +618,7 @@ the underlying pointer, so using create_[x]_from_ptr alters the returned value for the same object. -
- "~" Delete this object "&" Return an ordinary C_ptr value representing this + "&" Return an ordinary C_ptr value representing this object's address "sizeof" If enabled with ("sizeof"="1") on the module node, return the object's size in char. - ":methods" Returns a list of strings containing the names of the methods this object contains ":classof" Returns the name of the class this object belongs + ":classof" Returns the name of the class this object belongs to. @@ -603,8 +606,8 @@ have been wrapped by SWIG. indicated parent class. This is mainly used internally by the SWIG module, but may be useful to client programs. ":parents" Returns a list of all direct parent classes which have been wrapped by SWIG. "[member-variable]" Each member variable is wrapped as a -method with an optional parameter. -Called with one argument, the member variable is set to the value of the +method with an optional parameter. +Called with one argument, the member variable is set to the value of the argument. With zero arguments, the value is returned. 29.2.4.1 STL vector and string Example
+31.2.4.1 STL vector and string Example
@@ -637,7 +640,7 @@ length. Instead, use multiple returns, as in the argout_ref example. %include <stl.i> namespace std { - %template(StringVector) std::vector < string >; + %template(StringVector) std::vector < string >; }; %include "example.h" @@ -652,12 +655,12 @@ Since there's a makefile in that directory, the example is easy to build.
Here's a sample transcript of an interactive session using a string vector -after making a toplevel (make toplevel). This example uses the camlp4 +after making a toplevel (make toplevel). This example uses the camlp4 module.
--bash-2.05a$ ./example_top +bash-2.05a$ ./example_top Objective Caml version 3.06 Camlp4 Parsing version 3.06 @@ -685,17 +688,17 @@ C_list - : Example.c_obj = C_void # x '[1] ;; - : Example.c_obj = C_string "spam" -# for i = 0 to (x -> size() as int) - 1 do - print_endline ((x '[i to int]) as string) +# for i = 0 to (x -> size() as int) - 1 do + print_endline ((x '[i to int]) as string) done ;; foo bar baz - : unit = () -# +#29.2.4.2 C++ Class Example
+31.2.4.2 C++ Class Example
@@ -703,7 +706,7 @@ Here's a simple example using Trolltech's Qt Library:
-
-+ qt.i qt.i %module qt %{ @@ -712,20 +715,20 @@ Here's a simple example using Trolltech's Qt Library: %} class QApplication { public: - QApplication( int argc, char **argv ); - void setMainWidget( QWidget *widget ); - void exec(); + QApplication( int argc, char **argv ); + void setMainWidget( QWidget *widget ); + void exec(); }; class QPushButton { public: - QPushButton( char *str, QWidget *w ); - void resize( int x, int y ); - void show(); + QPushButton( char *str, QWidget *w ); + void resize( int x, int y ); + void show(); };29.2.4.3 Compiling the example
+31.2.4.3 Compiling the example
-@@ -733,9 +736,9 @@ bash-2.05a$ QTPATH=/your/qt/path bash-2.05a$ for file in swig.mli swig.ml swigp4.ml ; do swig -ocaml -co $file ; done bash-2.05a$ ocamlc -c swig.mli ; ocamlc -c swig.ml bash-2.05a$ ocamlc -I `camlp4 -where` -pp "camlp4o pa_extend.cmo q_MLast.cmo" -c swigp4.ml -bash-2.05a$ swig -ocaml -c++ -I$QTPATH/include qt.i +bash-2.05a$ swig -ocaml -c++ -I$QTPATH/include qt.i bash-2.05a$ mv qt_wrap.cxx qt_wrap.c -bash-2.05a$ ocamlc -c -ccopt -xc++ -ccopt -g -g -ccopt -I$QTPATH/include qt_wrap.c +bash-2.05a$ ocamlc -c -ccopt -xc++ -ccopt -g -g -ccopt -I$QTPATH/include qt_wrap.c bash-2.05a$ ocamlc -c qt.mli bash-2.05a$ ocamlc -c qt.ml bash-2.05a$ ocamlmktop -custom swig.cmo -I `camlp4 -where` \ @@ -743,11 +746,11 @@ bash-2.05a$ ocamlmktop -custom swig.cmo -I `camlp4 -where` \ -L$QTPATH/lib -cclib -lqt29.2.4.4 Sample Session
+31.2.4.4 Sample Session
--bash-2.05a$ ./qt_top +bash-2.05a$ ./qt_top Objective Caml version 3.06 Camlp4 Parsing version 3.06 @@ -767,13 +770,13 @@ val hello : Qt.c_obj = C_obj <fun>Assuming you have a working installation of QT, you will see a window -containing the string "hi" in a button. +containing the string "hi" in a button.
-29.2.5 Director Classes
+31.2.5 Director Classes
-29.2.5.1 Director Introduction
+31.2.5.1 Director Introduction
@@ -800,7 +803,7 @@ class foo { };
29.2.5.2 Overriding Methods in Ocaml
+31.2.5.2 Overriding Methods in Ocaml
@@ -828,7 +831,7 @@ In this example, I'll examine the objective caml code involved in providing an overloaded class. This example is contained in Examples/ocaml/shapes.
-29.2.5.3 Director Usage Example
+31.2.5.3 Director Usage Example
@@ -845,14 +848,14 @@ let triangle_class pts ob meth args = "cover" -> (match args with C_list [ x_arg ; y_arg ] -> - let xa = x_arg as float - and ya = y_arg as float in - (point_in_triangle pts xa ya) to bool + let xa = x_arg as float + and ya = y_arg as float in + (point_in_triangle pts xa ya) to bool | _ -> raise (Failure "cover needs two double arguments.")) | _ -> (invoke ob) meth args ;; let triangle = - new_derived_object + new_derived_object new_shape (triangle_class ((0.0,0.0),(0.5,1.0),(1.0,0.0))) '() ;; @@ -887,7 +890,7 @@ in a more effortless style in ocaml, while leaving the "engine" part of the program in C++. -
29.2.5.4 Creating director objects
+31.2.5.4 Creating director objects
@@ -896,7 +899,7 @@ The definition of the actual object triangle can be described this way:
-let triangle = - new_derived_object + new_derived_object new_shape (triangle_class ((0.0,0.0),(0.5,1.0),(1.0,0.0))) '() @@ -904,13 +907,13 @@ let triangle =The first argument to new_derived_object, new_shape is the method -which returns a shape instance. This function will be invoked with the +which returns a shape instance. This function will be invoked with the third argument will be appended to the argument list [ C_void ]. In the example, the actual argument list is sent as (C_list [ C_void ; C_void ]). The augmented constructor for a director class needs the first argument to determine whether it is being constructed as a derived object, or as an object of the indicated type only (in this case shape). The -Second argument is a closure that will be added to the final C_obj. +Second argument is a closure that will be added to the final C_obj.
@@ -928,7 +931,7 @@ object from causing a core dump, as long as the object is destroyed properly.
-29.2.5.5 Typemaps for directors, directorin, directorout, directorargout
+31.2.5.5 Typemaps for directors, directorin, directorout, directorargout
@@ -939,7 +942,7 @@ well as a function return value in the same way you provide function arguments, and to receive arguments the same way you normally receive function returns.
-29.2.5.6 directorin typemap
+31.2.5.6 typemap
@@ -950,7 +953,7 @@ code receives when you are called. In general, a simple directorin typ can use the same body as a simple out typemap.
-29.2.5.7 directorout typemap
+31.2.5.7 directorout typemap
@@ -961,7 +964,7 @@ for the same type, except when there are special requirements for object ownership, etc.
-29.2.5.8 directorargout typemap
+31.2.5.8 directorargout typemap
@@ -978,7 +981,7 @@ In the event that you don't specify all of the necessary values, integral values will read zero, and struct or object returns have undefined results.
-29.2.6 Exceptions
+31.2.6 Exceptions
diff --git a/Doc/Manual/Octave.html b/Doc/Manual/Octave.html index 3e12ce6..9b9744f 100644 --- a/Doc/Manual/Octave.html +++ b/Doc/Manual/Octave.html @@ -1,14 +1,15 @@ - +
SWIG and Octave + -30 SWIG and Octave
+32 SWIG and Octave
-@@ -33,6 +34,10 @@
- Class extension with %extend
- C++ templates
- C++ Smart Pointers +
- Directors (calling Octave from C++ code)
- Threads
- Memory management @@ -55,15 +60,16 @@ More information can be found at O Also, there are a dozen or so examples in the Examples/octave directory, and hundreds in the test suite (Examples/test-suite and Examples/test-suite/octave). -
30.1 Preliminaries
+32.1 Preliminaries
-As of SWIG 3.0.0, the Octave module has been tested with Octave versions 3.0.5, 3.2.4, 3.4.3, 3.6.4, and 3.8.0. -Use of Octave versions older than 3.x.x is not recommended, as these versions are no longer tested with SWIG. +As of SWIG 3.0.7, the Octave module is regularly tested with Octave versions 3.2.4, 3.8.1, and 4.0.0. +Use of older Octave versions is not recommended, as these versions are no longer tested with SWIG. +The SWIG runtime exports the function swig_octave_prereq() for checking the version of Octave.
-30.2 Running SWIG
+32.2 Running SWIG
@@ -95,7 +101,7 @@ The -c++ option is also required when wrapping C++ code: This creates a C++ source file "example_wrap.cpp". A C++ file is generated even when wrapping C code as Octave is itself written in C++ and requires wrapper code to be in the same language. The generated C++ source file contains the low-level wrappers that need to be compiled and linked with the rest of your C/C++ application (in this case, the gcd implementation) to create an extension module.
-30.2.1 Command-line options
+32.2.1 Command-line options
@@ -118,7 +124,7 @@ The special name "." loads C global variables into the module namespace, i.e. al The -opprefix options sets the prefix of the names of global/friend operator functions.
-30.2.2 Compiling a dynamic module
+32.2.2 Compiling a dynamic module
@@ -145,7 +151,7 @@ $ mkoctfile example_wrap.cpp example.c
-octave:1> swigexample30.2.3 Using your module
+32.2.3 Using your module
@@ -163,10 +169,10 @@ octave:4> swigexample.cvar.Foo=4; octave:5> swigexample.cvar.Foo ans = 4
30.3 A tour of basic C/C++ wrapping
+32.3 A tour of basic C/C++ wrapping
-30.3.1 Modules
+32.3.1 Modules
@@ -211,7 +217,7 @@ octave:4> swigexample.gcd(4,6) ans = 2
30.3.2 Functions
+32.3.2 Functions
@@ -228,7 +234,7 @@ int fact(int n);
-octave:1> swigexample.fact(4) 2430.3.3 Global variables
+32.3.3 Global variables
@@ -281,7 +287,7 @@ octave:2> swigexample.PI=3.142; octave:3> swigexample.PI ans = 3.1420 -
30.3.4 Constants and enums
+32.3.4 Constants and enums
@@ -303,7 +309,7 @@ swigexample.SCONST="Hello World" swigexample.SUNDAY=0 .... -
30.3.5 Pointers
+32.3.5 Pointers
@@ -329,7 +335,7 @@ octave:4> swigexample.fclose(f);
- Simply printing the value of a wrapped C++ type will print it's typename. E.g., + Simply printing the value of a wrapped C++ type will print its typename. E.g.,
-octave:1> swigexample; @@ -350,7 +356,7 @@ octave:2> f=swigexample.fopen("not there","r"); error: value on right hand side of assignment is undefined error: evaluating assignment expression near line 2, column 230.3.6 Structures and C++ classes
+32.3.6 Structures and C++ classes
@@ -485,7 +491,7 @@ ans = 1 Depending on the ownership setting of a swig_ref, it may call C++ destructors when its reference count goes to zero. See the section on memory management below for details.
-30.3.7 C++ inheritance
+32.3.7 C++ inheritance
@@ -494,7 +500,7 @@ This information contains the full class hierarchy. When an indexing operation ( the tree is walked to find a match in the current class as well as any of its bases. The lookup is then cached in the swig_ref.
-30.3.8 C++ overloaded functions
+32.3.8 C++ overloaded functions
@@ -504,7 +510,7 @@ The dispatch function selects which overload to call (if any) based on the passe typecheck typemaps are used to analyze each argument, as well as assign precedence. See the chapter on typemaps for details.
-30.3.9 C++ operators
+32.3.9 C++ operators
@@ -512,7 +518,7 @@ C++ operator overloading is supported, in a way similar to other modules. The swig_ref type supports all unary and binary operators between itself and all other types that exist in the system at module load time. When an operator is used (where one of the operands is a swig_ref), the runtime routes the call to either a member function of the given object, or to a global function whose named is derived from the types of the operands (either both or just the lhs or rhs).
-For example, if a and b are SWIG variables in Octave, a+b becomes a.__add(b). The wrapper is then free to implement __add to do whatever it wants. A wrapper may define the __add function manually, %rename some other function to it, or %rename a C++ operator to it. +For example, if a and b are SWIG variables in Octave, a+b becomes a.__add__(b). The wrapper is then free to implement __add__ to do whatever it wants. A wrapper may define the __add__ function manually, %rename some other function to it, or %rename a C++ operator to it.
By default the C++ operators are renamed to their corresponding Octave operators. So without doing any work, the following interface @@ -539,87 +545,87 @@ assert(c.value==5); Octave operators are mapped in the following way:
-__brace a{args} -__brace_asgn a{args} = rhs -__paren a(args) -__paren_asgn a(args) = rhs -__str generates string rep -__not !a -__uplus +a -__uminus -a -__transpose a.' -__hermitian a' -__incr a++ -__decr a-- -__add a + b -__sub a - b -__mul a * b -__div a / b -__pow a ^ b -__ldiv a \ b -__lshift a << b -__rshift a >> b -__lt a < b -__le a <= b -__eq a == b -__ge a >= b -__gt a > b -__ne a != b -__el_mul a .* b -__el_div a ./ b -__el_pow a .^ b -__el_ldiv a .\ b -__el_and a & b -__el_or a | b +__brace__ a{args} +__brace_asgn__ a{args} = rhs +__paren__ a(args) +__paren_asgn__ a(args) = rhs +__str__ generates string rep +__not__ !a +__uplus__ +a +__uminus__ -a +__transpose__ a.' +__hermitian__ a' +__incr__ a++ +__decr__ a-- +__add__ a + b +__sub__ a - b +__mul__ a * b +__div__ a / b +__pow__ a ^ b +__ldiv__ a \ b +__lshift__ a << b +__rshift__ a >> b +__lt__ a < b +__le__ a <= b +__eq__ a == b +__ge__ a >= b +__gt__ a > b +__ne__ a != b +__el_mul__ a .* b +__el_div__ a ./ b +__el_pow__ a .^ b +__el_ldiv__ a .\ b +__el_and__ a & b +__el_or__ a | bOn the C++ side, the default mappings are as follows:
-%rename(__add) *::operator+; -%rename(__add) *::operator+(); -%rename(__add) *::operator+() const; -%rename(__sub) *::operator-; -%rename(__uminus) *::operator-(); -%rename(__uminus) *::operator-() const; -%rename(__mul) *::operator*; -%rename(__div) *::operator/; -%rename(__mod) *::operator%; -%rename(__lshift) *::operator<<; -%rename(__rshift) *::operator>>; -%rename(__el_and) *::operator&&; -%rename(__el_or) *::operator||; -%rename(__xor) *::operator^; -%rename(__invert) *::operator~; -%rename(__lt) *::operator<; -%rename(__le) *::operator<=; -%rename(__gt) *::operator>; -%rename(__ge) *::operator>=; -%rename(__eq) *::operator==; -%rename(__ne) *::operator!=; -%rename(__not) *::operator!; -%rename(__incr) *::operator++; -%rename(__decr) *::operator--; -%rename(__paren) *::operator(); -%rename(__brace) *::operator[]; +%rename(__add__) *::operator+; +%rename(__add__) *::operator+(); +%rename(__add__) *::operator+() const; +%rename(__sub__) *::operator-; +%rename(__uminus__) *::operator-(); +%rename(__uminus__) *::operator-() const; +%rename(__mul__) *::operator*; +%rename(__div__) *::operator/; +%rename(__mod__) *::operator%; +%rename(__lshift__) *::operator<<; +%rename(__rshift__) *::operator>>; +%rename(__el_and__) *::operator&&; +%rename(__el_or__) *::operator||; +%rename(__xor__) *::operator^; +%rename(__invert__) *::operator~; +%rename(__lt__) *::operator<; +%rename(__le__) *::operator<=; +%rename(__gt__) *::operator>; +%rename(__ge__) *::operator>=; +%rename(__eq__) *::operator==; +%rename(__ne__) *::operator!=; +%rename(__not__) *::operator!; +%rename(__incr__) *::operator++; +%rename(__decr__) *::operator--; +%rename(__paren__) *::operator(); +%rename(__brace__) *::operator[];Octave can also utilise friend (i.e. non-member) operators with a simple %rename: see the example in the Examples/octave/operator directory.
-30.3.10 Class extension with %extend
+32.3.10 Class extension with %extend
The %extend directive works the same as in other modules.
-You can use it to define special behavior, like for example defining Octave operators not mapped to C++ operators, or defining certain Octave mechanisms such as how an object prints. For example, the octave_value::{is_string,string_value,print} functions are routed to a special method __str that can be defined inside an %extend. +You can use it to define special behavior, like for example defining Octave operators not mapped to C++ operators, or defining certain Octave mechanisms such as how an object prints. For example, the octave_value::{is_string,string_value,print} functions are routed to a special method __str__ that can be defined inside an %extend.
-%extend A { -string __str() { +string __str__() { stringstream sout; sout<<$self->value; return sout.str(); @@ -635,10 +641,19 @@ octave:2> a a = 4 octave:3> printf("%s\n",a); 4 -octave:4> a.__str() +octave:4> a.__str__() 430.3.11 C++ templates
+ ++Similarly, Octave can use the __float__ method to convert an object to a numeric value. +
+ ++Octave 3.8.0 and later versions will also map unary functions X() to the corresponding __X__ method, where X includes: abs(), acos(), acosh(), angle(), arg(), asin(), asinh(), atan(), atanh(), cbrt(), ceil(), conj(), cos(), cosh(), dawson(), erf(), erfc(), erfcinv(), erfcx(), erfi(), erfinv(), exp(), expm1(), finite(), fix(), floor(), gamma(), imag(), isalnum(), isalpha(), isascii(), iscntrl(), isdigit(), isgraph(), isinf(), islower(), isna(), isnan(), isprint(), ispunct(), isspace(), isupper(), isxdigit(), lgamma(), log(), log10(), log1p(), log2(), real(), round(), roundb(), signbit(), signum(), sin(), sinh(), sqrt(), tan(), tanh(), toascii(), tolower(), toupper() +
+ +32.3.11 C++ templates
@@ -687,7 +702,7 @@ Similarly, class templates can be instantiated as in the following example, s+=_s; return *this; } - std::string __str() const { + std::string __str__() const { std::stringstream sout; sout<<s; return sout.str(); @@ -715,14 +730,28 @@ ans = -
30.3.12 C++ Smart Pointers
+32.3.12 C++ Smart Pointers
+ + +32.3.12.1 The shared_ptr Smart Pointer
+ + ++The C++11 standard provides std::shared_ptr which was derived from the Boost +implementation, boost::shared_ptr. +Both of these are available for Octave in the SWIG library and usage is outlined +in the shared_ptr smart pointer library section. +
+ + +32.3.12.2 Generic Smart Pointers
C++ smart pointers are fully supported as in other modules.
-30.3.13 Directors (calling Octave from C++ code)
+32.3.13 Directors (calling Octave from C++ code)
@@ -803,14 +832,14 @@ c-side routine called octave-side routine called -
30.3.14 Threads
+32.3.14 Threads
The use of threads in wrapped Director code is not supported; i.e., an Octave-side implementation of a C++ class must be called from the Octave interpreter's thread. Anything fancier (apartment/queue model, whatever) is left to the user. Without anything fancier, this amounts to the limitation that Octave must drive the module... like, for example, an optimization package that calls Octave to evaluate an objective function.
-30.3.15 Memory management
+32.3.15 Memory management
@@ -844,14 +873,14 @@ The %newobject directive may be used to control this behavior for pointers retur In the case where one wishes for the C++ side to own an object that was created in Octave (especially a Director object), one can use the __disown() method to invert this logic. Then letting the Octave reference count go to zero will not destroy the object, but destroying the object will invalidate the Octave-side object if it still exists (and call destructors of other C++ bases in the case of multiple inheritance/subclass()'ing).
-30.3.16 STL support
+32.3.16 STL support
Various STL library files are provided for wrapping STL containers.
-30.3.17 Matrix typemaps
+32.3.17 Matrix typemaps
diff --git a/Doc/Manual/Perl5.html b/Doc/Manual/Perl5.html index 49e8965..8d7b866 100644 --- a/Doc/Manual/Perl5.html +++ b/Doc/Manual/Perl5.html @@ -1,12 +1,13 @@ - +
SWIG and Perl5 + -31 SWIG and Perl5
+33 SWIG and Perl5
@@ -87,7 +97,7 @@ later. We're no longer testing regularly with older versions, but Perl 5.6 seems to mostly work, while older versions don't. -@@ -68,6 +69,15 @@
- Modifying the proxy methods
- Adding additional Perl code +
- Cross language polymorphism +
31.1 Overview
+33.1 Overview
@@ -108,7 +118,7 @@ described. Advanced customization features, typemaps, and other options are found near the end of the chapter.
-31.2 Preliminaries
+33.2 Preliminaries
@@ -133,7 +143,7 @@ To build the module, you will need to compile the file example_wrap.c and link it with the rest of your program.
-31.2.1 Getting the right header files
+33.2.1 Getting the right header files
@@ -165,7 +175,7 @@ $ perl -e 'use Config; print "$Config{archlib}\n";' -
31.2.2 Compiling a dynamic module
+33.2.2 Compiling a dynamic module
@@ -198,7 +208,7 @@ the target should be named `example.so', `example.sl', or the appropriate dynamic module name on your system.
-31.2.3 Building a dynamic module with MakeMaker
+33.2.3 Building a dynamic module with MakeMaker
@@ -210,9 +220,9 @@ script such as the following:
# File : Makefile.PL use ExtUtils::MakeMaker; WriteMakefile( - `NAME' => `example', # Name of package - `LIBS' => [`-lm'], # Name of custom libraries - `OBJECT' => `example.o example_wrap.o' # Object files + `NAME' => `example', # Name of package + `LIBS' => [`-lm'], # Name of custom libraries + `OBJECT' => `example.o example_wrap.o' # Object files ); @@ -232,7 +242,7 @@ the preferred approach to compilation. More information about MakeMaker can be found in "Programming Perl, 2nd ed." by Larry Wall, Tom Christiansen, and Randal Schwartz. -31.2.4 Building a static version of Perl
+33.2.4 Building a static version of Perl
@@ -291,7 +301,7 @@ for a dynamic module, but change the link line to something like this:
$ gcc example.o example_wrap.o -L/usr/lib/perl/5.14/CORE \ - -lperl -lsocket -lnsl -lm -o myperl + -lperl -lsocket -lnsl -lm -o myperl@@ -301,7 +311,7 @@ added to it. Depending on your machine, you may need to link with additional libraries such as -lsocket, -lnsl, -ldl, etc.
-31.2.5 Using the module
+33.2.5 Using the module
@@ -454,7 +464,7 @@ system configuration (this requires root access and you will need to read the man pages).
-31.2.6 Compilation problems and compiling with C++
+33.2.6 Compilation problems and compiling with C++
@@ -484,8 +494,8 @@ Solaris, you often need to add an extra library -lCrun like this:
@@ -597,7 +607,7 @@ have to find the macro that conflicts and add an #undef into the .i file. Pleas any conflicting macros you find to swig-user mailing list. -$ swig -c++ -perl example.i -$ CC -c example.cxx -$ CC -c example_wrap.cxx -I/usr/lib/perl/5.14/i386-linux/CORE +$ CC -Kpic -c example.cxx +$ CC -Kpic -c example_wrap.cxx -I/usr/lib/perl/5.14/i386-linux/CORE $ CC -shared example.o example_wrap.o -o example.so -lCrun31.2.7 Compiling for 64-bit platforms
+33.2.7 Compiling for 64-bit platforms
@@ -624,7 +634,7 @@ also introduce problems on platforms that support more than one linking standard (e.g., -o32 and -n32 on Irix).
-31.3 Building Perl Extensions under Windows
+33.3 Building Perl Extensions under Windows
@@ -635,7 +645,7 @@ section assumes you are using SWIG with Microsoft Visual C++ although the procedure may be similar with other compilers.
-31.3.1 Running SWIG from Developer Studio
+33.3.1 Running SWIG from Developer Studio
@@ -698,7 +708,7 @@ print "$a\n"; -
31.3.2 Using other compilers
+33.3.2 Using other compilers
@@ -706,7 +716,7 @@ SWIG is known to work with Cygwin and may work with other compilers on Windows. For general hints and suggestions refer to the Windows chapter.
-31.4 The low-level interface
+33.4 The low-level interface
@@ -716,7 +726,7 @@ can be used to control your application. However, it is also used to construct more user-friendly proxy classes as described in the next section.
-31.4.1 Functions
+33.4.1 Functions
@@ -739,7 +749,7 @@ use example; $a = &example::fact(2); -
31.4.2 Global variables
+33.4.2 Global variables
@@ -809,7 +819,7 @@ extern char *path; // Declared later in the input -
31.4.3 Constants
+33.4.3 Constants
@@ -849,7 +859,7 @@ print example::FOO,"\n"; -
31.4.4 Pointers
+33.4.4 Pointers
@@ -882,9 +892,9 @@ To check to see if a value is the NULL pointer, use the
@@ -907,9 +917,9 @@ dereference them as follows:if (defined($ptr)) { - print "Not a NULL pointer."; + print "Not a NULL pointer."; } else { - print "Is a NULL pointer."; + print "Is a NULL pointer."; }@@ -958,7 +968,7 @@ as XS and xsubpp. Given the advancement of the SWIG typesystem and the SWIG and XS, this is no longer supported. -if ($$a == $$b) { - print "a and b point to the same thing in C"; + print "a and b point to the same thing in C"; } else { - print "a and b point to different objects."; + print "a and b point to different objects."; }31.4.5 Structures
+33.4.5 Structures
@@ -968,7 +978,7 @@ accessor functions as described in the "SWIG Basics" chapter. For example,
@@ -1092,7 +1102,7 @@ void Bar_f_set(Bar *b, Foo *val) { -struct Vector { - double x,y,z; + double x,y,z; };31.4.6 C++ classes
+33.4.6 C++ classes
@@ -1157,7 +1167,7 @@ provides direct access to C++ objects. A higher level interface using Perl prox can be built using these low-level accessors. This is described shortly.
-31.4.7 C++ classes and type-checking
+33.4.7 C++ classes and type-checking
@@ -1193,7 +1203,7 @@ If necessary, the type-checker also adjusts the value of the pointer (as is nece multiple inheritance is used).
-31.4.8 C++ overloaded functions
+33.4.8 C++ overloaded functions
@@ -1237,7 +1247,7 @@ example::Spam_foo_d($s,3.14); Please refer to the "SWIG Basics" chapter for more information.
-31.4.9 Operators
+33.4.9 Operators
@@ -1249,22 +1259,22 @@ The following C++ operators are currently supported by the Perl module:
-
-- operator++
-- operator--
-- operator+
-- operator-
-- operator*
-- operator/
-- operator==
-- operator!=
-- operator%
-- operator>
-- operator<
+- operator++
+- operator--
+- operator+
+- operator-
+- operator*
+- operator/
+- operator==
+- operator!=
+- operator%
+- operator>
+- operator<
- operator and
- operator or
31.4.10 Modules and packages
+33.4.10 Modules and packages
@@ -1359,7 +1369,7 @@ print Foo::fact(4),"\n"; # Call a function in package FooBar --> -
31.5 Input and output parameters
+33.5 Input and output parameters
@@ -1578,7 +1588,7 @@ print "$c\n"; Note: The REFERENCE feature is only currently supported for numeric types (integers and floating point).
-31.6 Exception handling
+33.6 Exception handling
@@ -1743,7 +1753,7 @@ This is still supported, but it is deprecated. The newer %exception di functionality, but it has additional capabilities that make it more powerful.
-31.7 Remapping datatypes with typemaps
+33.7 Remapping datatypes with typemaps
@@ -1760,7 +1770,7 @@ Typemaps are only used if you want to change some aspect of the primitive C-Perl interface.
-31.7.1 A simple typemap example
+33.7.1 A simple typemap example
@@ -1773,8 +1783,8 @@ you might define a typemap like this: %module example %typemap(in) int { - $1 = (int) SvIV($input); - printf("Received an integer : %d\n", $1); + $1 = (int) SvIV($input); + printf("Received an integer : %d\n", $1); } ... %inline %{ @@ -1819,8 +1829,8 @@ the typemap system follows typedef declarations. For example:
-%typemap(in) int n { - $1 = (int) SvIV($input); - printf("n = %d\n",$1); + $1 = (int) SvIV($input); + printf("n = %d\n",$1); } %inline %{ typedef int Integer; @@ -1864,7 +1874,7 @@ example::count("e","Hello World");31.7.2 Perl5 typemaps
+33.7.2 Perl5 typemaps
@@ -1969,7 +1979,7 @@ Return of C++ member data (all languages). Check value of input parameter. -
31.7.3 Typemap variables
+33.7.3 Typemap variables
@@ -2040,7 +2050,7 @@ properly assigned. The Perl name of the wrapper function being created. -
31.7.4 Useful functions
+33.7.4 Useful functions
@@ -2109,7 +2119,7 @@ int sv_isa(SV *, char *0; -
31.8 Typemap Examples
+33.8 Typemap Examples
@@ -2118,7 +2128,7 @@ might look at the files "perl5.swg" and "typemaps.i" in the SWIG library.
-31.8.1 Converting a Perl5 array to a char **
+33.8.1 Converting a Perl5 array to a char **
@@ -2133,47 +2143,47 @@ reference to be used as a char ** datatype. // This tells SWIG to treat char ** as a special case %typemap(in) char ** { - AV *tempav; - I32 len; - int i; - SV **tv; - if (!SvROK($input)) - croak("Argument $argnum is not a reference."); - if (SvTYPE(SvRV($input)) != SVt_PVAV) - croak("Argument $argnum is not an array."); - tempav = (AV*)SvRV($input); - len = av_len(tempav); - $1 = (char **) malloc((len+2)*sizeof(char *)); - for (i = 0; i <= len; i++) { - tv = av_fetch(tempav, i, 0); - $1[i] = (char *) SvPV(*tv,PL_na); - } - $1[i] = NULL; + AV *tempav; + I32 len; + int i; + SV **tv; + if (!SvROK($input)) + croak("Argument $argnum is not a reference."); + if (SvTYPE(SvRV($input)) != SVt_PVAV) + croak("Argument $argnum is not an array."); + tempav = (AV*)SvRV($input); + len = av_len(tempav); + $1 = (char **) malloc((len+2)*sizeof(char *)); + for (i = 0; i <= len; i++) { + tv = av_fetch(tempav, i, 0); + $1[i] = (char *) SvPV(*tv,PL_na); + } + $1[i] = NULL; }; // This cleans up the char ** array after the function call %typemap(freearg) char ** { - free($1); + free($1); } // Creates a new Perl array and places a NULL-terminated char ** into it %typemap(out) char ** { - AV *myav; - SV **svs; - int i = 0,len = 0; - /* Figure out how many elements we have */ - while ($1[len]) - len++; - svs = (SV **) malloc(len*sizeof(SV *)); - for (i = 0; i < len ; i++) { - svs[i] = sv_newmortal(); - sv_setpv((SV*)svs[i],$1[i]); - }; - myav = av_make(len,svs); - free(svs); - $result = newRV_noinc((SV*)myav); - sv_2mortal($result); - argvi++; + AV *myav; + SV **svs; + int i = 0,len = 0; + /* Figure out how many elements we have */ + while ($1[len]) + len++; + svs = (SV **) malloc(len*sizeof(SV *)); + for (i = 0; i < len ; i++) { + svs[i] = sv_newmortal(); + sv_setpv((SV*)svs[i],$1[i]); + }; + myav = av_make(len,svs); + free(svs); + $result = newRV_noinc((SV*)myav); + sv_2mortal($result); + argvi++; } // Now a few test functions @@ -2210,7 +2220,7 @@ print @$b,"\n"; # Print it out -
31.8.2 Return values
+33.8.2 Return values
@@ -2230,16 +2240,16 @@ can be done using the EXTEND() macro as in:
-%typemap(argout) int *OUTPUT { - if (argvi >= items) { - EXTEND(sp,1); /* Extend the stack by 1 object */ - } - $result = sv_newmortal(); - sv_setiv($target,(IV) *($1)); - argvi++; + if (argvi >= items) { + EXTEND(sp,1); /* Extend the stack by 1 object */ + } + $result = sv_newmortal(); + sv_setiv($target,(IV) *($1)); + argvi++; }31.8.3 Returning values from arguments
+33.8.3 Returning values from arguments
@@ -2254,24 +2264,24 @@ its arguments. This example describes the implementation of the OUTPUT // an output value. %typemap(argout) double *OUTPUT { - $result = sv_newmortal(); - sv_setnv($result, *$input); - argvi++; /* Increment return count -- important! */ + $result = sv_newmortal(); + sv_setnv($result, *$input); + argvi++; /* Increment return count -- important! */ } // We don't care what the input value is. Ignore, but set to a temporary variable %typemap(in,numinputs=0) double *OUTPUT(double junk) { - $1 = &junk; + $1 = &junk; } // Now a function to test it %{ /* Returns the first two input arguments */ int multout(double a, double b, double *out1, double *out2) { - *out1 = a; - *out2 = b; - return 0; + *out1 = a; + *out2 = b; + return 0; }; %} @@ -2293,7 +2303,7 @@ print "multout(7,13) = @r\n"; ($x,$y) = multout(7,13); -
31.8.4 Accessing array structure members
+33.8.4 Accessing array structure members
@@ -2356,7 +2366,7 @@ the "in" typemap in the previous section would be used to convert an to copy the converted array into a C data structure.
-31.8.5 Turning Perl references into C pointers
+33.8.5 Turning Perl references into C pointers
@@ -2367,7 +2377,7 @@ have a C function that modifies its arguments like this:
@@ -2421,7 +2431,7 @@ print "$c\n"; -void add(double a, double b, double *c) { - *c = a + b; + *c = a + b; }31.8.6 Pointer handling
+33.8.6 Pointer handling
@@ -2500,7 +2510,7 @@ For example: -
31.9 Proxy classes
+33.9 Proxy classes
@@ -2516,7 +2526,7 @@ to the underlying code. This section describes the implementation details of the proxy interface.
-31.9.1 Preliminaries
+33.9.1 Preliminaries
@@ -2538,7 +2548,7 @@ SWIG creates a collection of high-level Perl wrappers. In your scripts, you wil high level wrappers. The wrappers, in turn, interact with the low-level procedural module.
-31.9.2 Structure and class wrappers
+33.9.2 Structure and class wrappers
@@ -2548,9 +2558,9 @@ Suppose you have the following SWIG interface file:
@@ -2600,8 +2610,9 @@ sub DESTROY { my $self = tied(%{$_[0]}); delete $ITERATORS{$self}; if (exists $OWNER{$self}) { - examplec::delete_Vector($self)); - delete $OWNER{$self}; + examplec::delete_Vector($self)); + delete $OWNER{$self}; + } } sub FETCH { @@ -2653,8 +2664,8 @@ $v->{x} = 7.5; # Assignment of all members %$v = ( x=>3, - y=>9, - z=>-2); + y=>9, + z=>-2); # Reading members $x = $v->{x}; @@ -2664,7 +2675,7 @@ $v->DESTROY(); -%module example struct Vector { - Vector(double x, double y, double z); - ~Vector(); - double x,y,z; + Vector(double x, double y, double z); + ~Vector(); + double x,y,z; };31.9.3 Object Ownership
+33.9.3 Object Ownership
@@ -2675,7 +2686,7 @@ problem---suppose you had a function like this:
@@ -2688,9 +2699,9 @@ Vector object:Vector *Vector_get(Vector *v, int index) { - return &v[i]; + return &v[i]; }@@ -2751,7 +2762,7 @@ counting, garbage collection, or advanced features one might find in sophisticated languages. -Vector *new_Vector(double x, double y, double z) { - Vector *v; - v = new Vector(x,y,z); // Call C++ constructor - return v; + Vector *v; + v = new Vector(x,y,z); // Call C++ constructor + return v; }31.9.4 Nested Objects
+33.9.4 Nested Objects
@@ -2760,10 +2771,10 @@ Suppose that we have a new object that looks like this:
@@ -2779,9 +2790,9 @@ look like this (along with some supporting code): package Particle; ... %BLESSEDMEMBERS = ( - r => `Vector', - v => `Vector', - f => `Vector', + r => `Vector', + v => `Vector', + f => `Vector', ); @@ -2804,7 +2815,7 @@ $p->{f}->{x} = 0.0; %${$p->{v}} = ( x=>0, y=>0, z=>0); -struct Particle { - Vector r; - Vector v; - Vector f; - int type; + Vector r; + Vector v; + Vector f; + int type; }31.9.5 Proxy Functions
+33.9.5 Proxy Functions
@@ -2838,7 +2849,7 @@ This function replaces the original function, but operates in an identical manner.
-31.9.6 Inheritance
+33.9.6 Inheritance
@@ -2857,23 +2868,23 @@ interface file: class Shape { public: - virtual double area() = 0; - virtual double perimeter() = 0; - void set_location(double x, double y); + virtual double area() = 0; + virtual double perimeter() = 0; + void set_location(double x, double y); }; class Circle : public Shape { public: - Circle(double radius); - ~Circle(); - double area(); - double perimeter(); + Circle(double radius); + ~Circle(); + double area(); + double perimeter(); }; class Square : public Shape { public: - Square(double size); - ~Square(); - double area(); - double perimeter(); + Square(double size); + ~Square(); + double area(); + double perimeter(); } @@ -2914,7 +2925,7 @@ particular, inheritance of data members is extremely tricky (and I'm not even sure if it really works).
-31.9.7 Modifying the proxy methods
+33.9.7 Modifying the proxy methods
@@ -2942,7 +2953,7 @@ public: }; -
31.10 Adding additional Perl code
+33.10 Adding additional Perl code
@@ -2993,6 +3004,363 @@ set_transform($im, $a); +
33.11 Cross language polymorphism
+ + ++Proxy classes provide a more natural, object-oriented way to access +extension classes. As described above, each proxy instance has an +associated C++ instance, and method calls to the proxy are passed to the +C++ instance transparently via C wrapper functions. +
+ ++This arrangement is asymmetric in the sense that no corresponding +mechanism exists to pass method calls down the inheritance chain from +C++ to Perl. In particular, if a C++ class has been extended in Perl +(by extending the proxy class), these extensions will not be visible +from C++ code. Virtual method calls from C++ are thus not able access +the lowest implementation in the inheritance chain. +
+ ++Changes have been made to SWIG to address this problem and +make the relationship between C++ classes and proxy classes more +symmetric. To achieve this goal, new classes called directors are +introduced at the bottom of the C++ inheritance chain. The job of the +directors is to route method calls correctly, either to C++ +implementations higher in the inheritance chain or to Perl +implementations lower in the inheritance chain. The upshot is that C++ +classes can be extended in Perl and from C++ these extensions look +exactly like native C++ classes. Neither C++ code nor Perl code needs +to know where a particular method is implemented: the combination of +proxy classes, director classes, and C wrapper functions takes care of +all the cross-language method routing transparently. +
+ +33.11.1 Enabling directors
+ + ++The director feature is disabled by default. To use directors you +must make two changes to the interface file. First, add the "directors" +option to the %module directive, like this: +
+ +++ ++%module(directors="1") modulename +++Without this option no director code will be generated. Second, you +must use the %feature("director") directive to tell SWIG which classes +and methods should get directors. The %feature directive can be applied +globally, to specific classes, and to specific methods, like this: +
+ +++ ++// generate directors for all classes that have virtual methods +%feature("director"); + +// generate directors for all virtual methods in class Foo +%feature("director") Foo; +++You can use the %feature("nodirector") directive to turn off +directors for specific classes or methods. So for example, +
+ +++ ++%feature("director") Foo; +%feature("nodirector") Foo::bar; +++will generate directors for all virtual methods of class Foo except +bar(). +
+ ++Directors can also be generated implicitly through inheritance. +In the following, class Bar will get a director class that handles +the methods one() and two() (but not three()): +
+ +++ ++%feature("director") Foo; +class Foo { +public: + Foo(int foo); + virtual void one(); + virtual void two(); +}; + +class Bar: public Foo { +public: + virtual void three(); +}; +++then at the Perl side you can define +
+ +++ + ++use mymodule; + +package MyFoo; +use base 'mymodule::Foo'; + +sub one { + print "one from Perl\n"; +} ++33.11.2 Director classes
+ + + + + ++For each class that has directors enabled, SWIG generates a new class +that derives from both the class in question and a special +Swig::Director class. These new classes, referred to as director +classes, can be loosely thought of as the C++ equivalent of the Perl +proxy classes. The director classes store a pointer to their underlying +Perl object and handle various issues related to object ownership. +
+ ++For simplicity let's ignore the Swig::Director class and refer to the +original C++ class as the director's base class. By default, a director +class extends all virtual methods in the inheritance chain of its base +class (see the preceding section for how to modify this behavior). +Thus all virtual method calls, whether they originate in C++ or in +Perl via proxy classes, eventually end up in at the implementation in +the director class. The job of the director methods is to route these +method calls to the appropriate place in the inheritance chain. By +"appropriate place" we mean the method that would have been called if +the C++ base class and its extensions in Perl were seamlessly +integrated. That seamless integration is exactly what the director +classes provide, transparently skipping over all the messy extension API +glue that binds the two languages together. +
+ ++In reality, the "appropriate place" is one of only two possibilities: +C++ or Perl. Once this decision is made, the rest is fairly easy. If +the correct implementation is in C++, then the lowest implementation of +the method in the C++ inheritance chain is called explicitly. If the +correct implementation is in Perl, the Perl API is used to call the +method of the underlying Perl object (after which the usual virtual +method resolution in Perl automatically finds the right +implementation). +
+ ++Now how does the director decide which language should handle the method call? +The basic rule is to handle the method in Perl, unless there's a good +reason not to. The reason for this is simple: Perl has the most +"extended" implementation of the method. This assertion is guaranteed, +since at a minimum the Perl proxy class implements the method. If the +method in question has been extended by a class derived from the proxy +class, that extended implementation will execute exactly as it should. +If not, the proxy class will route the method call into a C wrapper +function, expecting that the method will be resolved in C++. The wrapper +will call the virtual method of the C++ instance, and since the director +extends this the call will end up right back in the director method. Now +comes the "good reason not to" part. If the director method were to blindly +call the Perl method again, it would get stuck in an infinite loop. We avoid this +situation by adding special code to the C wrapper function that tells +the director method to not do this. The C wrapper function compares the +pointer to the Perl object that called the wrapper function to the +pointer stored by the director. If these are the same, then the C +wrapper function tells the director to resolve the method by calling up +the C++ inheritance chain, preventing an infinite loop. +
+ ++One more point needs to be made about the relationship between director +classes and proxy classes. When a proxy class instance is created in +Perl, SWIG creates an instance of the original C++ class. +This is exactly what happens without directors and +is true even if directors are enabled for the particular class in +question. When a class derived from a proxy class is created, +however, SWIG then creates an instance of the corresponding C++ director +class. The reason for this difference is that user-defined subclasses +may override or extend methods of the original class, so the director +class is needed to route calls to these methods correctly. For +unmodified proxy classes, all methods are ultimately implemented in C++ +so there is no need for the extra overhead involved with routing the +calls through Perl. +
+ +33.11.3 Ownership and object destruction
+ + ++Memory management issues are slightly more complicated with directors +than for proxy classes alone. Perl instances hold a pointer to the +associated C++ director object, and the director in turn holds a pointer +back to a Perl object. By default, proxy classes own their C++ +director object and take care of deleting it when they are garbage +collected. +
+ ++This relationship can be reversed by calling the special +DISOWN() method of the proxy class. After calling this +method the director +class increments the reference count of the Perl object. When the +director class is deleted it decrements the reference count. Assuming no +outstanding references to the Perl object remain, the Perl object +will be destroyed at the same time. This is a good thing, since +directors and proxies refer to each other and so must be created and +destroyed together. Destroying one without destroying the other will +likely cause your program to segfault. +
+ ++Also note that due to the proxy implementation, the DESTROY() +method on directors can be called for several reasons, many of which +have little to do with the teardown of an object instance. To help +disambiguate this, a second argument is added to the DESTROY() +call when a C++ director object is being released. So, to avoid running +your clean-up code when an object is not really going away, or after it +has already been reclaimed, it is suggested that custom destructors in +Perl subclasses looks something like: +
+ +++ + ++sub DESTROY { + my($self, $final) = @_; + if($final) { + # real teardown code + } + shift->SUPER::DESTROY(@_); +} ++33.11.4 Exception unrolling
+ + ++With directors routing method calls to Perl, and proxies routing them +to C++, the handling of exceptions is an important concern. By default, the +directors ignore exceptions that occur during method calls that are +resolved in Perl. To handle such exceptions correctly, it is necessary +to temporarily translate them into C++ exceptions. This can be done with +the %feature("director:except") directive. The following code should +suffice in most cases: +
+ +++ ++%feature("director:except") { + if ($error != NULL) { + throw Swig::DirectorMethodException(); + } +} +++This code will check the Perl error state after each method call from +a director into Perl, and throw a C++ exception if an error occurred. +This exception can be caught in C++ to implement an error handler. +
+ ++It may be the case that a method call originates in Perl, travels up +to C++ through a proxy class, and then back into Perl via a director +method. If an exception occurs in Perl at this point, it would be nice +for that exception to find its way back to the original caller. This can +be done by combining a normal %exception directive with the +director:except handler shown above. Here is an example of a +suitable exception handler: +
+ +++ ++%exception { + try { $action } + catch (Swig::DirectorException &e) { SWIG_fail; } +} +++The class Swig::DirectorException used in this example is actually a +base class of Swig::DirectorMethodException, so it will trap this +exception. Because the Perl error state is still set when +Swig::DirectorMethodException is thrown, Perl will register the +exception as soon as the C wrapper function returns. +
+ +33.11.5 Overhead and code bloat
+ + ++Enabling directors for a class will generate a new director method for +every virtual method in the class' inheritance chain. This alone can +generate a lot of code bloat for large hierarchies. Method arguments +that require complex conversions to and from target language types can +result in large director methods. For this reason it is recommended that +you selectively enable directors only for specific classes that are +likely to be extended in Perl and used in C++. +
+ ++Compared to classes that do not use directors, the call routing in the +director methods does add some overhead. In particular, at least one +dynamic cast and one extra function call occurs per method call from +Perl. Relative to the speed of Perl execution this is probably +completely negligible. For worst case routing, a method call that +ultimately resolves in C++ may take one extra detour through Perl in +order to ensure that the method does not have an extended Perl +implementation. This could result in a noticeable overhead in some cases. +
+ ++Although directors make it natural to mix native C++ objects with Perl +objects (as director objects) via a common base class pointer, one +should be aware of the obvious fact that method calls to Perl objects +will be much slower than calls to C++ objects. This situation can be +optimized by selectively enabling director methods (using the %feature +directive) for only those methods that are likely to be extended in +Perl. +
+ +33.11.6 Typemaps
+ + ++Typemaps for input and output of most of the basic types from director +classes have been written. These are roughly the reverse of the usual +input and output typemaps used by the wrapper code. The typemap +operation names are 'directorin', 'directorout', and 'directorargout'. +The director code does not currently use any of the other kinds of typemaps. +It is not clear at this point which kinds are appropriate and +need to be supported. +
+ + diff --git a/Doc/Manual/Php.html b/Doc/Manual/Php.html index 78ee6ea..8c483b7 100644 --- a/Doc/Manual/Php.html +++ b/Doc/Manual/Php.html @@ -1,13 +1,13 @@ - - +SWIG and PHP + -32 SWIG and PHP
+34 SWIG and PHP
@@ -362,7 +378,7 @@ print $s; # The value of $s was not changed. --> -@@ -25,10 +25,11 @@
@@ -79,7 +80,7 @@ your extension into php directly, you will need the complete PHP source tree available. -- Pointers and References
- Structures and C++ classes
- PHP Pragmas, Startup and Shutdown code
32.1 Generating PHP Extensions
+34.1 Generating PHP Extensions
@@ -113,9 +114,7 @@ more detail in section 27.2.6.
The usual (and recommended) way is to build the extension as a separate dynamically loaded module (which is supported by all modern operating -systems). You can then specify that this be loaded -automatically in php.ini or load it explicitly for any script which -needs it. +systems).
@@ -126,7 +125,7 @@ and it doesn't play nicely with package system. We don't recommend this approach, or provide explicit support for it.
-32.1.1 Building a loadable extension
+34.1.1 Building a loadable extension
@@ -137,42 +136,59 @@ least work for Linux though):
-- gcc `php-config --includes` -fpic -c example_wrap.c - gcc -shared example_wrap.o -o example.so + gcc `php-config --includes` -fpic -c example_wrap.c example.c + gcc -shared example_wrap.o example.o -o example.so32.1.2 Using PHP Extensions
+34.1.2 Using PHP Extensions
-To test the extension from a PHP script, you need to load it first. You -can load it for every script by adding this line to the [PHP] section of +To test the extension from a PHP script, you first need to tell PHP to +load it. To do this, add a line like this to the [PHP] section of php.ini:
- extension=/path/to/modulename.so + extension=/path/to/modulename.so-Alternatively, you can load it explicitly only for scripts which need it -by adding this line to the start of each such PHP script:: +If the module is in PHP's default extension directory, you can omit the path. +
+ ++For some SAPIs (for example, the CLI SAPI) you can instead use the +dl() function to load +an extension at run time, by adding a like like this to the start of each +PHP script which uses your extension:
- dl("/path/to/modulename.so"); // Load the module + dl("/path/to/modulename.so"); // Load the module-SWIG also generates a php module, which -attempts to do the dl() call for you: +But note that this doesn't work when running PHP through a webserver in PHP5.3 +and later - you'll need to use extension in php.ini as +described above. +
+ ++The PHP module which SWIG generates will also attempt to do the dl() +call for you if the extension isn't already loaded:
-- include("example.php"); + include("example.php");32.2 Basic PHP interface
++This PHP module also defines the PHP classes for the wrapped API, so you'll +almost certainly want to include it anyway. +
+ +34.2 Basic PHP interface
@@ -183,7 +199,7 @@ other symbols unless care is taken to %rename them. At present SWIG doesn't have support for the namespace feature added in PHP 5.3.
-32.2.1 Constants
+34.2.1 Constants
@@ -220,9 +236,9 @@ echo "E = " . E . "\n";
There's one peculiarity of how constants work in PHP which it is useful to note (this is not specific to SWIG though) - if you try to use an undeclared -constant, PHP will issue a warning and then expand the constant to a string -version of the constant's name. The warning will often be missed though as -if you're using PHP in a webserver, it will probably end up in error.log or +constant, PHP will emit a notice and then expand the constant to a string +version of the constant's name. Unfortunately it is easy to miss the notice +if you're using PHP in a webserver, as it will probably end up in error.log or similar.
@@ -233,7 +249,7 @@ For example,@@ -246,9 +262,9 @@ accessed incorrectly in PHP, include("example.php"); if(EASY_TO_MISPEL) { - .... + ... } else { - .... + ... } @@ -260,7 +276,7 @@ is treated as true by the if test, when the value of the intended constant would be treated as false! -%module example -#define EASY_TO_MISPELL 0 +#define EASY_TO_MISPELL 032.2.2 Global Variables
+34.2.2 Global Variables
@@ -287,7 +303,7 @@ is accessed as follows:
@@ -309,7 +325,7 @@ undefined. At this time SWIG does not support custom accessor methods. -include("example.php"); print seki_get(); -seki_set( seki_get() * 2); # The C variable is now 4. +seki_set( seki_get() * 2); # The C variable is now 4. print seki_get();32.2.3 Functions
+34.2.3 Functions
@@ -332,7 +348,7 @@ Will be accessed in PHP like this : include("example.php"); $a = foo(2); $b = bar(3.5, -1.5); -$c = bar(3.5); # Use default argument for 2nd parameter +$c = bar(3.5); # Use default argument for 2nd parameter
32.2.4 Overloading
+34.2.4 Overloading
@@ -418,7 +434,7 @@ taking the integer argument.
--> -32.2.5 Pointers and References
+34.2.5 Pointers and References
@@ -503,13 +519,20 @@ echo "The sum $in1 + $in2 = $result\n"; Because PHP has a native concept of reference, it may seem more natural to the PHP developer to use references to pass pointers. To enable this, one needs to include phppointers.i which defines the -named typemap REFERENCE. +named typemap REF. +
+ ++Prior to SWIG 3.0, the REF typemaps relied on PHP's call-time +pass-by-reference, which was deprecated in PHP 5.3 and removed in PHP 5.4. +So if you use these REF typemaps, you should ensure that SWIG≥3.0 is +used to generate wrappers from your interface file.
-However, this relies on call-time pass-by-reference, which has been -deprecated in PHP for some time, and was finally removed in PHP 5.4. -So you should avoid creating new wrappers which rely on this approach. +In case you write your own typemaps, SWIG supports an attribute called +byref: if you set that, then SWIG will make sure that the generated +wrapper function will want the input parameter as a reference.
-@@ -532,7 +555,7 @@ include("example.php"); $in1 = 3; $in2 = 5; $result = 0; -add(&$in1,&$in2,&$result); +add($in1,$in2,$result); echo "The sum $in1 + $in2 = $result\n"; ?> @@ -556,7 +579,7 @@ PHP in a number of ways: by using unset on an existing variable, or assigning NULL to a variable. -32.2.6 Structures and C++ classes
+34.2.6 Structures and C++ classes
@@ -576,10 +599,10 @@ This interface file class Vector { public: - double x,y,z; - Vector(); - ~Vector(); - double magnitude(); + double x,y,z; + Vector(); + ~Vector(); + double magnitude(); }; struct Complex { @@ -617,7 +640,7 @@ Would be used in the following way from PHP5: Member variables and methods are accessed using the -> operator.
-32.2.6.1 Using -noproxy
+34.2.6.1 Using -noproxy
@@ -643,7 +666,7 @@ Complex_im_set($obj,$d); Complex_im_get($obj);
32.2.6.2 Constructors and Destructors
+34.2.6.2 Constructors and Destructors
@@ -684,7 +707,7 @@ the programmer can either reassign the variable or call unset($v)
-32.2.6.3 Static Member Variables
+34.2.6.3 Static Member Variables
@@ -699,7 +722,7 @@ returns the current value of the class variable. For example %module example class Ko { - static int threats; + static int threats; }; @@ -727,7 +750,7 @@ Ko::threats(10); echo "There have now been " . Ko::threats() . " threats\n"; -
32.2.6.4 Static Member Functions
+34.2.6.4 Static Member Functions
@@ -749,7 +772,25 @@ Ko::threats(); -
32.2.7 PHP Pragmas, Startup and Shutdown code
+34.2.6.5 Specifying Implemented Interfaces
+ + ++PHP supports the concept of abstract interfaces which a class can implement. +Since SWIG 3.0.3, you can tell SWIG that a wrapped class (for example +
+ +MyIterator
) implements theIterator
interface like +so: ++ ++%typemap("phpinterfaces") MyIterator "Iterator"; ++If there are multiple interfaces, just list them separated by commas. +
+ +34.2.7 PHP Pragmas, Startup and Shutdown code
@@ -837,7 +878,7 @@ The %rinit and %rshutdown statements are very similar but inse into the request init (PHP_RINIT_FUNCTION) and request shutdown (PHP_RSHUTDOWN_FUNCTION) code respectively.
-32.3 Cross language polymorphism
+34.3 Cross language polymorphism
@@ -872,7 +913,7 @@ wrapper functions takes care of all the cross-language method routing transparently.
-32.3.1 Enabling directors
+34.3.1 Enabling directors
@@ -961,7 +1002,7 @@ class MyFoo extends Foo { -
32.3.2 Director classes
+34.3.2 Director classes
@@ -1041,7 +1082,7 @@ so there is no need for the extra overhead involved with routing the calls through PHP. -32.3.3 Ownership and object destruction
+34.3.3 Ownership and object destruction
@@ -1097,7 +1138,7 @@ In this example, we are assuming that FooContainer will take care of deleting all the Foo pointers it contains at some point.
-32.3.4 Exception unrolling
+34.3.4 Exception unrolling
@@ -1156,7 +1197,7 @@ Swig::DirectorMethodException is thrown, PHP will register the exception as soon as the C wrapper function returns.
-32.3.5 Overhead and code bloat
+34.3.5 Overhead and code bloat
@@ -1189,7 +1230,7 @@ optimized by selectively enabling director methods (using the %feature directive) for only those methods that are likely to be extended in PHP.
-32.3.6 Typemaps
+34.3.6 Typemaps
@@ -1203,7 +1244,7 @@ need to be supported.
-32.3.7 Miscellaneous
+34.3.7 Miscellaneous
Director typemaps for STL classes are mostly in place, and hence you diff --git a/Doc/Manual/Pike.html b/Doc/Manual/Pike.html index 8c1eb2d..22ab4e2 100644 --- a/Doc/Manual/Pike.html +++ b/Doc/Manual/Pike.html @@ -1,12 +1,13 @@ - +
SWIG and Pike + -33 SWIG and Pike
+35 SWIG and Pike
-@@ -46,10 +47,10 @@ least, make sure you read the "SWIG Basics" chapter.
-33.1 Preliminaries
+35.1 Preliminaries
-33.1.1 Running SWIG
+35.1.1 Running SWIG
@@ -94,7 +95,7 @@ can use the -o option:
-$ swig -pike -o pseudonym.c example.i33.1.2 Getting the right header files
+35.1.2 Getting the right header files
@@ -114,7 +115,7 @@ You're looking for files with the names global.h, program.h and so on.
-33.1.3 Using your module
+35.1.3 Using your module
@@ -129,10 +130,10 @@ Pike v7.4 release 10 running Hilfe v3.5 (Incremental Pike Frontend) (1) Result: 24
33.2 Basic C/C++ Mapping
+35.2 Basic C/C++ Mapping
-33.2.1 Modules
+35.2.1 Modules
@@ -143,7 +144,7 @@ concerned), SWIG's %module directive doesn't really have any significance.
-33.2.2 Functions
+35.2.2 Functions
@@ -168,7 +169,7 @@ exactly as you'd expect it to: (1) Result: 24 -
33.2.3 Global variables
+35.2.3 Global variables
@@ -197,7 +198,7 @@ will result in two functions, Foo_get() and Foo_set(): (3) Result: 3.141590 -
33.2.4 Constants and enumerated types
+35.2.4 Constants and enumerated types
@@ -205,7 +206,7 @@ Enumerated types in C/C++ declarations are wrapped as Pike constants, not as Pike enums.
-33.2.5 Constructors and Destructors
+35.2.5 Constructors and Destructors
@@ -213,7 +214,7 @@ Constructors are wrapped as create() methods, and destructors are wrapped as destroy() methods, for Pike classes.
-33.2.6 Static Members
+35.2.6 Static Members
diff --git a/Doc/Manual/Preface.html b/Doc/Manual/Preface.html index d17dc22..3b654a6 100644 --- a/Doc/Manual/Preface.html +++ b/Doc/Manual/Preface.html @@ -1,12 +1,13 @@ - +
Preface + -1 Preface
+1 Preface
@@ -35,7 +36,7 @@ -
-1.1 Introduction
+1.1 Introduction
@@ -58,7 +59,7 @@ has since evolved into a general purpose tool that is used in a wide variety of applications--in fact almost anything where C/C++ programming is involved. -
1.2 SWIG Versions
+1.2 SWIG Versions
@@ -70,7 +71,7 @@ An official stable version was released along with the decision to make SWIG license changes and this gave rise to version 2.0.0 in 2010.
-1.3 SWIG License
+1.3 SWIG License
@@ -86,7 +87,7 @@ under license terms of the user's choice/requirements and at the same time the S source was placed under the GNU General Public License version 3.
-1.4 SWIG resources
+1.4 SWIG resources
@@ -126,7 +127,7 @@ about this can be obtained at: -
1.5 Prerequisites
+1.5 Prerequisites
@@ -151,7 +152,7 @@ However, this isn't meant to be a tutorial on C++ programming. For many of the gory details, you will almost certainly want to consult a good C++ reference. If you don't program in C++, you may just want to skip those parts of the manual. -
1.6 Organization of this manual
+1.6 Organization of this manual
@@ -163,7 +164,7 @@ can probably skip to that chapter and find almost everything you need to know.
-1.7 How to avoid reading the manual
+1.7 How to avoid reading the manual
@@ -175,7 +176,7 @@ The SWIG distribution also comes with a large directory of examples that illustrate different topics.
-1.8 Backwards compatibility
+1.8 Backwards compatibility
@@ -211,7 +212,7 @@ Note: The version symbol is not defined in the generated SWIG wrapper file. The SWIG preprocessor has defined SWIG_VERSION since SWIG-1.3.11.
-1.9 Release notes
+1.9 Release notes
@@ -220,7 +221,7 @@ contain, respectively, detailed release notes for the current version, detailed release notes for previous releases and summary release notes from SWIG-1.3.22 onwards.
-1.10 Credits
+1.10 Credits
@@ -233,7 +234,7 @@ who have made contributions at all levels over time. Contributors are mentioned either in the COPYRIGHT file or CHANGES files shipped with SWIG or in submitted bugs.
-1.11 Bug reports
+1.11 Bug reports
@@ -248,24 +249,31 @@ used, and any important pieces of the SWIG generated wrapper code. We can only fix bugs if we know about them.
-1.12 Installation
+1.12 Installation
-1.12.1 Windows installation
+1.12.1 Windows installation
-Please see the dedicated Windows chapter for instructions on installing +Please see the dedicated Windows chapter for instructions on installing SWIG on Windows and running the examples. The Windows distribution is called swigwin and includes a prebuilt SWIG executable, swig.exe, included in the top level directory. Otherwise it is exactly the same as the main SWIG distribution. There is no need to download anything else.
-1.12.2 Unix installation
+1.12.2 Unix installation
+These installation instructions are for using the distributed tarball, +for example, swig-3.0.8.tar.gz. +If you wish to build and install from source on Github, extra steps are required. +Please see the Bleeding Edge page on the SWIG website. +
+ +You must use GNU make to build and install SWIG.
@@ -332,7 +340,7 @@ be configured with a subset of target languages. SWIG used to include a set of runtime libraries for some languages for working with multiple modules. These are no longer built during the installation stage. However, users can build them just like any wrapper module as described in -the Modules chapter. +the Modules chapter. The CHANGES file shipped with SWIG in the top level directory also lists some examples which build the runtime library. @@ -350,7 +358,7 @@ a number of packages to be installed. Full instructions at1.12.3 Macintosh OS X installation
+1.12.3 Macintosh OS X installation
@@ -370,7 +378,7 @@ installation of software you might have. However, this is generally not the rec technique for building larger extension modules. Instead, you should utilize Darwin's two-level namespaces. Some details about this can be found here -http://developer.apple.com/documentation/ReleaseNotes/DeveloperTools/TwoLevelNamespaces.html. +Understanding Two-Level Namespaces.
@@ -378,7 +386,7 @@ Darwin's two-level namespaces. Some details about this can be found here Needless to say, you might have to experiment a bit to get things working at first. -1.12.4 Testing
+1.12.4 Testing
@@ -432,7 +440,7 @@ have many different target languages installed and a slow machine, it might take more than an hour to run the test-suite.
-1.12.5 Examples
+1.12.5 Examples
diff --git a/Doc/Manual/Preprocessor.html b/Doc/Manual/Preprocessor.html index 8fcbe92..2538f8f 100644 --- a/Doc/Manual/Preprocessor.html +++ b/Doc/Manual/Preprocessor.html @@ -1,12 +1,13 @@ - +
SWIG Preprocessor + -7 Preprocessing
+8 Preprocessing
-@@ -37,7 +38,7 @@ However, a number of modifications and enhancements have been made. This chapter describes some of these modifications. -
-7.1 File inclusion
+8.1 File inclusion
@@ -63,7 +64,7 @@ By default, the #include is ignored unless you run SWIG with the is that you often don't want SWIG to try and wrap everything included in standard header system headers and auxiliary files. -
7.2 File imports
+8.2 File imports
@@ -92,7 +93,7 @@ The -importall directive tells SWIG to follow all #include sta as imports. This might be useful if you want to extract type definitions from system header files without generating any wrappers. -
7.3 Conditional Compilation
+8.3 Conditional Compilation
@@ -115,9 +116,12 @@ SWIGCLISP Defined when using CLISP SWIGCSHARP Defined when using C# SWIGGUILE Defined when using Guile SWIGJAVA Defined when using Java +SWIGJAVASCRIPT Defined when using Javascript +SWIG_JAVASCRIPT_JSC Defined when using Javascript for JavascriptCore +SWIG_JAVASCRIPT_V8 Defined when using Javascript for v8 or node.js SWIGLUA Defined when using Lua SWIGMODULA3 Defined when using Modula-3 -SWIGMZSCHEME Defined when using Mzscheme +SWIGMZSCHEME Defined when using Mzscheme SWIGOCAML Defined when using Ocaml SWIGOCTAVE Defined when using Octave SWIGPERL Defined when using Perl @@ -126,6 +130,7 @@ SWIGPIKE Defined when using Pike SWIGPYTHON Defined when using Python SWIGR Defined when using R SWIGRUBY Defined when using Ruby +SWIGSCILAB Defined when using Scilab SWIGSEXP Defined when using S-expressions SWIGTCL Defined when using Tcl SWIGXML Defined when using XML @@ -152,7 +157,7 @@ SWIG (except for the symbol `SWIG' which is only defined within the SWIG compiler).
-7.4 Macro Expansion
+8.4 Macro Expansion
@@ -207,7 +212,7 @@ like #x. This is a non-standard SWIG extension.
7.5 SWIG Macros
+8.5 SWIG Macros
@@ -253,7 +258,7 @@ many of SWIG's advanced features and libraries are built using this mechanism (s support).
-7.6 C99 and GNU Extensions
+8.6 C99 and GNU Extensions
@@ -309,14 +314,14 @@ interface building. However, they are used internally to implement a number of SWIG directives and are provided to make SWIG more compatible with C99 code.
-7.7 Preprocessing and delimiters
+8.7 Preprocessing and delimiters
The preprocessor handles { }, " " and %{ %} delimiters differently.
-7.7.1 Preprocessing and %{ ... %} & " ... " delimiters
+8.7.1 Preprocessing and %{ ... %} & " ... " delimiters
@@ -341,7 +346,7 @@ the contents of the %{ ... %} block are copied without modification to the output (including all preprocessor directives).
-7.7.2 Preprocessing and { ... } delimiters
+8.7.2 Preprocessing and { ... } delimiters
@@ -383,7 +388,7 @@ to actually go into the wrapper file, prefix the preprocessor directives with
-% and leave the preprocessor directive in the code. 7.8 Preprocessor and Typemaps
+8.8 Preprocessor and Typemaps
@@ -454,7 +459,7 @@ would generate
7.9 Viewing preprocessor output
+8.9 Viewing preprocessor output
@@ -464,7 +469,7 @@ Instead the results after the preprocessor has run are displayed. This might be useful as an aid to debugging and viewing the results of macro expansions.
-7.10 The #error and #warning directives
+8.10 The #error and #warning directives
diff --git a/Doc/Manual/Python.html b/Doc/Manual/Python.html index 6a22738..ce7f9fe 100644 --- a/Doc/Manual/Python.html +++ b/Doc/Manual/Python.html @@ -1,12 +1,13 @@ - +
SWIG and Python + -34 SWIG and Python
+36 SWIG and Python
@@ -135,7 +157,7 @@ very least, make sure you read the "SWIG Basics" chapter. -@@ -38,6 +39,10 @@
- C++ namespaces
- C++ templates
- C++ Smart Pointers +
- C++ reference counted objects
- Further details on the Python class interface @@ -74,6 +79,7 @@
- Simple pointers
- Unbounded C Arrays
- String handling +
- Default arguments
- Typemaps
@@ -105,11 +111,27 @@
- %feature("docstring")
- Python Packages +
- Python 3 Support
34.1 Overview
+36.1 Overview
@@ -162,10 +184,10 @@ described followed by a discussion of low-level implementation details.
-34.2 Preliminaries
+36.2 Preliminaries
-34.2.1 Running SWIG
+36.2.1 Running SWIG
@@ -187,7 +209,7 @@ int fact(int n);
-The #define SWIG_FILE_WITH_INIT line inserts a macro that specifies that the +The #define SWIG_FILE_WITH_INIT line inserts a macro that specifies that the resulting C file should be built as a python extension, inserting the module init code. This .i file wraps the following simple C file:
@@ -263,13 +285,13 @@ The following sections have further practical examples and details on how you might go about compiling and using the generated files. -34.2.2 Using distutils
+36.2.2 Using distutils
The preferred approach to building an extension module for python is to compile it with distutils, which comes with all recent versions of python -(Distutils Docs). +(Distutils Docs).
@@ -355,7 +377,7 @@ This same approach works on all platforms if the appropriate compiler is install can even build extensions to the standard Windows Python using MingGW)
-34.2.3 Hand compiling a dynamic module
+36.2.3 Hand compiling a dynamic module
@@ -388,7 +410,7 @@ of the module prefixed by an underscore. If the name of your module is "_example.so" or "_examplemodule.so". The name of the module is specified using the %module directive or the - -module command line option. +-module command line option.
@@ -403,7 +425,7 @@ module actually consists of two files; socket.py and
-34.2.4 Static linking
+36.2.4 Static linking
@@ -448,14 +470,14 @@ you simply do something like this:
-$ swig -python example.i +$ swig -python -lembed.i example.i $ gcc example.c example_wrap.c \ -Xlinker -export-dynamic \ - -DHAVE_CONFIG_H -I/usr/local/include/python2.1 \ - -I/usr/local/lib/python2.1/config \ - -L/usr/local/lib/python2.1/config -lpython2.1 -lm -ldl \ - -o mypython - + -DHAVE_CONFIG_H -I/usr/include/python2.7 \ + -I/usr/lib/python2.7/config-x86_64-linux-gnu \ + -I/usr/lib/python2.7/config \ + -L/usr/lib/python2.7/config -lpython2.7 -lm -ldl \ + -o mypythonYou will need to supply the same libraries that were used to build Python the first @@ -476,13 +498,13 @@ hassle in the opinion of this author).
Compatibility note: The embed.i library file is -deprecated and has not been maintained for several years. Even though it -appears to "work" with Python 2.1, no future support is guaranteed. +deprecated and has not been actively maintained for many years. Even though it +appears to "work" with Python 2.7, no future support is guaranteed. If using static linking, you might want to rely on a different approach (perhaps using distutils).
-34.2.5 Using your module
+36.2.5 Using your module
@@ -639,7 +661,7 @@ system configuration (this requires root access and you will need to read the man pages).
-34.2.6 Compilation of C++ extensions
+36.2.6 Compilation of C++ extensions
@@ -731,7 +753,7 @@ erratic program behavior. If working with lots of software components, you might want to investigate using a more formal standard such as COM.
-34.2.7 Compiling for 64-bit platforms
+36.2.7 Compiling for 64-bit platforms
@@ -768,7 +790,7 @@ and -m64 allow you to choose the desired binary format for your python extension.
-34.2.8 Building Python Extensions under Windows
+36.2.8 Building Python Extensions under Windows
@@ -776,8 +798,8 @@ Building a SWIG extension to Python under Windows is roughly similar to the process used with Unix. Using the distutils, it is essentially identical. If you have the same version of the MS compiler that Python was built with (the python2.4 and python2.5 distributed by python.org -are built with Visual Studio 2003), the standard python setup.py -build should just work. +are built with Visual Studio 2003), the standard python setup.py +build should just work.
@@ -897,7 +919,7 @@ SWIG Wiki.
-34.3 A tour of basic C/C++ wrapping
+36.3 A tour of basic C/C++ wrapping
@@ -906,7 +928,7 @@ to your C/C++ code. Functions are wrapped as functions, classes are wrapped as This section briefly covers the essential aspects of this wrapping.
-34.3.1 Modules
+36.3.1 Modules
@@ -919,7 +941,7 @@ module name, make sure you don't use the same name as a built-in Python command or standard module name.
-34.3.2 Functions
+36.3.2 Functions
@@ -943,7 +965,7 @@ like you think it does: >>> -
34.3.3 Global variables
+36.3.3 Global variables
@@ -1081,7 +1103,7 @@ that starts with a leading underscore. SWIG does not create cvar if there are no global variables in a module.
-34.3.4 Constants and enums
+36.3.4 Constants and enums
@@ -1121,7 +1143,7 @@ other object. Unfortunately, there is no easy way for SWIG to generate code that prevents this. You will just have to be careful.
-34.3.5 Pointers
+36.3.5 Pointers
@@ -1147,7 +1169,7 @@ When wrapped, you will be able to use the functions in a natural way from Python
->>> import example ->>> f = example.fopen("junk","w") +>>> f = example.fopen("junk", "w") >>> example.fputs("Hello World\n", f) >>> example.fclose(f)@@ -1262,7 +1284,7 @@ C-style cast may return a bogus result whereas as the C++-style cast will return None if the conversion can't be performed. -34.3.6 Structures
+36.3.6 Structures
@@ -1272,7 +1294,7 @@ a very natural interface. For example,
@@ -1451,7 +1473,7 @@ everything works just like you would expect. For example:struct Vector { - double x,y,z; + double x,y,z; };34.3.7 C++ classes
+36.3.7 C++ classes
@@ -1540,7 +1562,7 @@ they are accessed through cvar like this: -
34.3.8 C++ inheritance
+36.3.8 C++ inheritance
@@ -1595,7 +1617,7 @@ then the function spam() accepts Foo * or a pointer to any cla It is safe to use multiple inheritance with SWIG.
-34.3.9 Pointers, references, values, and arrays
+36.3.9 Pointers, references, values, and arrays
@@ -1656,7 +1678,7 @@ treated as a returning value, and it will follow the same allocation/deallocation process.
-34.3.10 C++ overloaded functions
+36.3.10 C++ overloaded functions
@@ -1779,7 +1801,7 @@ first declaration takes precedence. Please refer to the "SWIG and C++" chapter for more information about overloading.
-34.3.11 C++ operators
+36.3.11 C++ operators
@@ -1868,7 +1890,7 @@ Also, be aware that certain operators don't map cleanly to Python. For instance overloaded assignment operators don't map to Python semantics and will be ignored.
-34.3.12 C++ namespaces
+36.3.12 C++ namespaces
@@ -1935,7 +1957,7 @@ utilizes thousands of small deeply nested namespaces each with identical symbol names, well, then you get what you deserve.
-34.3.13 C++ templates
+36.3.13 C++ templates
@@ -1989,7 +2011,21 @@ Some more complicated examples will appear later.
-34.3.14 C++ Smart Pointers
+36.3.14 C++ Smart Pointers
+ + +36.3.14.1 The shared_ptr Smart Pointer
+ + ++The C++11 standard provides std::shared_ptr which was derived from the Boost +implementation, boost::shared_ptr. +Both of these are available for Python in the SWIG library and usage is outlined +in the shared_ptr smart pointer library section. +
+ + +36.3.14.2 Generic Smart Pointers
@@ -2073,7 +2109,7 @@ simply use the __deref__() method. For example: -
34.3.15 C++ reference counted objects
+36.3.15 C++ reference counted objects
@@ -2082,7 +2118,7 @@ Python examples of memory management using referencing counting.
-34.4 Further details on the Python class interface
+36.4 Further details on the Python class interface
@@ -2105,7 +2141,7 @@ the -builtin option are in the Built-in section.
-34.4.1 Proxy classes
+36.4.1 Proxy classes
@@ -2162,15 +2198,15 @@ for Python 2.2): import _example class Foo(object): - def __init__(self): - self.this = _example.new_Foo() - self.thisown = 1 - def __del__(self): - if self.thisown: - _example.delete_Foo(self.this) - def spam(self,arg1): - return _example.Foo_spam(self.this,arg1) - x = property(_example.Foo_x_get, _example.Foo_x_set) + def __init__(self): + self.this = _example.new_Foo() + self.thisown = 1 + def __del__(self): + if self.thisown: + _example.delete_Foo(self.this) + def spam(self,arg1): + return _example.Foo_spam(self.this,arg1) + x = property(_example.Foo_x_get, _example.Foo_x_set) @@ -2194,7 +2230,7 @@ you can attach new Python methods to the class and you can even inherit from it by Python built-in types until Python 2.2).
-34.4.2 Built-in Types
+36.4.2 Built-in Types
@@ -2212,9 +2248,9 @@ like in a proxy class:
@@ -2238,7 +2274,7 @@ please refer to the python documentation:class Foo(object): - def __init__(self): - self.this = _example.new_Foo() - self.thisown = 1 + def __init__(self): + self.this = _example.new_Foo() + self.thisown = 1http://docs.python.org/extending/newtypes.html
-34.4.2.1 Limitations
+36.4.2.1 Limitations
Use of the -builtin option implies a couple of limitations: @@ -2306,11 +2342,11 @@ private:
@@ -2406,7 +2442,7 @@ assert(issubclass(B.Derived, A.Base)) --class MyPyException (Exception) : - def __init__(self, msg, *args) : +class MyPyException(Exception): + def __init__(self, msg, *args): Exception.__init__(self, *args) self.myexc = MyException(msg) - def what (self) : + def what(self): return self.myexc.what()34.4.2.2 Operator overloads -- use them!
+36.4.2.2 Operator overloads -- use them!
The entire justification for the -builtin option is improved @@ -2507,7 +2543,7 @@ structs.
-34.4.3 Memory management
+36.4.3 Memory management
NOTE: Although this section refers to proxy objects, everything here also applies @@ -2702,7 +2738,7 @@ It is also possible to deal with situations like this using typemaps--an advanced topic discussed later.
-34.4.4 Python 2.2 and classic classes
+36.4.4 Python 2.2 and classic classes
@@ -2712,7 +2748,7 @@ in Python-2.2, an entirely new type of class system was introduced. This new-style class system offers many enhancements including static member functions, properties (managed attributes), and class methods. Details about all of these changes can be found on www.python.org and is not repeated here. +href="https://www.python.org">www.python.org and is not repeated here.
@@ -2727,7 +2763,7 @@ old-style classes are used instead.
This dual-nature of the wrapper code means that you can create extension modules with SWIG and those modules will work with all versions of Python -ranging from Python-1.4 to the very latest release. Moreover, the wrappers take +ranging from Python-2.0 to the very latest release. Moreover, the wrappers take advantage of Python-2.2 features when available.
@@ -2739,7 +2775,7 @@ class itself. In Python-2.1 and earlier, they have to be accessed as a global function or through an instance (see the earlier section). -34.5 Cross language polymorphism
+36.5 Cross language polymorphism
@@ -2773,7 +2809,7 @@ proxy classes, director classes, and C wrapper functions takes care of all the cross-language method routing transparently.
-34.5.1 Enabling directors
+36.5.1 Enabling directors
@@ -2834,6 +2870,7 @@ the methods one() and two() (but not three()): class Foo { public: Foo(int foo); + virtual ~Foo(); virtual void one(); virtual void two(); }; @@ -2854,16 +2891,17 @@ then at the python side you can define import mymodule class MyFoo(mymodule.Foo): - def __init__(self, foo): - mymodule.Foo(self, foo) + def __init__(self, foo): + mymodule.Foo.__init__(self, foo) +# super().__init__(foo) # Alternative construction for Python3 - def one(self): - print "one from python" + def one(self): + print "one from python" -
34.5.2 Director classes
+36.5.2 Director classes
@@ -2945,7 +2983,7 @@ so there is no need for the extra overhead involved with routing the calls through Python. -34.5.3 Ownership and object destruction
+36.5.3 Ownership and object destruction
@@ -3012,7 +3050,7 @@ deleting all the Foo pointers it contains at some point. Note that no hard references to the Foo objects remain in Python.
-34.5.4 Exception unrolling
+36.5.4 Exception unrolling
@@ -3071,7 +3109,7 @@ Swig::DirectorMethodException is thrown, Python will register the exception as soon as the C wrapper function returns.
-34.5.5 Overhead and code bloat
+36.5.5 Overhead and code bloat
@@ -3105,7 +3143,7 @@ directive) for only those methods that are likely to be extended in Python.
-34.5.6 Typemaps
+36.5.6 Typemaps
@@ -3119,7 +3157,7 @@ need to be supported.
-34.5.7 Miscellaneous
+36.5.7 Miscellaneous
@@ -3166,7 +3204,7 @@ methods that return const references.
-34.6 Common customization features
+36.6 Common customization features
@@ -3179,7 +3217,7 @@ This section describes some common SWIG features that are used to improve your the interface to an extension module.
-34.6.1 C/C++ helper functions
+36.6.1 C/C++ helper functions
@@ -3260,7 +3298,7 @@ hard to implement. It is possible to clean this up using Python code, typemaps, customization features as covered in later sections.
-34.6.2 Adding additional Python code
+36.6.2 Adding additional Python code
@@ -3361,6 +3399,30 @@ print("Loading", "Whizz", "Bang", sep=' ... ') +
When using %pythoncode and %pythonbegin you generally +want to make sure that the block is delimited by %{ and %}. +If you delimit it with { and } then any lines with a +leading # will be handled by SWIG as preprocessor directives, when +you probably meant them as Python comments. Prior to SWIG 3.0.3, invalid +preprocessor directives were silently ignored, so generally using the wrong +delimiters resulted in such comments not appearing in the generated output +(though a comment starting with a valid preprocessor directive could cause +problems, for example: # error handling). SWIG 3.0.3 and later report +an error for invalid preprocessor directives, so you may have to update +existing interface files to delimit blocks of Python code correctly.
+ +As an alternative to providing a block containing Python code, you can +include python code from a file. The code is inserted exactly as in the +file, so this avoids any issues with the SWIG preprocessor. It's a good +approach if you have a non-trivial chunk of Python code to insert. To +use this feature you specify a filename in double quotes, for example:
+ ++++%pythoncode "somecode.py" ++Sometimes you may want to replace or modify the wrapper function that SWIG creates in the proxy .py file. The Python module in SWIG provides some features that enable you to do this. First, to @@ -3383,7 +3445,7 @@ def bar(*args): class Foo { public: int bar(int x); -} +}; @@ -3420,7 +3482,7 @@ proxy, just before the return statement. class Foo { public: int bar(int x); -} +}; @@ -3449,7 +3511,7 @@ SWIG version 1.3.28 you can use the directive forms class Foo { public: int bar(int x); -} +}; @@ -3479,7 +3541,7 @@ class Foo { public: int bar(int x); int bar(); -} +}; @@ -3488,7 +3550,7 @@ The same applies for overloaded constructors.
-34.6.3 Class extension with %extend
+36.6.3 Class extension with %extend
@@ -3577,7 +3639,7 @@ Vector(12,14,16) in any way---the extensions only show up in the Python interface.
-34.6.4 Exception handling with %exception
+36.6.4 Exception handling with %exception
@@ -3703,7 +3765,7 @@ The language-independent exception.i library file can also be used to raise exceptions. See the SWIG Library chapter.
-34.7 Tips and techniques
+36.7 Tips and techniques
@@ -3713,7 +3775,7 @@ strings, binary data, and arrays. This chapter discusses the common techniques solving these problems.
-34.7.1 Input and output parameters
+36.7.1 Input and output parameters
@@ -3926,7 +3988,7 @@ void foo(Bar *OUTPUT); may not have the intended effect since typemaps.i does not define an OUTPUT rule for Bar.
-34.7.2 Simple pointers
+36.7.2 Simple pointers
@@ -3995,7 +4057,7 @@ If you replace %pointer_functions() by %pointer_class(type,name)SWIG Library chapter for further details.
-34.7.3 Unbounded C Arrays
+36.7.3 Unbounded C Arrays
@@ -4057,7 +4119,7 @@ well suited for applications in which you need to create buffers, package binary data, etc.
-34.7.4 String handling
+36.7.4 String handling
@@ -4126,7 +4188,107 @@ If you need to return binary data, you might use the also be used to extra binary data from arbitrary pointers.
-34.8 Typemaps
+ +36.7.5 Default arguments
+ + ++C++ default argument code generation is documented in the main +Default arguments section. +There is also an optional Python specific feature that can be used called the python:cdefaultargs +feature flag. +By default, SWIG attempts to convert C++ default argument values +into Python values and generates code into the Python layer containing these values. +For example: +
+ +++ ++struct CDA { + int fff(int a = 1, bool b = false); +}; +++From Python this can be called as follows: +
+ +++ ++>>> CDA().fff() # C++ layer receives a=1 and b=false +>>> CDA().fff(2) # C++ layer receives a=2 and b=false +>>> CDA().fff(3, True) # C++ layer receives a=3 and b=true +++The default code generation in the Python layer is: +
+ +++ ++class CDA(object): + ... + def fff(self, a=1, b=False): + return _default_args.CDA_fff(self, a, b) +++Adding the feature: +
+ +++ ++%feature("python:cdefaultargs") CDA::fff; +struct CDA { + int fff(int a = 1, bool b = false); +++results in identical behaviour when called from Python, however, it results in different code generation: +
+ +++ ++class CDA(object): + ... + def fff(self, *args): + return _default_args.CDA_fff(self, *args) +++The default arguments are obtained in the C++ wrapper layer instead of the Python layer. +Some code generation modes are quite different, eg -builtin and -fastproxy, +and are unaffected by python:cdefaultargs as the default values are always obtained from the C++ layer. +
+ ++Note that not all default arguments can be converted into a Python equivalent. +When SWIG does not convert them, it will generate code to obtain them from the C++ layer as if +python:cdefaultargs was specified. +This will happen if just one argument cannot be converted into a Python equivalent. +This occurs typically when the argument is not fully numeric, such as int(1): +
+ +++ ++struct CDA { + int fff(int a = int(1), bool b = false); +}; +++Compatibility Note: SWIG-3.0.6 introduced the python:cdefaultargs feature. +Versions of SWIG prior to this varied in their ability to convert C++ default values into +equivalent Python default argument values. +
+ +36.8 Typemaps
@@ -4143,7 +4305,7 @@ Typemaps are only used if you want to change some aspect of the primitive C-Python interface or if you want to elevate your guru status.
-34.8.1 What is a typemap?
+36.8.1 What is a typemap?
@@ -4156,8 +4318,8 @@ you might define a typemap like this: %module example %typemap(in) int { - $1 = (int) PyLong_AsLong($input); - printf("Received an integer : %d\n",$1); + $1 = (int) PyLong_AsLong($input); + printf("Received an integer : %d\n",$1); } %inline %{ extern int fact(int n); @@ -4194,11 +4356,11 @@ You can refine this by supplying an optional parameter name. For example: %module example %typemap(in) int nonnegative { - $1 = (int) PyLong_AsLong($input); - if ($1 < 0) { - PyErr_SetString(PyExc_ValueError,"Expected a nonnegative value."); - return NULL; - } + $1 = (int) PyLong_AsLong($input); + if ($1 < 0) { + PyErr_SetString(PyExc_ValueError,"Expected a nonnegative value."); + return NULL; + } } %inline %{ extern int fact(int nonnegative); @@ -4220,8 +4382,8 @@ the typemap system follows typedef declarations. For example:
-%typemap(in) int n { - $1 = (int) PyLong_AsLong($input); - printf("n = %d\n",$1); + $1 = (int) PyLong_AsLong($input); + printf("n = %d\n",$1); } %inline %{ typedef int Integer; @@ -4259,7 +4421,7 @@ parameter is omitted):34.8.2 Python typemaps
+36.8.2 Python typemaps
@@ -4300,7 +4462,7 @@ a look at the SWIG library version 1.3.20 or so.
-34.8.3 Typemap variables
+36.8.3 Typemap variables
@@ -4371,7 +4533,7 @@ properly assigned. The Python name of the wrapper function being created. -
34.8.4 Useful Python Functions
+36.8.4 Useful Python Functions
@@ -4499,7 +4661,7 @@ write me -
34.9 Typemap Examples
+36.9 Typemap Examples
@@ -4508,7 +4670,7 @@ might look at the files "python.swg" and "typemaps.i" in the SWIG library.
-34.9.1 Converting Python list to a char **
+36.9.1 Converting Python list to a char **
@@ -4531,11 +4693,11 @@ object to be used as a char ** object. for (i = 0; i < size; i++) { PyObject *o = PyList_GetItem($input,i); if (PyString_Check(o)) - $1[i] = PyString_AsString(PyList_GetItem($input,i)); + $1[i] = PyString_AsString(PyList_GetItem($input,i)); else { - PyErr_SetString(PyExc_TypeError,"list must contain strings"); - free($1); - return NULL; + PyErr_SetString(PyExc_TypeError,"list must contain strings"); + free($1); + return NULL; } } $1[i] = 0; @@ -4571,7 +4733,7 @@ follows :
->>> from argv import * ->>> print_args(["Dave","Mike","Mary","Jane","John"]) +>>> print_args(["Dave", "Mike", "Mary", "Jane", "John"]) argv[0] = Dave argv[1] = Mike argv[2] = Mary @@ -4588,7 +4750,7 @@ memory allocation is used to allocate memory for the array, the the C function. -34.9.2 Expanding a Python object into multiple arguments
+36.9.2 Expanding a Python object into multiple arguments
@@ -4609,7 +4771,7 @@ allows the function to be used from Python as follows:
@@ -4630,11 +4792,11 @@ previous example: for (i = 0; i < $1; i++) { PyObject *o = PyList_GetItem($input,i); if (PyString_Check(o)) - $2[i] = PyString_AsString(PyList_GetItem($input,i)); + $2[i] = PyString_AsString(PyList_GetItem($input,i)); else { - PyErr_SetString(PyExc_TypeError,"list must contain strings"); - free($2); - return NULL; + PyErr_SetString(PyExc_TypeError,"list must contain strings"); + free($2); + return NULL; } } $2[i] = 0; @@ -4663,11 +4825,51 @@ to supply the argument count. This is automatically set by the typemap code. F->>> foo(4, ["foo","bar","spam","1"]) +>>> foo(4, ["foo", "bar", "spam", "1"])+ +->>> foo(["foo","bar","spam","1"]) +>>> foo(["foo", "bar", "spam", "1"]) +++If your function is overloaded in C++, for example: +
+ +++ ++int foo(int argc, char **argv); +int foo(); +++don't forget to also provide a suitable typecheck typemap for overloading +such as: +
+ +++ ++%typecheck(SWIG_TYPECHECK_STRING_ARRAY) (int argc, char **argv) { + $1 = PyList_Check($input) ? 1 : 0; +} +++If you don't you'll get an error message along the lines of: +
+ ++-+Traceback (most recent call last): + File "runme.py", line 3, in >module< + example.foo(["foo", "bar", "spam", "1"]) +NotImplementedError: Wrong number or type of arguments for overloaded function 'foo'. + Possible C/C++ prototypes are: + foo(int,char **) + foo()34.9.3 Using typemaps to return arguments
+36.9.3 Using typemaps to return arguments
@@ -4678,12 +4880,11 @@ arguments rather than in the return value of a function. For example:
/* Returns a status value and two values in out1 and out2 */ int spam(double a, double b, double *out1, double *out2) { - ... Do a bunch of stuff ... - *out1 = result1; - *out2 = result2; - return status; -}; - + ... Do a bunch of stuff ... + *out1 = result1; + *out2 = result2; + return status; +}@@ -4698,23 +4899,23 @@ A typemap can be used to handle this case as follows : // is guaranteed to be a List object by SWIG. %typemap(argout) double *OutValue { - PyObject *o, *o2, *o3; - o = PyFloat_FromDouble(*$1); - if ((!$result) || ($result == Py_None)) { - $result = o; - } else { - if (!PyTuple_Check($result)) { - PyObject *o2 = $result; - $result = PyTuple_New(1); - PyTuple_SetItem(target,0,o2); - } - o3 = PyTuple_New(1); - PyTuple_SetItem(o3,0,o); - o2 = $result; - $result = PySequence_Concat(o2,o3); - Py_DECREF(o2); - Py_DECREF(o3); + PyObject *o, *o2, *o3; + o = PyFloat_FromDouble(*$1); + if ((!$result) || ($result == Py_None)) { + $result = o; + } else { + if (!PyTuple_Check($result)) { + PyObject *o2 = $result; + $result = PyTuple_New(1); + PyTuple_SetItem($result,0,o2); } + o3 = PyTuple_New(1); + PyTuple_SetItem(o3,0,o); + o2 = $result; + $result = PySequence_Concat(o2,o3); + Py_DECREF(o2); + Py_DECREF(o3); + } } int spam(double a, double b, double *OutValue, double *OutValue); @@ -4756,7 +4957,7 @@ function can now be used as follows: >>>
34.9.4 Mapping Python tuples into small arrays
+36.9.4 Mapping Python tuples into small arrays
@@ -4805,7 +5006,7 @@ array, such an approach would not be recommended for huge arrays, but for small structures, this approach works fine.
-34.9.5 Mapping sequences to C arrays
+36.9.5 Mapping sequences to C arrays
@@ -4894,7 +5095,7 @@ static int convert_darray(PyObject *input, double *ptr, int size) { -
34.9.6 Pointer handling
+36.9.6 Pointer handling
@@ -4991,7 +5192,7 @@ class object (if applicable). -
34.10 Docstring Features
+36.10 Docstring Features
@@ -5019,7 +5220,7 @@ of your users much simpler.
-34.10.1 Module docstring
+36.10.1 Module docstring
@@ -5053,7 +5254,7 @@ layout of controls on a panel, etc. to be loaded from an XML file." -
34.10.2 %feature("autodoc")
+36.10.2 %feature("autodoc")
@@ -5081,7 +5282,7 @@ four levels for autodoc controlled by the value given to the feature, %feature("autodoc", "level"). The four values for level are covered in the following sub-sections. -
34.10.2.1 %feature("autodoc", "0")
+36.10.2.1 %feature("autodoc", "0")
@@ -5110,7 +5311,7 @@ def function_name(*args, **kwargs): -
34.10.2.2 %feature("autodoc", "1")
+36.10.2.2 %feature("autodoc", "1")
@@ -5135,13 +5336,13 @@ def function_name(*args, **kwargs): -
34.10.2.3 %feature("autodoc", "2")
+36.10.2.3 %feature("autodoc", "2")
Level "2" results in the function prototype as per level "0". In addition, a line of -documentation is generated for each parameter. Using the previous example, the generated -code will be: +documentation is generated for each parameter using numpydoc style. +Using the previous example, the generated code will be:
@@ -5150,11 +5351,12 @@ def function_name(*args, **kwargs): """ function_name(x, y, foo=None, bar=None) -> bool - Parameters: - x: int - y: int - foo: Foo * - bar: Bar * + Parameters + ---------- + x: int + y: int + foo: Foo * + bar: Bar * """ ... @@ -5185,17 +5387,18 @@ def function_name(*args, **kwargs): """ function_name(x, y, foo=None, bar=None) -> bool - Parameters: - x (C++ type: int) -- Input x dimension - y: int - foo: Foo * - bar: Bar * + Parameters + ---------- + x (C++ type: int) -- Input x dimension + y: int + foo: Foo * + bar: Bar * """-34.10.2.4 %feature("autodoc", "3")
+36.10.2.4 %feature("autodoc", "3")
@@ -5208,11 +5411,12 @@ def function_name(*args, **kwargs): """ function_name(int x, int y, Foo foo=None, Bar bar=None) -> bool - Parameters: - x: int - y: int - foo: Foo * - bar: Bar * + Parameters + ---------- + x: int + y: int + foo: Foo * + bar: Bar * """ ... @@ -5220,7 +5424,7 @@ def function_name(*args, **kwargs): -
34.10.2.5 %feature("autodoc", "docstring")
+36.10.2.5 %feature("autodoc", "docstring")
@@ -5239,7 +5443,7 @@ void GetPosition(int* OUTPUT, int* OUTPUT); -
34.10.3 %feature("docstring")
+36.10.3 %feature("docstring")
@@ -5271,150 +5475,786 @@ with more than one line. -
34.11 Python Packages
+36.11 Python Packages
--Using the package option of the %module directive -allows you to specify what Python package that the module will be -living in when installed. -
+Python has concepts of modules and packages. Modules are separate units of +code and may be grouped together to form a package. Packages may be nested, +that is they may contain subpackages. This leads to tree-like hierarchy, with +packages as intermediate nodes and modules as leaf nodes.
-+-The hierarchy of Python packages/modules follows the hierarchy of +*.py files found in a source tree (or, more generally, in the Python path). +Normally, the developer creates new module by placing a *.py file +somewhere under Python path; the module is then named after that *.py +file. A package is created by placing an __init__.py file within a +directory; the package is then named after that directory. For example, the +following source tree:
+ +-%module(package="wx") xrc +mod1.py +pkg1/__init__.py +pkg1/mod2.py +pkg1/pkg2/__init__.py +pkg1/pkg2/mod3.py-This is useful when the .i file is %imported by -another .i file. By default SWIG will assume that the -importer is able to find the importee with just the module name, but -if they live in separate Python packages then that won't work. -However if the importee specifies what its package is with the -%module option then the Python code generated for the -importer will use that package name when importing the other module -and also in base class declarations, etc. if the package name is -different than its own. +defines the following Python packages and modules:
-34.12 Python 3 Support
- +++pkg1 # package +pkg1.pkg2 # package +mod1 # module +pkg1.mod2 # module +pkg1.pkg2.mod3 # module ++-SWIG is able to support Python 3.0. The wrapper code generated by -SWIG can be compiled with both Python 2.x or 3.0. Further more, by -passing the -py3 command line option to SWIG, wrapper code -with some Python 3 specific features can be generated (see below -subsections for details of these features). The -py3 option also -disables some incompatible features for Python 3, such as --classic. +The purpose of an __init__.py file is two-fold. First, the existence of +__init__.py in a directory informs the Python interpreter that this +directory contains a Python package. Second, the code in __init__.py is +loaded/executed automatically when the package is initialized (when it or its +submodule/subpackage gets import'ed). By default, SWIG generates +proxy Python code – one *.py file for each *.i +interface. The __init__.py files, however, are not generated by SWIG. +They should be created by other means. Both files (module *.py and +__init__.py) should be installed in appropriate destination +directories in order to obtain a desirable package/module hierarchy. +
-There is a list of known-to-be-broken features in Python 3: +Python3 adds another option for packages with +PEP 0420 (implicit +namespace packages). Implicit namespace packages no longer use +__init__.py files. SWIG generated Python modules support implicit +namespace packages. See +36.11.5 Implicit Namespace +Packages for more information.
--
- No more support for FILE* typemaps, because PyFile_AsFile has been dropped - in Python 3.
-- The -apply command line option is removed and generating - code using apply() is no longer supported.
--The following are Python 3.0 new features that are currently supported by -SWIG. +If you place a SWIG generated module into a Python package then there +are details concerning the way SWIG +searches for the wrapper module +that you may want to familiarize yourself with.
-34.12.1 Function annotation
- +The way Python defines its modules and packages impacts SWIG users. Some +users may need to use special features such as the package option in the +%module directive or import related command line options. These are +explained in the following sections.
--The -py3 option will enable function annotation support. When used -SWIG is able to generate proxy method definitions like this: -
+36.11.1 Setting the Python package
-- def foo(self, bar : "int"=0) -> "void" : ... --Also, even if without passing SWIG the -py3 option, the parameter list -still could be generated: +Using the package option in the %module directive allows you +to specify a Python package that the module will be in when installed.
-+- def foo(self, bar=0): ... -++%module(package="wx") xrc ++-But for overloaded function or method, the parameter list would fallback to -*args or self, *args, and **kwargs may be append -depend on whether you enabled the keyword argument. This fallback is due to -all overloaded functions share the same function in SWIG generated proxy class. +This is useful when the .i file is %imported by +another .i file. By default SWIG will assume that the +importer is able to find the importee with just the module name, but +if they live in separate Python packages then this won't work. +However if the importee specifies what its package is with the +%module option then the Python code generated for the +importer will use that package name when importing the other module +and in base class declarations, etc..
--For detailed usage of function annotation, see -PEP 3107. +
SWIG assumes that the package option provided to %module +together with the module name (that is, wx.xrc in the above +example) forms a fully qualified (absolute) name of a module (in Python terms). +This is important especially for Python 3, where absolute imports are used by +default. It's up to you to place the generated module files (.py, +.so) in appropriate subdirectories. For example, if you have an +interface file foo.i with:
-34.12.2 Buffer interface
- +++%module(package="pkg1.pkg2") foo ++-Buffer protocols were revised in Python 3. SWIG also gains a series of -new typemaps to support buffer interfaces. These typemap macros are -defined in pybuffer.i, which must be included in order to use them. -By using these typemaps, your wrapped function will be able to -accept any Python object that exposes a suitable buffer interface. +then the resulting directory layout should be
--For example, the get_path() function puts the path string -into the memory pointed to by its argument: -
++-+pkg1/ +pkg1/__init__.py +pkg1/pkg2/__init__.py +pkg1/pkg2/foo.py # (generated by SWIG) +pkg1/pkg2/_foo.so # (shared library built from C/C++ code generated by SWIG) +++-void get_path(char *s); -36.11.2 Absolute and relative imports
--Then you can write a typemap like this: (the following example is -applied to both Python 3.0 and 2.6, since the bytearray type -is backported to 2.6. -
+Suppose, we have the following hierarchy of files:
-+-%include <pybuffer.i> -%pybuffer_mutable_string(char *str); -void get_path(char *s); -++ ++pkg1/ +pkg1/__init__.py +pkg1/mod2.py +pkg1/pkg2/__init__.py +pkg1/pkg2/mod3.py ++Let the contents of pkg1/pkg2/mod3.py be
+++class M3: pass ++-And then on the Python side the wrapped get_path could be used in this -way: +We edit pkg1/mod2.py and want to import module +pkg1/pkg2/mod3.py in order to derive from class M3. We can +write appropriate Python code in several ways, for example:
-+->>> p = bytearray(10) ->>> get_path(p) ->>> print(p) -bytearray(b'/Foo/Bar/\x00') -+
- -
Using "import <>" syntax with absolute package name:
++++# pkg1/mod2.py +import pkg1.pkg2.mod3 +class M2(pkg1.pkg2.mod3.M3): pass ++-The macros defined in pybuffer.i are similar to those in -cstring.i: -
+- -
Using "import <>" syntax with package name relative to + pkg1 (only in Python 2.7 and earlier):
++++# pkg1/mod2.py +import pkg2.mod3 +class M2(pkg2.mod3.M3): pass ++-%pybuffer_mutable_binary(parm, size_parm) -
+- -
Using "from <> import <>" syntax (relative import + syntax, only in Python 2.5 and later):
++++# pkg1/mod2.py +from .pkg2 import mod3 +class M2(mod3.M3): pass +++-- -
Other variants, for example the following construction in order to + have the pkg2.mod3.M3 symbol available in mod2 as + in point 2 above (but now under Python 3):
++++# pkg1/mod2.py +from . import pkg2 +from .pkg2 import mod3 +class M2(pkg2.mod3.M3): pass +++ + +
Now suppose we have mod2.i with
+ +++ ++// mod2.i +%module (package="pkg1") mod2 +%import "mod3.i" +// ... ++and mod3.i with
+ +++ ++// mod3.i +%module (package="pkg1.pkg2") mod3 +// ... ++By default, SWIG would generate mod2.py proxy file with +import directive as in point 1. This can be changed with the +-relativeimport command line option. The -relativeimport instructs +SWIG to organize imports as in point 2 (for Python < 2.7.0) or as in point 4 +for Python 2.7.0 and newer. This is a check done at the time the module is +imported. In short, if you have +mod2.i and mod3.i as above, then without +-relativeimport SWIG will write
+ +++ ++import pkg1.pkg2.mod3 ++to mod2.py proxy file, and with -relativeimport it will +write
+ +++ ++from sys import version_info +if version_info >= (2, 7, 0): + from . import pkg2 + import pkg1.pkg2.mod3 +else: + import pkg2.mod3 +del version_info ++You should avoid using relative imports and use absolute ones whenever +possible. There are some cases, however, when relative imports may be +necessary. The first example is, when some (legacy) Python code refers entities +imported by proxy files generated by SWIG, and it assumes that the proxy file +uses relative imports. Second case is, when one puts import directives in +__init__.py to import symbols from submodules or subpackages and the +submodule depends on other submodules (discussed later).
+ +36.11.3 Enforcing absolute import semantics
+ + +As you may know, there is an incompatibility in import semantics (for the +import <> syntax) between Python 2 and 3. In Python 2.4 and +earlier it is not clear whether
+ ++++import foo ++refers to a top-level module or to another module inside the current +package. In Python 3 it always refers to a top-level module +(see PEP 328). +To instruct Python 2.5 through 2.7 to use new semantics (that is import +foo is interpreted as absolute import), one has to put the following +line +
+ +++ ++from __future__ import absolute_import ++at the very beginning of his proxy *.py file. In SWIG, it may be +accomplished with %pythonbegin directive as follows:
+ +++ ++%pythonbegin %{ +from __future__ import absolute_import +%} ++36.11.4 Importing from __init__.py
+ + +Imports in __init__.py are handy when you want to populate a +package's namespace with names imported from other modules. In SWIG based +projects this approach may also be used to split large pieces of code into +smaller modules, compile them in parallel and then re-assemble everything at +runtime by importing submodules' contents in __init__.py, for +example.
+ +Unfortunately import directives in __init__.py may cause problems, +especially if they refer to a package's submodules. This is caused by the way +Python initializes packages. If you spot problems with imports from +__init__.py try using -relativeimport option. Below we +explain in detail one issue, for which the -relativeimport workaround +may be helpful.
+ +Consider the following example (Python 3):
+ +++ ++pkg1/__init__.py # (empty) +pkg1/pkg2/__init__.py # (imports something from bar.py) +pkg1/pkg2/foo.py +pkg1/pkg2/bar.py # (imports foo.py) ++If the file contents are:
+ ++
+ +- + +
pkg1/pkg2/__init__.py:
++++# pkg1/pkg2/__init__.py +from .bar import Bar ++- + +
pkg1/pkg2/foo.py:
++++# pkg1/pkg2/foo.py +class Foo: pass ++- +
pkg1/pkg2/bar.py:
++++# pkg1/pkg2/bar.py +import pkg1.pkg2.foo +class Bar(pkg1.pkg2.foo.Foo): pass ++Now if one simply used import pkg1.pkg2, it will usually fail:
+ +++ ++>>> import pkg1.pkg2 +Traceback (most recent call last): + File "<stdin>", line 1, in <module> + File "./pkg1/pkg2/__init__.py", line 2, in <module> + from .bar import Bar + File "./pkg1/pkg2/bar.py", line 3, in <module> + class Bar(pkg1.pkg2.foo.Foo): pass +AttributeError: 'module' object has no attribute 'pkg2' ++Surprisingly, if we execute the import pkg1.pkg2 directive for the +second time, it succeeds. The reason seems to be following: when Python spots +the from .bar import Bar directive in pkg1/pkg2/__init__.py +it starts loading pkg1/pkg2/bar.py. This module imports +pkg1.pkg2.foo in turn and tries to use pkg1.pkg2.foo.Foo, but +the package pkg1 is not fully initialized yet (the initialization +procedure is actually in progress) and it seems like the effect of the already seen +import pkg1.pkg2.pkg3.foo is "delayed" or ignored. Exactly the +same may happen to a proxy module generated by SWIG.
+ +One workaround for this case is to use a relative +import in pkg1/pkg2/bar.py. If we change bar.py to be:
+ +++ ++from .pkg3 import foo +class Bar(foo.Foo): pass ++or
+ +++ ++from . import pkg3 +from .pkg3 import foo +class Bar(pkg3.foo.Foo): pass ++then the example works again. With SWIG, you need to enable the +-relativeimport option in order to have the above workaround in +effect (note, that the Python 2 case also needs the -relativeimport +workaround).
+ +36.11.5 Implicit Namespace Packages
+ + +Python 3.3 introduced +PEP 0420 which +implements implicit namespace packages. In a nutshell, implicit namespace +packages remove the requirement of an __init__.py file and allow packages +to be split across multiple PATH elements. For example: +
+ +++ ++/fragment1/pkg1/mod1.py +/fragment2/pkg1/mod2.py +/fragment3/pkg1/mod3.py ++If PYTHONPATH is set to "/fragment1:/fragment2:/fragment3", then mod1, mod2 +and mod3 will be part of pkg1. This allows for splitting of packages into +separate pieces. This can be useful for SWIG generated wrappers in the +following way. +
+ +Suppose you create a SWIG wrapper for a module called robin. The SWIG +generated code consists of two files robin.py and _robin.so. You wish to +make these modules part of a subpackage (brave.sir). With implicit namespace +packages you can place these files in the following configurations: +
+ +Using PYTHONPATH="/some/path"
+++ ++/some/path/brave/sir/robin.py +/some/path/brave/sir/_robin.so ++Using PYTHONPATH="/some/path:/some/other/path" + +
++ ++/some/path/brave/sir/robin.py +/some/other/path/brave/sir/_robin.so ++Finally suppose that your pure python code is stored in a .zip file or +some other way (database, web service connection, etc). Python can load the +robin.py module using a custom importer. But the _robin.so module will need +to be located on a file system. Implicit namespace packages make this +possible. For example, using PYTHONPATH="/some/path/foo.zip:/some/other/path" + +
Contents of foo.zip
+++ ++brave/ +brave/sir/ +brave/sir/robin.py ++File system contents
+++ ++/some/other/path/brave/sir/_robin.so ++Support for implicit namespace packages was added to python-3.3. The +zipimporter requires python-3.5.1 or newer to work with subpackages. +
+ ++Compatibility Note: Support for implicit namespace packages was added in SWIG-3.0.9. +
+ + +36.11.6 Searching for the wrapper module
+ + ++When SWIG creates wrappers from an interface file, say foo.i, two Python modules are +created. There is a pure Python module module (foo.py) and C/C++ code which is +built and linked into a dynamically (or statically) loaded module _foo +(see the Preliminaries section for details). So, the interface +file really defines two Python modules. How these two modules are loaded is +covered next. +
+ ++The pure Python module needs to load the C/C++ module in order to link +to the wrapped C/C++ methods. To do this it must make some assumptions +about what package the C/C++ module may be located in. The approach the +pure Python module uses to find the C/C++ module is as follows: +
+ ++
+ +- +
The pure Python module, foo.py, tries to load the C/C++ module, _foo, from the same package foo.py is + located in. The package name is determined from the __name__ + attribute given to foo.py by the Python loader that imported + foo.py. If foo.py is not in a package then _foo is loaded + as a global module.
+- +
If the above import of _foo results in an ImportError + being thrown, then foo.py makes a final attempt to load _foo + as a global module.
++As an example suppose foo.i is compiled into foo.py and _foo.so. Assuming +/dir is on PYTHONPATH, then the two modules can be installed and used in the +following ways: +
+ + +36.11.6.1 Both modules in the same package
+ + +Both modules are in one package:
++++/dir/package/foo.py +/dir/package/__init__.py +/dir/package/_foo.so ++And imported with
+++ + ++from package import foo ++36.11.6.2 Split modules
+ + +The pure python module is in a package and the C/C++ module is global:
++++/dir/package/foo.py +/dir/package/__init__.py +/dir/_foo.so ++And imported with
+++ + ++from package import foo ++36.11.6.3 Both modules are global
+ + +Both modules are global:
++++/dir/foo.py +/dir/_foo.so ++And imported with
+++ ++import foo +++If _foo is statically linked into an embedded Python interpreter, then it may or +may not be in a Python package. This depends in the exact way the module was +loaded statically. The above search order will still be used for statically +loaded modules. So, one may place the module either globally or in a package +as desired. +
+ +36.11.6.4 Statically linked C modules
+ + +It is strongly recommended to use dynamically linked modules for the C +portion of your pair of Python modules. +If for some reason you still need +to link the C module of the pair of Python modules generated by SWIG into +your interpreter, then this section provides some details on how this impacts +the pure Python modules ability to locate the other part of the pair. +Please also see the Static Linking section. +
+ +When Python is extended with C code the Python interpreter needs to be +informed about details of the new C functions that have been linked into +the executable. The code to do this is created by SWIG and is automatically +called in the correct way when the module is dynamically loaded. However +when the code is not dynamically loaded (because it is statically linked) +Then the initialization method for the module created by SWIG is not +called automatically and the Python interpreter has no idea that the +new SWIG C module exists. +
+ +Before Python 3, one could simply call the init method created by SWIG +which would have normally been called when the shared object was dynamically +loaded. The specific name of this method is not given here because statically +linked modules are not encouraged with SWIG +(Static Linking). However one can find this +init function in the C file generated by SWIG. +
+ +If you are really keen on static linking there are two ways +to initialize the SWIG generated C module with the init method. Which way +you use depends on what version of Python your module is being linked with. +Python 2 and Python 3 treat this init function differently. And the way +they treat it affects how the pure Python module will be able to +locate the C module. +
+ +The details concerning this are covered completly in the documentation +for Python itself. Links to the relavent sections follow: +
+ + + +There are two keys things to understand. The first is that in +Python 2 the init() function returns void. In Python 3 the init() function +returns a PyObject * which points to the new module. Secondly, when +you call the init() method manually, you are the Python importer. So, you +determine which package the C module will be located in. +
+ +So, if you are using Python 3 it is important that you follow what is +described in the Python documentation linked above. In particular, you can't +simply call the init() function generated by SWIG and cast the PyObject +pointer it returns over the side. If you do then Python 3 will have no +idea that your C module exists and the pure Python half of your wrapper will +not be able to find it. You need to register your module with the Python +interpreter as described in the Python docs. +
+ +With Python 2 things are somewhat more simple. In this case the init function +returns void. Calling it will register your new C module as a global +module. The pure Python part of the SWIG wrapper will be able to find it +because it tries both the pure Python module it is part of and the global +module. If you wish not to have the statically linked module be a global +module then you will either need to refer to the Python documentation on how +to do this (remember you are now the Python importer) or use dynamic linking. +
+ +36.12 Python 3 Support
+ + ++SWIG is able to support Python 3.0. The wrapper code generated by +SWIG can be compiled with both Python 2.x or 3.0. Further more, by +passing the -py3 command line option to SWIG, wrapper code +with some Python 3 specific features can be generated (see below +subsections for details of these features). The -py3 option also +disables some incompatible features for Python 3, such as +-classic. + +
+There is a list of known-to-be-broken features in Python 3: +
++
+ +- No more support for FILE* typemaps, because PyFile_AsFile has been dropped + in Python 3.
+- The -apply command line option is removed and generating + code using apply() is no longer supported.
++The following are Python 3.0 new features that are currently supported by +SWIG. +
+ +36.12.1 Function annotation
+ + ++The -py3 option will enable function annotation support. When used +SWIG is able to generate proxy method definitions like this: +
+ ++ ++ def foo(self, bar : "int"=0) -> "void" : ... ++Also, even if without passing SWIG the -py3 option, the parameter list +still could be generated: +
+ ++ ++ def foo(self, bar=0): ... ++But for overloaded function or method, the parameter list would fallback to +*args or self, *args, and **kwargs may be append +depend on whether you enabled the keyword argument. This fallback is due to +all overloaded functions share the same function in SWIG generated proxy class. +
+ ++For detailed usage of function annotation, see +PEP 3107. +
+ +36.12.2 Buffer interface
+ + ++Buffer protocols were revised in Python 3. SWIG also gains a series of +new typemaps to support buffer interfaces. These typemap macros are +defined in pybuffer.i, which must be included in order to use them. +By using these typemaps, your wrapped function will be able to +accept any Python object that exposes a suitable buffer interface. +
+ ++For example, the get_path() function puts the path string +into the memory pointed to by its argument: +
+ ++ ++void get_path(char *s); ++Then you can write a typemap like this: (the following example is +applied to both Python 3.0 and 2.6, since the bytearray type +is backported to 2.6. +
+ + ++ ++%include <pybuffer.i> +%pybuffer_mutable_string(char *str); +void get_path(char *s); ++And then on the Python side the wrapped get_path could be used in this +way: +
+ ++ ++>>> p = bytearray(10) +>>> get_path(p) +>>> print(p) +bytearray(b'/Foo/Bar/\x00') ++The macros defined in pybuffer.i are similar to those in +cstring.i: +
+ ++%pybuffer_mutable_binary(parm, size_parm) +
+ ++ +-The macro can be used to generate a typemap which maps a buffer of an object to a pointer provided by parm and a size argument provided by size_parm. For example: @@ -5510,7 +6350,7 @@ modify the buffer.
34.12.3 Abstract base classes
+36.12.3 Abstract base classes
@@ -5548,7 +6388,243 @@ used to define an abstract base class for your own C++ class:
For details of abstract base class, please see -PEP 3119. +PEP 3119. +
+ +36.12.4 Byte string output conversion
+ + ++By default, any byte string (char* or std::string) returned +from C or C++ code is decoded to text as UTF-8. This decoding uses the +surrogateescape error handler under Python 3.1 or higher -- this +error handler decodes invalid byte sequences to high surrogate characters +in the range U+DC80 to U+DCFF. + +As an example, consider the following SWIG interface, which exposes a byte +string that cannot be completely decoded as UTF-8: +
+ ++ ++%module example + +%include <std_string.i> + +%inline %{ + +const char* non_utf8_c_str(void) { + return "h\xe9llo w\xc3\xb6rld"; +} + +%} ++When this method is called from Python 3, the return value is the following +text string: +
+ ++ ++>>> s = example.non_utf8_c_str() +>>> s +'h\udce9llo wörld' ++Since the C string contains bytes that cannot be decoded as UTF-8, those raw +bytes are represented as high surrogate characters that can be used to obtain +the original byte sequence: +
+ ++ ++>>> b = s.encode('utf-8', errors='surrogateescape') +>>> b +b'h\xe9llo w\xc3\xb6rld' ++One can then attempt a different encoding, if desired (or simply leave the +byte string as a raw sequence of bytes for use in binary protocols): +
+ ++ ++>>> b.decode('latin-1') +'héllo wörld' ++Note, however, that text strings containing surrogate characters are rejected +with the default strict codec error handler. For example: +
+ ++ ++>>> with open('test', 'w') as f: +... print(s, file=f) +... +Traceback (most recent call last): + File "<stdin>", line 2, in <module> +UnicodeEncodeError: 'utf-8' codec can't encode character '\udce9' in position 1: surrogates not allowed ++This requires the user to check most strings returned by SWIG bindings, but +the alternative is for a non-UTF8 byte string to be completely inaccessible +in Python 3 code. +
+ ++For more details about the surrogateescape error handler, please see +PEP 383. +
+ ++In some cases, users may wish to instead handle all byte strings as bytes +objects in Python 3. This can be accomplished by adding +SWIG_PYTHON_STRICT_BYTE_CHAR to the generated code: +
+ ++ ++%module char_to_bytes +%begin %{ +#define SWIG_PYTHON_STRICT_BYTE_CHAR +%} + +char *charstring(char *s) { + return s; +} ++This will modify the behavior so that only Python 3 bytes objects will be +accepted and converted to a C/C++ string, and any string returned from C/C++ +will be converted to a bytes object in Python 3: +
+ ++ ++>>> from char_to_bytes import * +>>> charstring(b"hi") # Byte string +b'hi' +>>> charstring("hi") # Unicode string +Traceback (most recent call last): + File "<stdin>", line 1, in ? +TypeError: in method 'charstring', argument 1 of type 'char *' ++Note that in Python 2, defining SWIG_PYTHON_STRICT_BYTE_CHAR has no +effect, since strings in Python 2 are equivalent to Python 3 bytes objects. +However, there is a similar capability to force unicode-only handling for +wide characters C/C++ strings (wchar_t * or std::wstring +types) in Python 2. By default, in Python 2 both strings and unicode strings +are converted to C/C++ wide strings, and returned wide strings are converted +to a Python unicode string. To instead only convert unicode strings to wide +strings, users can add SWIG_PYTHON_STRICT_UNICODE_WCHAR to the +generated code: +
+ ++ ++%module wchar_to_unicode +%begin %{ +#define SWIG_PYTHON_STRICT_UNICODE_WCHAR +%} + +wchar_t *wcharstring(wchar_t *s) { + return s; +} ++This ensures that only unicode strings are accepted by wcharstring in both +Python 2 and Python 3: +
+ ++ ++>>> from wchar_to_unicode import * +>>> wcharstring(u"hi") # Unicode string +u'hi' +>>> wcharstring(b"hi") # Byte string +Traceback (most recent call last): + File "<stdin>", line 1, in ? +TypeError: in method 'charstring', argument 1 of type 'wchar_t *' ++By defining both SWIG_PYTHON_STRICT_BYTE_CHAR and +SWIG_PYTHON_STRICT_UNICODE_WCHAR, Python wrapper code can support +overloads taking both std::string (as Python bytes) and std::wstring +(as Python unicode). +
+ +36.12.5 Python 2 Unicode
+ + ++A Python 3 string is a Unicode string so by default a Python 3 string that contains Unicode +characters passed to C/C++ will be accepted and converted to a C/C++ string +(char * or std::string types). +A Python 2 string is not a unicode string by default and should a Unicode string be +passed to C/C++ it will fail to convert to a C/C++ string +(char * or std::string types). +The Python 2 behavior can be made more like Python 3 by defining +SWIG_PYTHON_2_UNICODE when compiling the generated C/C++ code. +By default when the following is wrapped: +
+ ++ ++%module unicode_strings +char *charstring(char *s) { + return s; +} ++An error will occur when using Unicode strings in Python 2: +
+ ++ ++>>> from unicode_strings import * +>>> charstring("hi") +'hi' +>>> charstring(u"hi") +Traceback (most recent call last): + File "<stdin>", line 1, in ? +TypeError: in method 'charstring', argument 1 of type 'char *' ++When the SWIG_PYTHON_2_UNICODE macro is added to the generated code: +
+ ++ ++%module unicode_strings +%begin %{ +#define SWIG_PYTHON_2_UNICODE +%} + +char *charstring(char *s) { + return s; +} ++Unicode strings will be successfully accepted and converted from UTF-8, +but note that they are returned as a normal Python 2 string: +
+ ++ ++>>> from unicode_strings import * +>>> charstring("hi") +'hi' +>>> charstring(u"hi") +'hi' +>>> ++Note that defining both SWIG_PYTHON_2_UNICODE and +SWIG_PYTHON_STRICT_BYTE_CHAR at the same time is not allowed, since +the first is allowing unicode conversion and the second is explicitly +prohibiting it.
diff --git a/Doc/Manual/R.html b/Doc/Manual/R.html index ceea321..9b5993b 100644 --- a/Doc/Manual/R.html +++ b/Doc/Manual/R.html @@ -1,12 +1,13 @@ - +SWIG and R + -35 SWIG and R
+37 SWIG and R
-@@ -33,7 +34,7 @@ compile and run an R interface to QuantLib running on Mandriva Linux with gcc. The R bindings also work on Microsoft Windows using Visual C++. -
-35.1 Bugs
+37.1 Bugs
@@ -45,7 +46,7 @@ Currently the following features are not implemented or broken:
- C Array wrappings
35.2 Using R and SWIG
+37.2 Using R and SWIG
@@ -119,7 +120,24 @@ Without it, inheritance of wrapped objects may fail. These two files can be loaded in any order
-35.3 Precompiling large R files
++ If you are compiling code yourself (not using R itself), there are a few things to watch out for: +
+ ++
+ +- The output shared library name (to the left of the file extension) MUST match the module name, or alternatively, you can also set the -package NAME command line argument. See swig -r -help for more information +
- If you do not set the output file name appropriately, you might see errors like +
+++> fact(4) +Error in .Call("R_swig_fact", s_arg1, as.logical(.copy), PACKAGE = "example") : + "R_swig_fact" not available for .Call() for package "example" ++- Make sure the architecture of the shared library(x64 for instance), matches the architecture of the R program you want to load your shared library into +
37.3 Precompiling large R files
In cases where the R file is large, one make save a lot of loading @@ -137,7 +155,7 @@ will save a large amount of loading time. -35.4 General policy
+37.4 General policy
@@ -146,7 +164,7 @@ wrapping over the underlying functions and rely on the R type system to provide R syntax.
-35.5 Language conventions
+37.5 Language conventions
@@ -155,7 +173,7 @@ and [ are overloaded to allow for R syntax (one based indices and slices)
-35.6 C++ classes
+37.6 C++ classes
@@ -167,7 +185,7 @@ keep track of the pointer object which removes the necessity for a lot of the proxy class baggage you see in other languages.
-35.7 Enumerations
+37.7 Enumerations
diff --git a/Doc/Manual/Ruby.html b/Doc/Manual/Ruby.html index 301631a..cfb99e7 100644 --- a/Doc/Manual/Ruby.html +++ b/Doc/Manual/Ruby.html @@ -1,13 +1,14 @@ - +
-SWIG and Ruby - +SWIG and Ruby + + -36 SWIG and Ruby
+38 SWIG and Ruby
-@@ -42,6 +43,10 @@
- C++ STL Functors
- C++ STL Iterators
- C++ Smart Pointers +
- Cross-Language Polymorphism
- Exception Unrolling @@ -144,10 +149,10 @@
This chapter describes SWIG's support of Ruby.
-36.1 Preliminaries
+38.1 Preliminaries
-SWIG 1.3 is known to work with Ruby versions 1.6 and later. +
SWIG 3.0 is known to work with Ruby versions 1.8 and later. Given the choice, you should use the latest stable version of Ruby. You should also determine if your system supports shared libraries and dynamic loading. SWIG will work with or without dynamic loading, but @@ -159,7 +164,7 @@ read the "SWIG Basics" chapter. It is also assumed that the reader has a basic understanding of Ruby.
-36.1.1 Running SWIG
+38.1.1 Running SWIG
To build a Ruby module, run SWIG using the -ruby @@ -183,7 +188,7 @@ if compiling a C++ extension) that contains all of the code needed to build a Ruby extension module. To finish building the module, you need to compile this file and link it with the rest of your program.
-36.1.2 Getting the right header files
+38.1.2 Getting the right header files
In order to compile the wrapper code, the compiler needs the ruby.h @@ -191,7 +196,7 @@ header file. This file is usually contained in a directory such as
@@ -201,12 +206,18 @@ installed, you can run Ruby to find out. For example:/usr/lib/ruby/1.8/x86_64-linux-gnu/ruby.h -/usr/local/lib/ruby/1.6/i686-linux/ruby.h +/usr/include/ruby-2.1.0/ruby.h-$ ruby -e 'puts $:.join("\n")' -/usr/local/lib/ruby/site_ruby/1.6 /usr/local/lib/ruby/site_ruby/1.6/i686-linux -/usr/local/lib/ruby/site_ruby /usr/local/lib/ruby/1.6 /usr/local/lib/ruby/1.6/i686-linux . +/usr/local/lib/site_ruby/2.1.0 +/usr/local/lib/x86_64-linux-gnu/site_ruby +/usr/local/lib/site_ruby +/usr/lib/ruby/vendor_ruby/2.1.0 +/usr/lib/x86_64-linux-gnu/ruby/vendor_ruby/2.1.0 +/usr/lib/ruby/vendor_ruby +/usr/lib/ruby/2.1.0 +/usr/lib/x86_64-linux-gnu/ruby/2.1.036.1.3 Compiling a dynamic module
+38.1.3 Compiling a dynamic module
Ruby extension modules are typically compiled into shared @@ -259,19 +270,27 @@ operating system would look something like this:
-$ swig -ruby example.i -$ gcc -c example.c -$ gcc -c example_wrap.c -I/usr/local/lib/ruby/1.6/i686-linux +$ gcc -O2 -fPIC -c example.c +$ gcc -O2 -fPIC -c example_wrap.c -I/usr/include/ruby-2.1.0 $ gcc -shared example.o example_wrap.o -o example.soFor other platforms it may be necessary to compile with the -fPIC -option to generate position-independent code. If in doubt, consult the +
+The -fPIC option tells GCC to generate position-independent code (PIC) +which is required for most architectures (it's not vital on x86, but +still a good idea as it allows code pages from the library to be shared between +processes). Other compilers may need a different option specified instead of +-fPIC. +
+ ++If in doubt, consult the manual pages for your compiler and linker to determine the correct set of options. You might also check the SWIG Wiki for additional information.
-36.1.4 Using your module
+38.1.4 Using your module
Ruby module names must be capitalized, @@ -301,7 +320,7 @@ begins with:
will result in an extension module using the feature name "example" and Ruby module name "Example".
-36.1.5 Static linking
+38.1.5 Static linking
An alternative approach to dynamic linking is to rebuild the @@ -316,7 +335,7 @@ finding the Ruby source, adding an entry to the ext/Setup file, adding your directory to the list of extensions in the file, and finally rebuilding Ruby.
-36.1.6 Compilation of C++ extensions
+38.1.6 Compilation of C++ extensions
On most machines, C++ extension modules should be linked @@ -325,8 +344,8 @@ using the C++ compiler. For example:
@@ -348,7 +367,7 @@ $libs = append_library($libs, "supc++") create_makefile('example')$ swig -c++ -ruby example.i -$ g++ -c example.cxx -$ g++ -c example_wrap.cxx -I/usr/local/lib/ruby/1.6/i686-linux +$ g++ -fPIC -c example.cxx +$ g++ -fPIC -c example_wrap.cxx -I/usr/include/ruby-2.1.0 $ g++ -shared example.o example_wrap.o -o example.so36.2 Building Ruby Extensions under Windows 95/NT
+38.2 Building Ruby Extensions under Windows 95/NT
Building a SWIG extension to Ruby under Windows 95/NT is @@ -373,7 +392,7 @@ order to build extensions, you may need to download the source distribution to the Ruby package, as you will need the Ruby header files.
-36.2.1 Running SWIG from Developer Studio
+38.2.1 Running SWIG from Developer Studio
If you are developing your application within Microsoft @@ -437,13 +456,13 @@ Foo = 3.0
36.3 The Ruby-to-C/C++ Mapping
+38.3 The Ruby-to-C/C++ Mapping
This section describes the basics of how SWIG maps C or C++ declarations in your SWIG interface files to Ruby constructs.
-36.3.1 Modules
+38.3.1 Modules
The SWIG %module directive specifies @@ -515,7 +534,7 @@ option to wrap everything into the global module, take care that the names of your constants, classes and methods don't conflict with any of Ruby's built-in names.
-36.3.2 Functions
+38.3.2 Functions
Global functions are wrapped as Ruby module methods. For @@ -549,7 +568,7 @@ irb(main):002:0> Example.fact(4) 24
36.3.3 Variable Linking
+38.3.3 Variable Linking
C/C++ global variables are wrapped as a pair of singleton @@ -611,7 +630,7 @@ directive. For example:
effect until it is explicitly disabled using %mutable. -36.3.4 Constants
+38.3.4 Constants
C/C++ constants are wrapped as module constants initialized @@ -639,7 +658,7 @@ irb(main):002:0> Example::PI 3.14159
36.3.5 Pointers
+38.3.5 Pointers
"Opaque" pointers to arbitrary C/C++ types (i.e. types that @@ -663,7 +682,7 @@ returns an instance of an internally generated Ruby class:
A NULL pointer is always represented by the Ruby nil object.
-36.3.6 Structures
+38.3.6 Structures
C/C++ structs are wrapped as Ruby classes, with accessor @@ -677,7 +696,7 @@ For example, this struct declaration:
gets wrapped as a Vector class, with -Ruby instance methods x, x=, +Ruby instance methods x, x=, y and y=. These methods can be used to access structure data from Ruby as follows:
@@ -768,7 +787,7 @@ void Bar_f_set(Bar *b, Foo *val) { } -36.3.7 C++ classes
+38.3.7 C++ classes
Like structs, C++ classes are wrapped by creating a new Ruby @@ -823,7 +842,7 @@ Ale 3 -
36.3.8 C++ Inheritance
+38.3.8 C++ Inheritance
The SWIG type-checker is fully aware of C++ inheritance. @@ -976,7 +995,7 @@ inherit from both Base1 and Base2 (i.e. they exhibit "Duck Typing").
-36.3.9 C++ Overloaded Functions
+38.3.9 C++ Overloaded Functions
C++ overloaded functions, methods, and constructors are @@ -1066,7 +1085,7 @@ arises--in this case, the first declaration takes precedence.
Please refer to the "SWIG and C++" chapter for more information about overloading.
-36.3.10 C++ Operators
+38.3.10 C++ Operators
For the most part, overloaded operators are handled @@ -1108,7 +1127,7 @@ c = Example.add_complex(a, b) is discussed in the section on operator overloading.
-36.3.11 C++ namespaces
+38.3.11 C++ namespaces
SWIG is aware of C++ namespaces, but namespace names do not @@ -1165,7 +1184,7 @@ and create extension modules for each namespace separately. If your program utilizes thousands of small deeply nested namespaces each with identical symbol names, well, then you get what you deserve.
-36.3.12 C++ templates
+38.3.12 C++ templates
C++ templates don't present a huge problem for SWIG. However, @@ -1207,7 +1226,7 @@ irb(main):004:0> p.second 4 -
36.3.13 C++ Standard Template Library (STL)
+38.3.13 C++ Standard Template Library (STL)
On a related note, the standard SWIG library contains a @@ -1300,12 +1319,12 @@ puts v shown in these examples. More details can be found in the SWIG and C++ chapter.
-36.3.14 C++ STL Functors
+38.3.14 C++ STL Functors
Some containers in the STL allow you to modify their default behavior by using so called functors or function objects. -Functors are often just a very simple struct with operator() +Functors are often just a very simple struct with operator() redefined or an actual C/C++ function. This allows you, for example, to always keep the sort order of a STL container to your liking.
@@ -1319,7 +1338,7 @@ this includes std::set, std::multiset and std::multimap. -The functors in swig are called swig::UnaryFunction +
The functors in swig are called swig::UnaryFunction and swig::BinaryFunction. For C++ predicates (ie. functors that must return bool as a result) swig::UnaryPredicate @@ -1333,7 +1352,7 @@ are provided.
%include <std_set.i> -%typemap(IntSet) std::set< int, swig::BinaryPredicate >; +%template(IntSet) std::set< int, swig::BinaryPredicate >;You can then use the set from Ruby with or without a proc @@ -1361,7 +1380,7 @@ b -
36.3.15 C++ STL Iterators
+38.3.15 C++ STL Iterators
The STL is well known for the use of iterators. There @@ -1372,8 +1391,8 @@ values they point at, while the non-const iterators can both read and modify the values.
The Ruby STL wrappings support both type of iterators by using -a proxy class in-between. This proxy class is swig::Iterator or -swig::ConstIterator. Derived from them are template +a proxy class in-between. This proxy class is swig::Iterator or +swig::ConstIterator. Derived from them are template classes that need to be initialized with the actual iterator for the container you are wrapping and often times with the beginning and ending points of the iteration range.
@@ -1442,9 +1461,23 @@ i -If you'd rather have STL classes without any iterators, you should define -DSWIG_NO_EXPORT_ITERATOR_METHODS when running swig.
+If you'd rather have STL classes without any iterators, you should define -DSWIG_NO_EXPORT_ITERATOR_METHODS when running swig.
+ +38.3.16 C++ Smart Pointers
+ + +38.3.16.1 The shared_ptr Smart Pointer
+ + ++The C++11 standard provides std::shared_ptr which was derived from the Boost +implementation, boost::shared_ptr. +Both of these are available for Ruby in the SWIG library and usage is outlined +in the shared_ptr smart pointer library section. +
+ -36.3.16 C++ Smart Pointers
+38.3.16.2 Generic Smart Pointers
In certain C++ programs, it is common to use classes that @@ -1509,7 +1542,7 @@ method. For example:
irb(main):004:0> f = p.__deref__() # Returns underlying Foo *-36.3.17 Cross-Language Polymorphism
+38.3.17 Cross-Language Polymorphism
SWIG's Ruby module supports cross-language polymorphism @@ -1518,7 +1551,7 @@ module. Rather than duplicate the information presented in the 36.3.17.1 Exception Unrolling +
38.3.17.1 Exception Unrolling
Whenever a C++ director class routes one of its virtual @@ -1541,7 +1574,7 @@ method is "wrapped" using the rb_rescue2() function from Ruby's C API. If any Ruby exception is raised, it will be caught here and a C++ exception is raised in its place.
-36.4 Naming
+38.4 Naming
Ruby has several common naming conventions. Constants are @@ -1579,7 +1612,7 @@ generated by SWIG, it is turned off by default in SWIG 1.3.28. However, it is planned to become the default option in future releases.
-36.4.1 Defining Aliases
+38.4.1 Defining Aliases
It's a fairly common practice in the Ruby built-ins and @@ -1649,7 +1682,7 @@ matching rules used for other kinds of features apply (see the chapter on "Customization Features") for more details).
-36.4.2 Predicate Methods
+38.4.2 Predicate Methods
Ruby methods that return a boolean value and end in a @@ -1698,7 +1731,7 @@ using SWIG's "features" mechanism and so the same name matching rules used for other kinds of features apply (see the chapter on "Customization Features") for more details).
-36.4.3 Bang Methods
+38.4.3 Bang Methods
Ruby methods that modify an object in-place and end in an @@ -1730,7 +1763,7 @@ using SWIG's "features" mechanism and so the same name matching rules used for other kinds of features apply (see the chapter on "Customization Features") for more details).
-36.4.4 Getters and Setters
+38.4.4 Getters and Setters
Often times a C++ library will expose properties through @@ -1765,7 +1798,7 @@ irb(main):003:0> puts foo.value %rename("value=") Foo::setValue(int value); -
36.5 Input and output parameters
+38.5 Input and output parameters
A common problem in some C programs is handling parameters @@ -1904,10 +1937,10 @@ void get_dimensions(Matrix *m, int *rows, int*columns);
r, c = Example.get_dimensions(m)-36.6 Exception handling
+38.6 Exception handling
-36.6.1 Using the %exception directive
+38.6.1 Using the %exception directive
The SWIG %exception directive can be @@ -2016,7 +2049,7 @@ methods and functions named getitem and setitem. limited to C++ exception handling. See the chapter on Customization Features for more examples.
-36.6.2 Handling Ruby Blocks
+38.6.2 Handling Ruby Blocks
One of the highlights of Ruby and most of its standard library @@ -2083,7 +2116,7 @@ a special in typemap, like:
For more information on typemaps, see Typemaps.
-36.6.3 Raising exceptions
+38.6.3 Raising exceptions
There are three ways to raise exceptions from C++ code to @@ -2240,7 +2273,7 @@ function. The first argument passed to rb_raise() is the exception type. You can raise a custom exception type or one of the built-in Ruby exception types.
-36.6.4 Exception classes
+38.6.4 Exception classes
Starting with SWIG 1.3.28, the Ruby module supports the %exceptionclass @@ -2277,7 +2310,7 @@ end
For another example look at swig/Examples/ruby/exception_class.
-36.7 Typemaps
+38.7 Typemaps
This section describes how you can modify SWIG's default @@ -2292,7 +2325,7 @@ a required part of using SWIG---the default wrapping behavior is enough in most cases. Typemaps are only used if you want to change some aspect of the primitive C-Ruby interface.
-36.7.1 What is a typemap?
+38.7.1 What is a typemap?
A typemap is nothing more than a code generation rule that is @@ -2449,7 +2482,7 @@ to be used as follows (notice how the length parameter is omitted):
2 -36.7.2 Typemap scope
+38.7.2 Typemap scope
Once defined, a typemap remains in effect for all of the @@ -2495,7 +2528,7 @@ where the class itself is defined. For example:
}; -36.7.3 Copying a typemap
+38.7.3 Copying a typemap
A typemap is copied by using assignment. For example:
@@ -2537,7 +2570,7 @@ rules as for %apply (char *buf, int len) { (char *buffer, int size) }; // Multiple arguments -36.7.4 Deleting a typemap
+38.7.4 Deleting a typemap
A typemap can be deleted by simply defining no code. For @@ -2562,7 +2595,7 @@ defined by typemaps, clearing a fundamental type like int will make that type unusable unless you also define a new set of typemaps immediately after the clear operation.
-36.7.5 Placement of typemaps
+38.7.5 Placement of typemaps
Typemap declarations can be declared in the global scope, @@ -2633,13 +2666,13 @@ In this example, this is done using the class declaration class string .
-36.7.6 Ruby typemaps
+38.7.6 Ruby typemaps
The following list details all of the typemap methods that can be used by the Ruby module:
-36.7.6.1 "in" typemap
+38.7.6.1 "in" typemap
Converts Ruby objects to input @@ -2706,7 +2739,7 @@ arguments to be specified. For example:
At this time, only zero or one arguments may be converted.
-36.7.6.2 "typecheck" typemap
+38.7.6.2 "typecheck" typemap
The "typecheck" typemap is used to support overloaded @@ -2728,7 +2761,7 @@ program uses overloaded methods, you should also define a collection of "typecheck" typemaps. More details about this follow in a later section on "Typemaps and Overloading."
-36.7.6.3 "out" typemap
+38.7.6.3 "out" typemap
Converts return value of a C function @@ -2779,7 +2812,7 @@ version of the C datatype matched by the typemap.
36.7.6.4 "arginit" typemap
+38.7.6.4 "arginit" typemap
The "arginit" typemap is used to set the initial value of a @@ -2794,7 +2827,7 @@ applications. For example:
}36.7.6.5 "default" typemap
+38.7.6.5 "default" typemap
The "default" typemap is used to turn an argument into a @@ -2815,11 +2848,11 @@ not support optional arguments, such as Java and C#, effectively ignore the value specified by this typemap as all arguments must be given.
Once a default typemap has been applied to an argument, all -arguments that follow must have default values. See the +arguments that follow must have default values. See the Default/optional arguments section for further information on default argument wrapping.
-36.7.6.6 "check" typemap
+38.7.6.6 "check" typemap
The "check" typemap is used to supply value checking code @@ -2834,7 +2867,7 @@ arguments have been converted. For example:
}36.7.6.7 "argout" typemap
+38.7.6.7 "argout" typemap
The "argout" typemap is used to return values from arguments. @@ -2888,7 +2921,7 @@ some function like SWIG_Ruby_AppendOutput.
See the typemaps.i library for examples.
-36.7.6.8 "freearg" typemap
+38.7.6.8 "freearg" typemap
The "freearg" typemap is used to cleanup argument data. It is @@ -2915,7 +2948,7 @@ This code is also placed into a special variable $cleanup that may be used in other typemaps whenever a wrapper function needs to abort prematurely.
-36.7.6.9 "newfree" typemap
+38.7.6.9 "newfree" typemap
The "newfree" typemap is used in conjunction with the %newobject @@ -2939,7 +2972,7 @@ string *foo();
See Object ownership and %newobject for further details.
-The "memberin" typemap is used to copy data from an @@ -2957,21 +2990,21 @@ example:
already provides a default implementation for arrays, strings, and other objects. -The "varin" typemap is used to convert objects in the target language to C for the purposes of assigning to a C/C++ global variable. This is implementation specific.
-The "varout" typemap is used to convert a C/C++ object to an object in the target language when reading a C/C++ global variable. This is implementation specific.
-The "throws" typemap is only used when SWIG parses a C++ @@ -3009,10 +3042,10 @@ catch(char const *_e) {
Note that if your methods do not have an exception specification yet they do throw exceptions, SWIG cannot know how to -deal with them. For a neat way to handle these, see the Exception +deal with them. For a neat way to handle these, see the Exception handling with %exception section.
-Converts C++ objects in director @@ -3071,7 +3104,7 @@ referring to the class itself.
Converts Ruby objects in director @@ -3144,7 +3177,7 @@ exception.
-Output argument processing in director @@ -3202,19 +3235,19 @@ referring to the instance of the class itself
Cleanup of function return values
-Setting of C global variables
-@@ -3264,7 +3297,7 @@ so that their values can be properly assigned.
When you write a typemap, you usually have to work directly @@ -3279,7 +3312,7 @@ stick to the swig functions instead of the native Ruby functions. That should help you avoid having to rewrite a lot of typemaps across multiple languages.
-Here, while the Ruby versions return the value directly, the SWIG @@ -3389,7 +3422,7 @@ versions do not, but return a status value to indicate success (SWIG_OK -
RSTRING_LEN(str)
@@ -3412,7 +3445,7 @@ versions do not, but return a status value to indicate success (SWIG_OK void rb_raise(VALUE exception, const char *fmt,
@@ -3491,7 +3524,7 @@ message to standard error if Ruby was invoked with the -w
flag. The given format string fmt and remaining
arguments are interpreted as with printf().
-36.7.8.5 Iterators
+38.7.8.5 Iterators
void rb_iter_break()
@@ -3537,14 +3570,14 @@ VALUE), VALUE value)This section includes a few examples of typemaps. For more examples, you might look at the examples in the Example/ruby directory.
-A common problem in many C programs is the processing of @@ -3609,7 +3642,7 @@ array. Since dynamic memory allocation is used to allocate memory for the array, the "freearg" typemap is used to later release this memory after the execution of the C function.
-Ruby's solution to the "keyword arguments" capability of some @@ -3823,7 +3856,7 @@ memory leak. Fortunately, this typemap is a lot easier to write:
program that uses the extension, can be found in the Examples/ruby/hashargs directory of the SWIG distribution. -Occasionally, it might be necessary to convert pointer values @@ -3882,7 +3915,7 @@ For example:
} - VALUE Data_Wrap_Struct(VALUE class, void
@@ -3909,7 +3942,7 @@ as above.
type c-type from the data object obj
and assigns that pointer to ptr.
-36.7.13 Example: STL Vector to Ruby Array
+38.7.13 Example: STL Vector to Ruby Array
Another use for macros and type maps is to create a Ruby array @@ -4001,7 +4034,7 @@ STL with ruby, you are advised to use the standard swig STL library, which does much more than this. Refer to the section called the C++ Standard Template Library. -
@@ -4035,7 +4068,7 @@ generate ri documentation from a c wrap file, you could do:
$ rdoc -r file_wrap.c -@@ -4065,7 +4098,7 @@ layout of controls on a panel, etc. to be loaded from an XML file." %module(docstring=DOCSTRING) xrc -
Since SWIG does know everything about the function it wraps, @@ -4086,7 +4119,7 @@ several options for autodoc controlled by the value given to the feature, described below.
-@@ -4110,7 +4143,7 @@ Then Ruby code like this will be generated: ... -
@@ -4130,7 +4163,7 @@ this: ... -
@@ -4142,7 +4175,7 @@ parameter types with the "2" option will result in Ruby code like this:
-@@ -4157,13 +4190,13 @@ this:
function_name(int x, int y, Foo foo=nil, Bar bar=nil) -> bool Parameters: - x - int - y - int - foo - Foo - bar - Bar+ x - int + y - int + foo - Foo + bar - Bar -
@@ -4179,7 +4212,7 @@ generated string. For example: void GetPosition(int* OUTPUT, int* OUTPUT); -
@@ -4190,10 +4223,10 @@ docstring associated with classes, function or methods are output. If an item already has an autodoc string then it is combined with the docstring and they are output together.
-SWIG allows operator overloading with, by using the %extend @@ -4374,7 +4407,7 @@ separate method for handling inequality since Ruby parses the expression a != b as !(a == b).
-The chapter on Working @@ -4458,7 +4491,7 @@ and then type make to build the shared library:
$ ruby extconf.rb creating Makefile $ make -g++ -fPIC -g -O2 -I. -I/usr/local/lib/ruby/1.7/i686-linux \ +g++ -fPIC -g -O2 -I. -I/usr/include/ruby-2.1.0 \ -I. -c shape_wrap.cxx gcc -shared -L/usr/local/lib -o shape.so shape_wrap.o -L. \ -lruby -lruby -lc@@ -4500,7 +4533,7 @@ irb(main):005:0> c.getX() 5.0 -
The Ruby language doesn't support multiple inheritance, but @@ -4567,7 +4600,7 @@ matching rules used for other kinds of features apply (see the chapter on "Customization Features") for more details).
-One of the most common issues in generating SWIG bindings for @@ -4590,7 +4623,7 @@ to C++ (or vice versa) depending on what function or methods are invoked. Clearly, developing a SWIG wrapper requires a thorough understanding of how the underlying library manages memory.
-Ruby uses a mark and sweep garbage collector. When the garbage @@ -4604,8 +4637,7 @@ objects that have already been marked). Those objects, in turn, may reference other objects. This process will continue until all active objects have been "marked." After the mark phase comes the sweep phase. In the sweep phase, all objects that have not been marked will be -garbage collected. For more information about the Ruby garbage -collector please refer to http://rubygarden.org/ruby/ruby?GCAndExtensions.
+garbage collected.The Ruby C/API provides extension developers two hooks into the garbage collector - a "mark" function and a "sweep" function. By @@ -4622,7 +4654,7 @@ any memory has been allocated in creating the underlying C struct or C++ struct, then a "free" function must be defined that deallocates this memory.
-As described above, memory management depends on clearly @@ -4682,7 +4714,7 @@ public: C++ constructor, thus creating a new foo object. By default, SWIG will assign the new Ruby object a "free" function. When the Ruby object is garbage collected, the "free" function will be -called. It in turn will call Foo's destructor.
+called. It in turn will call Foo's destructor.Next, consider this code:
@@ -4767,7 +4799,7 @@ public:This code can be seen in swig/examples/ruby/tracking.
-The remaining parts of this section will use the class library @@ -4804,7 +4836,7 @@ public: class Zoo { protected: - std::vector<animal *=""> animals; + std::vector<Animal *> animals; public: // Construct an empty zoo @@ -4927,7 +4959,8 @@ class-by-class basis if needed. To fix the example above:
/* Tell SWIG that create_animal creates a new object */ %newobject Zoo::create_animal; -/* Tell SWIG to keep track of mappings between C/C++ structs/classes. */%trackobjects; +/* Tell SWIG to keep track of mappings between C/C++ structs/classes. */ +%trackobjects; %include "example.h" @@ -4989,10 +5022,10 @@ object from its underlying C++ object.In general, you will only need to use the SWIG_RubyInstanceFor, which is required for implementing mark functions as shown below. However, if you implement your own free functions (see below) you may -also have to call the SWIG_RubyRemoveTracking and RubyUnlinkObjects +also have to call the SWIG_RubyRemoveTracking and RubyUnlinkObjects methods.
-With a bit more testing, we see that our class library still @@ -5087,7 +5120,7 @@ static void mark_Zoo(void* ptr) {
Note the mark function is dependent on the SWIG_RUBY_InstanceFor method, and thus requires that %trackobjects is enabled. For more -information, please refer to the track_object.i test case in the SWIG +information, please refer to the ruby_track_objects.i test case in the SWIG test suite.
When this code is compiled we now see:
@@ -5121,7 +5154,7 @@ irb(main):016:0>This code can be seen in swig/examples/ruby/mark_function.
-By default, SWIG creates a "free" function that is called when @@ -5154,21 +5187,23 @@ above.
To show how to use the %freefunc directive, let's slightly change our example. Assume that the zoo -object is responsible for freeing animal that it contains. This means +object is responsible for freeing any animal that it contains. This means that the Zoo::add_animal function should be marked with a DISOWN typemap and the destructor should be updated as below:
Zoo::~Zoo() { - IterType iter = this->animals.begin(); - IterType end = this->animals.end(); - - for(iter; iter != end; ++iter) { - Animal* animal = *iter; - delete animal; - } -}+
+Zoo::~Zoo() { + IterType iter = this->animals.begin(); + IterType end = this->animals.end(); + + for(iter; iter != end; ++iter) { + Animal* animal = *iter; + delete animal; + } +} +
When we use these objects in IRB we see:
@@ -5216,8 +5251,7 @@ existing Ruby object to the destroyed C++ object and raise an exception. #include "example.h" %} -/* Specify that ownership is transferred to the zoo - when calling add_animal */ +/* Specify that ownership is transferred to the zoo when calling add_animal */ %apply SWIGTYPE *DISOWN { Animal* animal }; /* Track objects */ @@ -5288,7 +5322,7 @@ been freed, and thus raises a runtime exception.This code can be seen in swig/examples/ruby/free_function.
-As has been said, the Ruby GC runs and marks objects before @@ -5343,7 +5377,7 @@ used for callbacks, for example.
To solve the problem, SWIG can now generate code with director functions containing the optional macros SWIG_INIT_STACK and SWIG_RELEASE_STACK. These macros will try to force Ruby to -reinitiliaze the beginning of the stack the first time a +reinitialize the beginning of the stack the first time a director function is called. This will lead Ruby to measure and not collect any VALUE objects defined from that point on.
diff --git a/Doc/Manual/SWIG.html b/Doc/Manual/SWIG.html index 25dc899..bf1705d 100644 --- a/Doc/Manual/SWIG.html +++ b/Doc/Manual/SWIG.html @@ -1,12 +1,13 @@ - +@@ -110,7 +111,7 @@ where filename is a SWIG interface file or a C/C++ header file. Below is a subset of options that can be used. Additional options are also defined for each target language. A full list can be obtained by typing swig -help or swig --lang -help. +-<lang> -help for language <lang> specific options.
@@ -119,25 +120,31 @@ can be obtained by typing swig -help or swig -clisp Generate CLISP wrappers -cffi Generate CFFI wrappers -csharp Generate C# wrappers +-d Generate D wrappers -go Generate Go wrappers -guile Generate Guile wrappers -java Generate Java wrappers +-javascript Generate Javascript wrappers -lua Generate Lua wrappers -modula3 Generate Modula 3 wrappers -mzscheme Generate Mzscheme wrappers -ocaml Generate Ocaml wrappers +-octave Generate Octave wrappers -perl Generate Perl wrappers -php Generate PHP wrappers -pike Generate Pike wrappers -python Generate Python wrappers -r Generate R (aka GNU S) wrappers -ruby Generate Ruby wrappers +-scilab Generate Scilab wrappers -sexp Generate Lisp S-Expressions wrappers -tcl Generate Tcl wrappers -uffi Generate Common Lisp / UFFI wrappers -xml Generate XML wrappers -c++ Enable C++ parsing +-cppext ext Change file extension of C++ generated files to ext + (default is cxx, except for PHP which uses cpp) -Dsymbol Define a preprocessor symbol -Fstandard Display error/warning messages in commonly used format -Fmicrosoft Display error/warning messages in Microsoft format @@ -145,8 +152,9 @@ can be obtained by typing swig -help or swig -Idir Add a directory to the file include path -lfile Include a SWIG library file. -module name Set the name of the SWIG module --o outfile Name of output file --outcurrentdir Set default output dir to current dir instead of input file's path +-o outfile Set name of C/C++ output file to <outfile> +-oh headfile Set name of C++ output header file for directors to <headfile> +-outcurrentdir Set default output dir to current dir instead of input file's path -outdir dir Set language specific files output directory -pcreversion Display PCRE version information -swiglib Show location of SWIG library @@ -154,7 +162,7 @@ can be obtained by typing swig -help or swig
@@ -201,7 +209,7 @@ semantics in SWIG is analogous to that of the declarations section used in input files to parser generation tools such as yacc or bison.
-@@ -211,7 +219,7 @@ additional files depending on the target language. By default, an input file with the name file.i is transformed into a file file_wrap.c or file_wrap.cxx (depending on whether or not the -c++ option has been used). The name of the -output file can be changed using the -o option. In certain +output C/C++ file can be changed using the -o option. In certain cases, file suffixes are used by the compiler to determine the source language (C, C++, etc.). Therefore, you have to use the -o option to change the suffix of the SWIG-generated wrapper @@ -224,7 +232,7 @@ $ swig -c++ -python -o example_wrap.cpp example.i
The C/C++ output file created by SWIG often -contains everything that is needed to construct a extension module +contains everything that is needed to construct an extension module for the target scripting language. SWIG is not a stub compiler nor is it usually necessary to edit the output file (and if you look at the output, you probably won't want to). To build the final extension module, the @@ -233,7 +241,7 @@ program to create a shared library.
-Many target languages will also generate proxy class files in the +For many target languages SWIG will also generate proxy class files in the target language. The default output directory for these language specific files is the same directory as the generated C/C++ file. This can be modified using the -outdir option. For example: @@ -258,10 +266,10 @@ this option the default output directory is the path to the input file. If -o and -outcurrentdir are used together, -outcurrentdir is effectively ignored as the output directory for the language files is the same directory as the -generated C/C++ file if not overidden with -outdir. +generated C/C++ file if not overridden with -outdir.
-@@ -271,7 +279,7 @@ documentation files. However, this feature is currently under repair and will reappear in a later SWIG release.
-@@ -295,7 +303,7 @@ make it more powerful than the normal C preprocessor. These extensions are described in the "Preprocessor" chapter.
-@@ -326,7 +334,7 @@ included in C header files using conditional compilation like this: it is parsing an input file.
-@@ -424,7 +432,7 @@ does not utilize a separate typedef-name terminal symbol as described on p. 234 of K&R).
-@@ -484,10 +492,10 @@ Or in Python: Whenever possible, SWIG creates an interface that closely matches the underlying C/C++ code. However, due to subtle differences between languages, run-time environments, and semantics, it is not always possible to do so. The -next few sections describes various aspects of this mapping. +next few sections describe various aspects of this mapping.
-@@ -612,7 +620,7 @@ will use the same internal representation (e.g., UCS-2 vs. UCS-4). You may need to write some special conversion functions.
-@@ -667,7 +675,7 @@ Earlier versions of SWIG incorrectly handled const and created constants instead.
-@@ -728,7 +736,7 @@ However, for the same conservative reasons even a constant with a simple cast wi
-#define F_CONST (double) 5 // A floating pointer constant with cast +#define F_CONST (double) 5 // A floating point constant with cast
The %constant directive is used to more precisely create constants corresponding to different C datatypes. Although it is not -usually not needed for simple values, it is more useful when working +usually needed for simple values, it is more useful when working with pointers and other more complex datatypes. Typically, %constant is only used when you want to add constants to the scripting language interface that are not defined in the original header file.
-@@ -858,7 +866,7 @@ const int spam = 42;
@@ -868,7 +876,7 @@ from a scripting language to a C char *, the pointer usually points to string data stored inside the interpreter. It is almost always a really bad idea to modify this data. Furthermore, some languages may explicitly disallow it. For instance, in Python, -strings are supposed be immutable. If you violate this, you will probably +strings are supposed to be immutable. If you violate this, you will probably receive a vast amount of wrath when you unleash your module on the world.
@@ -897,7 +905,7 @@ input values. However, it must be noted that you could change the behavior of using typemaps. -@@ -905,7 +913,7 @@ Most C programs manipulate arrays, structures, and other types of objects. This discusses the handling of these datatypes.
-@@ -971,7 +979,7 @@ simplified and less prone to error. -
@@ -993,7 +1001,7 @@ as sentinel values or to denote a missing/empty value. Therefore, SWIG leaves NULL pointer checking up to the application.
-@@ -1034,23 +1042,22 @@ expect :
# Copy a file def filecopy(source,target): - f1 = fopen(source,"r") - f2 = fopen(target,"w") - buffer = malloc(8192) - nbytes = fread(buffer,8192,1,f1) - while (nbytes > 0): - fwrite(buffer,8192,1,f2) - nbytes = fread(buffer,8192,1,f1) - free(buffer) - + f1 = fopen(source,"r") + f2 = fopen(target,"w") + buffer = malloc(8192) + nbytes = fread(buffer,8192,1,f1) + while (nbytes > 0): + fwrite(buffer,8192,1,f2) + nbytes = fread(buffer,8192,1,f1) + free(buffer)
-In this case f1, f2, and buffer are all +In this case f1, f2, and buffer are all opaque objects containing C pointers. It doesn't matter what value they contain--our program works just fine without this knowledge.
-@@ -1110,7 +1117,7 @@ The only way to fix this problem is to make sure you properly declare type names -
@@ -1199,7 +1206,7 @@ The corresponding wrapper function will accept arguments of type unsigned int * or size_t *.
-@@ -1209,7 +1216,7 @@ more difficult to map to a scripting language interface. This section describes some of these issues.
-@@ -1240,7 +1247,7 @@ to Vectors instead of Vectors. For the most part, this transformation is transparent so you might not notice.
-@@ -1295,7 +1302,7 @@ don't work correctly if Vector doesn't define a default constructor. The section on SWIG and C++ has more information about this case.
-@@ -1312,10 +1319,10 @@ gets mapped to an underlying pair of set/get functions like this :
Vector *unit_i_get() { - return &unit_i; + return &unit_i; } void unit_i_set(Vector *value) { - unit_i = *value; + unit_i = *value; }
@@ -1456,7 +1463,7 @@ value is not released. -
@@ -1483,7 +1490,7 @@ void transpose(double (*a)[20]);
Like C, SWIG does not perform array bounds checking. It is up to the -user to make sure the pointer points a suitably allocated region of memory. +user to make sure the pointer points to a suitably allocated region of memory.
@@ -1592,7 +1599,7 @@ void pathname_set(char *value) { In the target language, the value can be set like a normal variable.
-@@ -1602,11 +1609,11 @@ directive as shown :
// File : interface.i -int a; // Can read/write +int a; // Can read/write %immutable; -int b,c,d // Read only variables +int b,c,d; // Read only variables %mutable; -double x,y // read/write +double x,y; // read/write
@@ -1666,10 +1673,10 @@ generate a warning message. Simply change the directives to %immutable;%mutable; to silence the warning. Don't forget the extra semicolon!
-@@ -1711,7 +1718,7 @@ wrapping a header file like this:
-%rename applies a renaming operation to all future +%rename applies a renaming operation to all future occurrences of a name. The renaming applies to functions, variables, class and structure names, member functions, and member data. For example, if you had two-dozen C++ classes, all with a member function @@ -1767,7 +1774,7 @@ This directive is still supported, but it is deprecated and should probably be a directive is more powerful and better supports wrapping of raw header file information.
-@@ -1882,17 +1889,35 @@ and a more descriptive one, but the two functions are otherwise equivalent:
@@ -2056,7 +2081,7 @@ wrap C++ overloaded functions and methods or C++ methods which use default argum
-@@ -2098,7 +2123,7 @@ members of the class, so when the chosen class is unignored, all of its methods -
@@ -2115,8 +2140,8 @@ default arguments are optional in the target language. For example, this functio used in Tcl as follows :
-% plot -3.4 7.5 # Use default value -% plot -3.4 7.5 10 # set color to 10 instead +% plot -3.4 7.5 # Use default value +% plot -3.4 7.5 10 # set color to 10 instead
@@ -2254,7 +2279,7 @@ disabled using %nocallback. When you do this, the interface now works
Notice that when the function is used as a callback, special names -such as add_cb is used instead. To call the function +such as add_cb are used instead. To call the function normally, just use the original function name such as add().
@@ -2288,7 +2313,7 @@ See the Typemaps chapter for more about typ and individual target language chapters for more on callbacks and the 'director' feature. -@@ -2300,13 +2325,13 @@ handle C++ are described in the next section. If SWIG encounters the definition of a structure or union, it creates a set of accessor functions. Although SWIG does not need structure definitions to build an interface, providing definitions -make it possible to access structure members. The accessor functions +makes it possible to access structure members. The accessor functions generated by SWIG simply take a pointer to an object and allow access to an individual member. For example, the declaration :
struct Vector { - double x,y,z; + double x,y,z; }
double Vector_x_get(struct Vector *obj) { - return obj->x; + return obj->x; } double Vector_y_get(struct Vector *obj) { - return obj->y; + return obj->y; } double Vector_z_get(struct Vector *obj) { - return obj->z; + return obj->z; } void Vector_x_set(struct Vector *obj, double value) { - obj->x = value; + obj->x = value; } void Vector_y_set(struct Vector *obj, double value) { - obj->y = value; + obj->y = value; } void Vector_z_set(struct Vector *obj, double value) { - obj->z = value; + obj->z = value; }
@@ -2379,7 +2404,7 @@ programs :
typedef struct { - double x,y,z; + double x,y,z; } Vector;
double Vector_x_get(Vector *obj) { - return obj->x; + return obj->x; }
typedef struct vector_struct { - double x,y,z; + double x,y,z; } Vector;
Structures involving character strings require some care. SWIG assumes that all members of type char * have been dynamically allocated using malloc() and that they are NULL-terminated -ASCII strings. When such a member is modified, the previously contents +ASCII strings. When such a member is modified, the previous contents will be released, and the new contents allocated. For example :
%module mymodule ... struct Foo { - char *name; - ... + char *name; + ... }
char *Foo_name_get(Foo *obj) { - return Foo->name; + return Foo->name; } char *Foo_name_set(Foo *obj, char *c) { - if (obj->name) free(obj->name); - obj->name = (char *) malloc(strlen(c)+1); - strcpy(obj->name,c); - return obj->name; + if (obj->name) + free(obj->name); + obj->name = (char *) malloc(strlen(c)+1); + strcpy(obj->name,c); + return obj->name; }
@@ -2485,7 +2511,7 @@ discussed in a later chapter. In many cases, the warning message is harmless.
-@@ -2508,7 +2534,7 @@ typedef struct Bar {
When a structure member is wrapped, it is handled as a pointer, unless the %naturalvar directive is used where it is handled more like a C++ reference (see C++ Member data). -The accessors to the member variable as a pointer is effectively wrapped as follows: +The accessors to the member variable as a pointer are effectively wrapped as follows:
@@ -2645,8 +2671,8 @@ struct Bar { // Default constructor generated.
-Since ignoring the implicit or default destructors most of the times -produce memory leaks, SWIG will always try to generate them. If +Since ignoring the implicit or default destructors most of the time +produces memory leaks, SWIG will always try to generate them. If needed, however, you can selectively disable the generation of the default/implicit destructor by using %nodefaultdtor
@@ -2676,11 +2702,11 @@ has now been enabled as the default behavior. Note: There are also the -nodefault option and %nodefault directive, which disable both the default or implicit destructor generation. This could lead to memory leaks across -the target languages, and is highly recommended you don't use them. +the target languages, and it is highly recommended you don't use them. -@@ -2700,7 +2726,7 @@ the following declaration :
/* file : vector.h */ ... typedef struct Vector { - double x,y,z; + double x,y,z; } Vector;typedef struct Integer { - int value; + int value; } Int; %extend Integer { ... } /* Correct name */ %extend Int { ... } /* Incorrect name */ struct Float { - float value; + float value; }; typedef struct Float FloatValue; %extend Float { ... } /* Correct name */ @@ -2852,7 +2878,7 @@ There is one exception to this rule and that is when the struct is anonymously n@@ -2953,7 +2979,7 @@ be used to extend a structure with more than just methods, a more suitable directive name has been chosen. -typedef struct { - double value; + double value; } Double; %extend Double { ... } /* Okay */5.5.7 Nested structures
+5.5.7 Nested structures
@@ -2961,13 +2987,13 @@ Occasionally, a C program will involve structures like this :
@@ -2979,15 +3005,15 @@ following:typedef struct Object { - int objtype; - union { - int ivalue; - double dvalue; - char *strvalue; - void *ptrvalue; - } intRep; + int objtype; + union { + int ivalue; + double dvalue; + char *strvalue; + void *ptrvalue; + } intRep; } Object;@@ -2999,16 +3025,16 @@ structures. In this case, functions like this would be created :typedef union { - int ivalue; - double dvalue; - char *strvalue; - void *ptrvalue; + int ivalue; + double dvalue; + char *strvalue; + void *ptrvalue; } Object_intRep; typedef struct Object { - int objType; - Object_intRep intRep; + int objType; + Object_intRep intRep; } Object;-Object_intRep *Object_intRep_get(Object *o) { - return (Object_intRep *) &o->intRep; + return (Object_intRep *) &o->intRep; } int Object_intRep_ivalue_get(Object_intRep *o) { - return o->ivalue; + return o->ivalue; } int Object_intRep_ivalue_set(Object_intRep *o, int value) { - return (o->ivalue = value); + return (o->ivalue = value); } double Object_intRep_dvalue_get(Object_intRep *o) { - return o->dvalue; + return o->dvalue; } ... etc ... @@ -3037,7 +3063,7 @@ Finally, note that nesting is handled differently in C++ mode, see Nested classes. -5.5.8 Other things to note about structure wrapping
+5.5.8 Other things to note about structure wrapping
@@ -3099,7 +3125,7 @@ interface described here, most of SWIG's language modules use it in some way or another.
-5.6 Code Insertion
+5.6 Code Insertion
@@ -3109,7 +3135,7 @@ additional C code to perform initialization or other operations. There are four common ways to insert code, but it's useful to know how the output of SWIG is structured first.
-5.6.1 The output of SWIG
+5.6.1 The output of SWIG
@@ -3145,7 +3171,7 @@ the module upon loading. -
5.6.2 Code insertion blocks
+5.6.2 Code insertion blocks
@@ -3215,7 +3241,7 @@ program. For example :
%{ /* Create a new vector */ static Vector *new_Vector() { - return (Vector *) malloc(sizeof(Vector)); + return (Vector *) malloc(sizeof(Vector)); } %} @@ -3223,7 +3249,7 @@ static Vector *new_Vector() { Vector *new_Vector();5.6.3 Inlined code blocks
+5.6.3 Inlined code blocks
@@ -3235,7 +3261,7 @@ there is a special inlined form of code block that is used as follows %inline %{ /* Create a new vector */ Vector *new_Vector() { - return (Vector *) malloc(sizeof(Vector)); + return (Vector *) malloc(sizeof(Vector)); } %} @@ -3250,7 +3276,7 @@ declaration. Since the code inside an %inline %{ ... %} block is given to both the C compiler and SWIG, it is illegal to include any SWIG directives inside a %{ ... %} block.
-5.6.4 Initialization blocks
+5.6.4 Initialization blocks
@@ -3261,19 +3287,19 @@ initialization on module loading, you could write this:
-%init %{ - init_variables(); + init_variables(); %}5.7 An Interface Building Strategy
+5.7 An Interface Building Strategy
-This section describes the general approach for building interface +This section describes the general approach for building interfaces with SWIG. The specifics related to a particular scripting language are found in later chapters.
-5.7.1 Preparing a C program for SWIG
+5.7.1 Preparing a C program for SWIG
@@ -3284,9 +3310,9 @@ of steps you can follow to make an interface for a C program :
-The preferred method of using SWIG is to generate separate interface +The preferred method of using SWIG is to generate a separate interface file. Suppose you have the following C header file :
@@ -3380,7 +3406,7 @@ The main advantage of this approach is minimal maintenance of an interface file In more complex projects, an interface file containing numerous %include and #include statements like this is one of the most common approaches to interface file design due to lower maintenance overhead. -5.7.3 Why use separate interface files?
+5.7.3 Why use separate interface files?
@@ -3409,7 +3435,7 @@ and immediately see what is available without having to dig it out of header files. -
5.7.4 Getting the right header files
+5.7.4 Getting the right header files
@@ -3425,11 +3451,11 @@ include certain header files by using a %{,%} block like this: #include <GL/glu.h> %} -// Put rest of declarations here +// Put the rest of the declarations here ...
@@ -3467,7 +3493,7 @@ program that is more interactive. In many cases, the old or Tcl script.
-Note: If some cases, you might be inclined to create a +Note: In some cases, you might be inclined to create a scripting language wrapper for main(). If you do this, the compilation will probably work and your module might even load correctly. The only trouble is that when you call your diff --git a/Doc/Manual/SWIGDocumentation.html b/Doc/Manual/SWIGDocumentation.html index 369663d..597581c 100644 --- a/Doc/Manual/SWIGDocumentation.html +++ b/Doc/Manual/SWIGDocumentation.html @@ -1,9 +1,10 @@
-Last update : SWIG-3.0.10 (12 Jun 2016)
+SWIG (Simplified Wrapper and Interface Generator) is a software development tool for building scripting language interfaces to C and C++ programs. Originally developed in 1995, SWIG was first used by @@ -2079,7 +2416,7 @@ PRE { font-family: monospace } it has since evolved into a general purpose tool that is used in a wide variety of applications--in fact almost anything where C/C++ programming is involved.
-In the late 1990's, the most stable version of SWIG was release 1.1p5. Versions 1.3.x were officially development versions and these were released over a period of 10 years starting from the year 2000. @@ -2087,7 +2424,7 @@ PRE { font-family: monospace } 1.3.x series had been stable for many years. An official stable version was released along with the decision to make SWIG license changes and this gave rise to version 2.0.0 in 2010.
-The LICENSE file shipped with SWIG in the top level directory contains the SWIG license. For further insight into the license including the license of SWIG's output code, please visit the SWIG @@ -2097,7 +2434,7 @@ http://www.swig.org/legal.html
The official location of SWIG related material is
@@ -2123,7 +2460,7 @@ http://www.swig.org/legal.html. SWIG Bleeding Edge
This manual assumes that you know how to write C/C++ programs and that you have at least heard of scripting languages such as Tcl, Python, and Perl. A detailed knowledge of these scripting languages is @@ -2141,20 +2478,20 @@ http://www.swig.org/legal.html.
of the gory details, you will almost certainly want to consult a good C++ reference. If you don't program in C++, you may just want to skip those parts of the manual. -The first few chapters of this manual describe SWIG in general and provide an overview of its capabilities. The remaining chapters are devoted to specific SWIG language modules and are self contained. Thus, if you are using SWIG to build Python interfaces, you can probably skip to that chapter and find almost everything you need to know.
-If you hate reading manuals, glance at the "Introduction" which contains a few simple examples. These examples contain about 95% of everything you need to know to use SWIG. After that, simply use the language-specific chapters as a reference. The SWIG distribution also comes with a large directory of examples that illustrate different topics.
-If you are a previous user of SWIG, don't expect SWIG to provide complete backwards compatibility. Although the developers strive to the utmost to keep backwards compatibility, this isn't always possible as @@ -2179,12 +2516,12 @@ http://www.swig.org/legal.html.
Note: The version symbol is not defined in the generated SWIG wrapper file. The SWIG preprocessor has defined SWIG_VERSION since SWIG-1.3.11.
-The CHANGES.current, CHANGES and RELEASENOTES files shipped with SWIG in the top level directory contain, respectively, detailed release notes for the current version, detailed release notes for previous releases and summary release notes from SWIG-1.3.22 onwards.
-SWIG is an unfunded project that would not be possible without the contributions of many people working in their spare time. If you have benefitted from using SWIG, please consider @@ -2192,7 +2529,7 @@ Donating to SWIG to keep development going. There have been a large varied number of people who have made contributions at all levels over time. Contributors are mentioned either in the COPYRIGHT file or CHANGES files shipped with SWIG or in submitted bugs.
-Although every attempt has been made to make SWIG bug-free, we are also trying to make feature improvements that may introduce bugs. To report a bug, either send mail to the SWIG developer list at the @@ -2202,16 +2539,21 @@ SWIG bug tracker. In your report, be as specific as possible, occurred), corresponding portions of the SWIG interface file used, and any important pieces of the SWIG generated wrapper code. We can only fix bugs if we know about them.
-Please see the dedicated Windows chapter - for instructions on installing SWIG on Windows and running the - examples. The Windows distribution is called swigwin and includes a - prebuilt SWIG executable, swig.exe, included in the top level - directory. Otherwise it is exactly the same as the main SWIG - distribution. There is no need to download anything else.
-Please see the dedicated Windows chapter for + instructions on installing SWIG on Windows and running the examples. + The Windows distribution is called swigwin and includes a prebuilt SWIG + executable, swig.exe, included in the top level directory. Otherwise it + is exactly the same as the main SWIG distribution. There is no need to + download anything else.
+These installation instructions are for using the distributed + tarball, for example, swig-3.0.8.tar.gz. If you wish to build + and install from source on Github, extra steps are required. Please see + the Bleeding Edge page on the + SWIG website.
You must use GNU make to build and install SWIG.
PCRE needs to be installed on @@ -2263,9 +2605,9 @@ $ ./configure --help.
SWIG used to include a set of runtime libraries for some languages for working with multiple modules. These are no longer built during the installation stage. However, users can build them just like any wrapper - module as described in the Modules chapter. - The CHANGES file shipped with SWIG in the top level directory also - lists some examples which build the runtime library.
+ module as described in the Modules chapter. The + CHANGES file shipped with SWIG in the top level directory also lists + some examples which build the runtime library.Note:
SWIG is known to work on various flavors of OS X. Follow the Unix installation instructions above. However, as of this writing, there is still great deal of inconsistency with how shared libaries are handled @@ -2289,12 +2631,11 @@ $ ./configure --help. installation of software you might have. However, this is generally not the recommended technique for building larger extension modules. Instead, you should utilize Darwin's two-level namespaces. Some details - about this can be found here -http://developer.apple.com/documentation/ReleaseNotes/DeveloperTools/TwoLevelNamespaces.html -.
+ about this can be found here +Understanding Two-Level Namespaces.Needless to say, you might have to experiment a bit to get things working at first.
-If you want to test SWIG after building it, a check can be performed on Unix operating systems. Type the following:
Note: The test-suite currently contains over 500 tests. If you have many different target languages installed and a slow machine, it might take more than an hour to run the test-suite.
-The Examples directory contains a variety of examples of using SWIG and it has some browsable documentation. Simply point your browser to the file "Example/index.html".
@@ -2342,7 +2683,7 @@ http://developer.apple.com/documentation/ReleaseNotes/DeveloperTools/TwoLevelNam Visual Studio will convert these old style project files into a current solution file.SWIG is a software development tool that simplifies the task of interfacing different languages to C and C++ programs. In a nutshell, SWIG is a compiler that takes C/C++ declarations and creates the wrappers needed to access those declarations from other languages - including including Perl, Python, Tcl, Ruby, Guile, and Java. SWIG - normally requires no modifications to existing code and can often be - used to build a usable interface in only a few minutes. Possible - applications of SWIG include:
+ including Perl, Python, Tcl, Ruby, Guile, and Java. SWIG normally + requires no modifications to existing code and can often be used to + build a usable interface in only a few minutes. Possible applications + of SWIG include:As stated in the previous section, the primary purpose of SWIG is to simplify the task of integrating C/C++ with other programming languages. However, why would anyone want to do that? To answer that @@ -2421,7 +2762,7 @@ http://developer.apple.com/documentation/ReleaseNotes/DeveloperTools/TwoLevelNam
To address these limitations, many programmers have arrived at the conclusion that it is much easier to use different programming @@ -2457,7 +2798,7 @@ http://developer.apple.com/documentation/ReleaseNotes/DeveloperTools/TwoLevelNam Therefore, it provides a wide variety of customization features that let you change almost every aspect of the language bindings. This is the main reason why SWIG has such a large user manual ;-).
-The best way to illustrate SWIG is with a simple example. Consider the following C code:
/* File : example.i */ @@ -2504,7 +2847,7 @@ extern int my_mod(int n, int m); module that will be created by SWIG. The %{ %} block provides a location for inserting additional code, such as C header files or additional C declarations, into the generated C wrapper code. -2.3.2 The swig command
+2.3.2 The swig command
SWIG is invoked using the swig command. We can use this to build a Tcl module (under Linux) as follows :
@@ -2531,15 +2874,15 @@ example_wrap.c that should be compiled along with the example.c loaded, Tcl can now access the functions and variables declared in the SWIG interface. A look at the file example_wrap.c reveals a hideous mess. However, you almost never need to worry about it. --2.3.3 Building a Perl5 module
+2.3.3 Building a Perl5 module
Now, let's turn these functions into a Perl5 module. Without making any changes type the following (shown for Solaris):
-unix > swig -perl5 example.i unix > gcc -c example.c example_wrap.c \ - -I/usr/local/lib/perl5/sun4-solaris/5.003/CORE -unix > ld -G example.o example_wrap.o -o example.so # This is for Solaris + -I/usr/local/lib/perl5/sun4-solaris/5.003/CORE +unix > ld -G example.o example_wrap.o -o example.so # This is for Solaris unix > perl5.003 use example; print example::fact(4), "\n"; @@ -2552,7 +2895,7 @@ print $example::My_variable + 4.5, "\n"; unix >2.3.4 Building a Python module
+2.3.4 Building a Python module
Finally, let's build a module for Python (shown for Irix).
-@@ -2572,7 +2915,7 @@ Type "copyright", "credits" or "license" for more 7.52.3.5 Shortcuts
+2.3.5 Shortcuts
To the truly lazy programmer, one may wonder why we needed the extra interface file at all. As it turns out, you can often do without it. For example, you could also build a Perl5 module by just running SWIG @@ -2581,7 +2924,7 @@ Type "copyright", "credits" or "license" for more
unix > swig -perl5 -module example example.h unix > gcc -c example.c example_wrap.c \ - -I/usr/local/lib/perl5/sun4-solaris/5.003/CORE + -I/usr/local/lib/perl5/sun4-solaris/5.003/CORE unix > ld -G example.o example_wrap.o -o example.so unix > perl5.003 use example; @@ -2594,8 +2937,8 @@ print $example::My_variable + 4.5, "\n"; 7.52.4 Supported C/C++ language - features
+2.4 Supported C/C++ language features +
A primary goal of the SWIG project is to make the language binding process extremely easy. Although a few simple examples have been shown, SWIG is quite capable in supporting most of C++. Some of the major @@ -2614,18 +2957,17 @@ print $example::My_variable + 4.5, "\n";
Currently, the only major C++ feature not supported is nested - classes--a limitation that should be removed in a future release, but - has some workarounds for the moment.
+Most of C++11 is also supported. Details are in the +C++11 section.
It is important to stress that SWIG is not a simplistic C++ lexing tool like several apparently similar wrapper generation tools. SWIG not only parses C++, it implements the full C++ type system and it is able to understand C++ semantics. SWIG generates its wrappers with full knowledge of this information. As a result, you will find SWIG to be just as capable of dealing with nasty corner cases as it is in wrapping - simple C++ code. In fact, SWIG is able handle C++ code that stresses + simple C++ code. In fact, SWIG is able to handle C++ code that stresses the very limits of many C++ compilers.
-When used as intended, SWIG requires minimal (if any) modification to existing C or C++ code. This makes SWIG extremely easy to use with existing packages and promotes software reuse and modularity. By making @@ -2633,8 +2975,8 @@ print $example::My_variable + 4.5, "\n"; the interface and reuse the code in other applications. It is also possible to support different types of interfaces depending on the application.
-SWIG is a command line tool and as such can be incorporated into any build system that supports invoking external tools/compilers. SWIG is most commonly invoked from within a Makefile, but is also known to be @@ -2650,13 +2992,13 @@ http://www.gnu.org/software/autoconf-archive/ax_pkg_swig.html#ax_pkg_swig Autoconf Archive for further information on this and other Autoconf macros.
There is growing support for SWIG in some build tools, for example CMake is a cross-platform, open-source - build manager with built in support for SWIG. CMake can detect the SWIG +href="http://cmake.org">CMake is a cross-platform, open-source build + manager with built in support for SWIG. CMake can detect the SWIG executable and many of the target language libraries for linking against. CMake knows how to build shared libraries and loadable modules on many different operating systems. This allows easy cross platform - SWIG development. It also can generate the custom commands necessary - for driving SWIG from IDE's and makefiles. All of this can be done from + SWIG development. It can also generate the custom commands necessary + for driving SWIG from IDEs and makefiles. All of this can be done from a single cross platform input file. The following example is a CMake input file for creating a python wrapper for the SWIG interface file, example.i:
@@ -2687,7 +3029,7 @@ SWIG_LINK_LIBRARIES(example ${PYTHON_LIBRARIES}) SWIG and compile the generated C++ files into _example.so (UNIX) or _example.pyd (Windows). For other target languages on Windows a dll, instead of a .pyd file, is usually generated. -SWIG is designed to produce working code that needs no hand-modification (in fact, if you look at the output, you probably won't want to modify it). You should think of your target language @@ -2695,7 +3037,7 @@ SWIG_LINK_LIBRARIES(example ${PYTHON_LIBRARIES}) resulting output file. While this approach may limit flexibility for hard-core hackers, it allows others to forget about the low-level implementation details.
-No, this isn't a special section on the sorry state of world politics. However, it may be useful to know that SWIG was written with a certain "philosophy" about programming---namely that programmers are @@ -2706,7 +3048,7 @@ SWIG_LINK_LIBRARIES(example ${PYTHON_LIBRARIES}) On the other hand, this kind of freedom may be exactly what is needed to work with complicated and unusual C/C++ applications.
Ironically, the freedom that SWIG provides is countered by an - extremely conservative approach to code generation. At it's core, SWIG + extremely conservative approach to code generation. At its core, SWIG tries to distill even the most advanced C++ code down to a small well-defined set of interface building techniques based on ANSI C programming. Because of this, you will find that SWIG interfaces can be @@ -2714,9 +3056,14 @@ SWIG_LINK_LIBRARIES(example ${PYTHON_LIBRARIES}) used on any platform. Again, this is an important part of staying out of the programmer's way----the last thing any developer wants to do is to spend their time debugging the output of a tool that relies on - non-portable or unreliable programming features.
+ non-portable or unreliable programming features. Dependencies are often + a source of incompatibilities and problems and so additional third + party libraries are not used in the generated code. SWIG will also + generally avoid generating code that introduces a dependency on the C++ + Standard Template Library (STL). SWIG will generate code that depends + on the C libraries though.SWIG does not come with the usual Windows type installation program, however it is quite easy to get started. The main steps are:
The swigwin distribution contains the SWIG Windows executable, swig.exe, which will run on 32 bit versions of Windows, ie Windows 95 and later. If you want to build your own swig.exe have a look at Building swig.exe on Windows.
-Using Microsoft Visual C++ is the most common approach to compiling and linking SWIG's output. The Examples directory has a few Visual C++ - project files (.dsp files). These were produced by Visual C++ 6. Later - versions of Visual Studio should also be able to open and convert these - project files. The C# examples come with .NET 2003 solution (.sln) and - project files instead of Visual C++ 6 project files. The project files - have been set up to execute SWIG in a custom build rule for the SWIG - interface (.i) file. Alternatively run the + project files (.dsp files). These were produced by Visual C++ 6. Newer + versions of Visual Studio should be able to open and convert these + project files. Each C# example comes with a Visual Studio 2005 solution + and associated project files instead of Visual C++ 6 project files. The + project files have been set up to execute SWIG in a custom build rule + for the SWIG interface (.i) file. Alternatively run the examples using Cygwin.
More information on each of the examples is available with the examples distributed with SWIG (Examples/index.html).
-Ensure the SWIG executable is as supplied in the SWIG root directory in order for the examples to work. Most languages require some environment variables to be set before running Visual C++. Note @@ -2814,13 +3161,13 @@ examples using Cygwin.
coded values. If you are interested in how the project files are set up there is explanatory information in some of the language module's documentation. -The C# examples do not require any environment variables to be set as a C# project file is included. Just open up the .sln solution file in Visual Studio .NET 2003 or later, select Release Build, and do a Rebuild All from the Build menu. The accompanying C# and C++ project files are automatically used by the solution file.
- JAVA_INCLUDE : Set this to the directory containing
jni.h
JAVA_BIN : Set this to the bin directory containing
@@ -2829,7 +3176,7 @@ examples using Cygwin.
PERL5_INCLUDE : Set this to the directory containing
perl.h
PERL5_LIB : Set this to the Perl library including
@@ -2838,7 +3185,7 @@ examples using Cygwin.
PERL5_INCLUDE: D:\nsPerl5.004_04\lib\CORE
PERL5_LIB: D:\nsPerl5.004_04\lib\CORE\perl.lib
PYTHON_INCLUDE : Set this to the directory that
contains Python.h
PYTHON_LIB : Set this to the python library
@@ -2847,7 +3194,7 @@ examples using Cygwin.
TCL_INCLUDE : Set this to the directory containing
tcl.h
TCL_LIB : Set this to the TCL library including
@@ -2856,7 +3203,7 @@ examples using Cygwin.
R_INCLUDE : Set this to the directory containing R.h
R_LIB : Set this to the R library (Rdll.lib)
including path for linking. The library needs to be built as described
@@ -2866,7 +3213,7 @@ examples using Cygwin.
RUBY_INCLUDE : Set this to the directory containing
ruby.h
RUBY_LIB : Set this to the ruby library including
@@ -2875,27 +3222,27 @@ examples using Cygwin.
If you do not have access to Visual C++ you will have to set up project files / Makefiles for your chosen compiler. There is a section in each of the language modules detailing what needs setting up using Visual C++ which may be of some guidance. Alternatively you may want to use Cygwin as described in the following section.
-SWIG can also be compiled and run using Cygwin or MinGW which provides a Unix like front end to Windows and comes free with gcc, an ANSI C/C++ compiler. However, this is not a recommended approach as the prebuilt executable is supplied.
-If you want to replicate the build of swig.exe that comes with the download, follow the MinGW instructions below. This is not necessary to use the supplied swig.exe. This information is provided for those that want to modify the SWIG source code in a Windows environment. Normally this is not needed, so most people will want to ignore this section.
-The short abbreviated instructions follow...
cd / -tar -jxf msys-automake-1.8.2.tar.bz2 +tar -jxf msys-automake-1.8.2.tar.bz2 tar -jxf msys-autoconf-2.59.tar.bz2 -tar -zxf bison-2.0-MSYS.tar.gz +tar -zxf bison-2.0-MSYS.tar.gz
Note that SWIG can also be built using Cygwin. However, SWIG will then require the Cygwin DLL when executing. Follow the Unix instructions in the README file in the SWIG root directory. Note that @@ -2996,20 +3343,20 @@ make generated files which are supplied with the release distribution. These files are generated using the autogen.sh script and will only need regenerating in circumstances such as changing the build system.
-If you don't want to install Cygwin or MinGW, use a different compiler to build SWIG. For example, all the source code files can be added to a Visual C++ project file in order to build swig.exe from the Visual C++ IDE.
-The examples and test-suite work as successfully on Cygwin as on any other Unix operating system. The modules which are known to work are Python, Tcl, Perl, Ruby, Java and C#. Follow the Unix instructions in the README file in the SWIG root directory to build the examples.
-A common problem when using SWIG on Windows are the Microsoft function calling conventions which are not in the C++ standard. SWIG parses ISO C/C++ so cannot deal with proprietary conventions such as @@ -3025,8 +3372,52 @@ __declspec(dllimport), __stdcall etc. There is a Windows __declspec(dllexport) ULONG __stdcall foo(DWORD, __int32); +
Note that if you follow Microsoft's recommendation of wrapping the +__declspec calls in a preprocessor definition, you will need to + make sure that the definition is included by SWIG as well, by either + defining it manually or via a header. For example, if you have + specified the preprocessor definition in a header named +export_lib.h and include other headers which depend on it, you + should use the %include directive to include the definition + explicitly. For example, if you had a header file, bar.h, + which depended on export_lib.h, your SWIG definition file + might look like:
++// bar.i +%module bar +%include <windows.i> +%include "export_lib.h" +%include "bar.h" ++
where export_lib.h may contain:
++// export_lib.h +#define BAR_API __declspec(dllexport) ++
and bar.h may look like:
++// bar.h +#include "export_lib.h" +BAR_API void bar_function(int, double); ++
Using the preprocessor to remove BAR_API is a popular simpler + solution:
++// bar.i +%module bar +#define BAR_API +%include "bar.h" +
This chapter provides a brief overview of scripting language extension programming and the mechanisms by which scripting language interpreters access C and C++ code.
-When a scripting language is used to control a C program, the resulting system tends to look as follows:
Scripting languages are built around a parser that knows how to execute commands and scripts. Within this parser, there is a mechanism for executing commands and accessing variables. Normally, this is used @@ -3093,13 +3484,15 @@ src="ch2.1.png" WIDTH="377"> information about the wrapper by providing details about the name of the function, arguments, and so forth. The next few sections illustrate the process.
-Suppose you have an ordinary C function like this :
int fact(int n) { - if (n <= 1) return 1; - else return n*fact(n-1); + if (n <= 1) + return 1; + else + return n*fact(n-1); }
-int wrap_fact(ClientData clientData, Tcl_Interp *interp, - int argc, char *argv[]) { - int result; - int arg0; - if (argc != 2) { - interp->result = "wrong # args"; - return TCL_ERROR; - } - arg0 = atoi(argv[1]); - result = fact(arg0); - sprintf(interp->result,"%d", result); - return TCL_OK; +int wrap_fact(ClientData clientData, Tcl_Interp *interp, int argc, char *argv[]) { + int result; + int arg0; + if (argc != 2) { + interp->result = "wrong # args"; + return TCL_ERROR; + } + arg0 = atoi(argv[1]); + result = fact(arg0); + sprintf(interp->result,"%d", result); + return TCL_OK; }@@ -3141,9 +3533,9 @@ int wrap_fact(ClientData clientData, Tcl_Interp *interp,
int Wrap_Init(Tcl_Interp *interp) { - Tcl_CreateCommand(interp, "fact", wrap_fact, (ClientData) NULL, - (Tcl_CmdDeleteProc *) NULL); - return TCL_OK; + Tcl_CreateCommand(interp, "fact", wrap_fact, (ClientData) NULL, + (Tcl_CmdDeleteProc *) NULL); + return TCL_OK; }
Variable linking refers to the problem of mapping a C/C++ global variable to a variable in the scripting language interpreter. For example, suppose you had the following variable:
@@ -3179,7 +3571,7 @@ $Foo = $a + 2.0; # Assignment such as $Foo might implicitly call the get function. Similarly, typing $Foo = 4 would call the underlying set function to change the value. -In many cases, a C program or library may define a large collection of constants. For example:
Although scripting languages have no trouble accessing simple functions and variables, accessing C/C++ structures and classes present a different problem. This is because the implementation of structures @@ -3208,9 +3600,9 @@ $GREEN. Virtually all scripting languages provide C functions for
struct Vector { - Vector(); - ~Vector(); - double x,y,z; + Vector(); + ~Vector(); + double x,y,z; };@@ -3242,20 +3634,20 @@ void Vector_z_set(Vector *v, double z);
Since accessor functions provide a mechanism for accessing the internals of an object, the interpreter does not need to know anything about the actual representation of a Vector.
-In certain cases, it is possible to use the low-level accessor functions to create a proxy class, also known as a shadow class. A proxy class is a special kind of object that gets created in a scripting language to access a C/C++ class (or struct) in a way that looks like the original structure (that is, it proxies the real C++ - class). For example, if you have the following C definition :
+ class). For example, if you have the following C++ definition :class Vector { public: - Vector(); - ~Vector(); - double x,y,z; + Vector(); + ~Vector(); + double x,y,z; };
Vector v -v configure -x 3 -y 4 -z 13 +v configure -x 3 -y 4 -z -13
When proxy classes are used, two objects are at really work--one in +
When proxy classes are used, two objects are really at work--one in the scripting language, and an underlying C/C++ object. Operations affect both objects equally and for all practical purposes, it appears as if you are simply manipulating a C/C++ object.
-The final step in using a scripting language with your C/C++ application is adding your extensions to the scripting language itself. There are two primary approaches for doing this. The preferred - technique is to build a dynamically loadable extension in the form a + technique is to build a dynamically loadable extension in the form of a shared library. Alternatively, you can recompile the scripting language interpreter with your extensions added to it.
-To create a shared library or DLL, you often need to look at the manual pages for your compiler and linker. However, the procedure for a - few common machines is shown below:
+ few common platforms is shown below:# Build a shared library for Solaris -gcc -c example.c example_wrap.c -I/usr/local/include +gcc -fpic -c example.c example_wrap.c -I/usr/local/include ld -G example.o example_wrap.o -o example.so # Build a shared library for Linux gcc -fpic -c example.c example_wrap.c -I/usr/local/include gcc -shared example.o example_wrap.o -o example.so - -# Build a shared library for Irix -gcc -c example.c example_wrap.c -I/usr/local/include -ld -shared example.o example_wrap.o -o example.so -
To use your shared library, you simply use the corresponding command @@ -3344,7 +3731,7 @@ ld -shared example.o example_wrap.o -o example.so c++ -shared example.o example_wrap.o -o example.so
When building extensions as shared libraries, it is not uncommon for your extension to rely upon other shared libraries on your machine. In order for the extension to work, it needs to be able to find all of @@ -3382,7 +3769,7 @@ lib/libgraph.so:/lib/cmplrs/cc/libgraph.so:/usr/lib/cmplrs/cc/libgraph.so: Although this is an easy solution, it is not recommended. Consider setting the path using linker options instead. -
With static linking, you rebuild the scripting language interpreter with extensions. The process usually involves compiling a short main program that adds your customized commands to the language and starts @@ -3393,7 +3780,7 @@ lib/libgraph.so:/lib/cmplrs/cc/libgraph.so:/usr/lib/cmplrs/cc/libgraph.so: fact, there are very few practical reasons for doing this--consider using shared libraries instead.
To run SWIG, use the swig command with options and a filename like this:
where filename is a SWIG interface file or a C/C++ header file. Below is a subset of options that can be used. Additional options are also defined for each target language. A full - list can be obtained by typing swig -help or swig - -lang -help.
+ list can be obtained by typing swig -help or swig + -<lang> -help for language <lang> specific options.-allegrocl Generate ALLEGROCL wrappers @@ -3506,25 +3893,31 @@ lang -help. -clisp Generate CLISP wrappers -cffi Generate CFFI wrappers -csharp Generate C# wrappers +-d Generate D wrappers -go Generate Go wrappers -guile Generate Guile wrappers -java Generate Java wrappers +-javascript Generate Javascript wrappers -lua Generate Lua wrappers -modula3 Generate Modula 3 wrappers -mzscheme Generate Mzscheme wrappers -ocaml Generate Ocaml wrappers +-octave Generate Octave wrappers -perl Generate Perl wrappers -php Generate PHP wrappers -pike Generate Pike wrappers -python Generate Python wrappers -r Generate R (aka GNU S) wrappers -ruby Generate Ruby wrappers +-scilab Generate Scilab wrappers -sexp Generate Lisp S-Expressions wrappers -tcl Generate Tcl wrappers -uffi Generate Common Lisp / UFFI wrappers -xml Generate XML wrappers -c++ Enable C++ parsing +-cppext ext Change file extension of C++ generated files to ext + (default is cxx, except for PHP which uses cpp) -Dsymbol Define a preprocessor symbol -Fstandard Display error/warning messages in commonly used format -Fmicrosoft Display error/warning messages in Microsoft format @@ -3532,8 +3925,9 @@ lang -help. -Idir Add a directory to the file include path -lfile Include a SWIG library file. -module name Set the name of the SWIG module --o outfile Name of output file --outcurrentdir Set default output dir to current dir instead of input file's path +-o outfile Set name of C/C++ output file to <outfile> +-oh headfile Set name of C++ output header file for directors to <headfile> +-outcurrentdir Set default output dir to current dir instead of input file's path -outdir dir Set language specific files output directory -pcreversion Display PCRE version information -swiglib Show location of SWIG library @@ -3541,7 +3935,7 @@ lang -help.
As input, SWIG expects a file containing ANSI C/C++ declarations and special SWIG directives. More often than not, this is a special SWIG interface file which is usually denoted with a special .i or @@ -3577,32 +3971,32 @@ Modules Introduction section.
interpreted by SWIG. The %{...%} syntax and semantics in SWIG is analogous to that of the declarations section used in input files to parser generation tools such as yacc or bison. -The output of SWIG is a C/C++ file that contains all of the wrapper code needed to build an extension module. SWIG may generate some additional files depending on the target language. By default, an input file with the name file.i is transformed into a file file_wrap.c or file_wrap.cxx (depending on whether or not - the -c++ option has been used). The name of the output file - can be changed using the -o option. In certain cases, file - suffixes are used by the compiler to determine the source language (C, - C++, etc.). Therefore, you have to use the -o option to change - the suffix of the SWIG-generated wrapper file if you want something - different than the default. For example:
+ the -c++ option has been used). The name of the output C/C++ + file can be changed using the -o option. In certain cases, + file suffixes are used by the compiler to determine the source language + (C, C++, etc.). Therefore, you have to use the -o option to + change the suffix of the SWIG-generated wrapper file if you want + something different than the default. For example:$ swig -c++ -python -o example_wrap.cpp example.i
The C/C++ output file created by SWIG often contains everything that - is needed to construct a extension module for the target scripting + is needed to construct an extension module for the target scripting language. SWIG is not a stub compiler nor is it usually necessary to edit the output file (and if you look at the output, you probably won't want to). To build the final extension module, the SWIG output file is compiled and linked with the rest of your C/C++ program to create a shared library.
-Many target languages will also generate proxy class files in the - target language. The default output directory for these language +
For many target languages SWIG will also generate proxy class files + in the target language. The default output directory for these language specific files is the same directory as the generated C/C++ file. This can be modified using the -outdir option. For example:
C and C++ style comments may appear anywhere in interface files. In previous versions of SWIG, comments were used to generate documentation files. However, this feature is currently under repair and will reappear in a later SWIG release.
-Like C, SWIG preprocesses all input files through an enhanced version of the C preprocessor. All standard preprocessor features are supported including file inclusion, conditional compilation and macros. @@ -3647,7 +4041,7 @@ pyfiles/example.py includes a number of macro handling enhancements that make it more powerful than the normal C preprocessor. These extensions are described in the "Preprocessor" chapter.
-Most of SWIG's operation is controlled by special directives that are always preceded by a "%" to distinguish them from normal C declarations. These directives are used to give SWIG hints or to alter @@ -3667,7 +4061,7 @@ pyfiles/example.py
SWIG is a special preprocessing symbol defined by SWIG when it is parsing an input file.
-Although SWIG can parse most C/C++ declarations, it does not provide a complete C/C++ parser implementation. Most of these limitations pertain to very complicated type declarations and certain advanced C++ @@ -3740,7 +4134,7 @@ Nested classes section for more information.
primary complication in the implementation is that the SWIG parser does not utilize a separate typedef-name terminal symbol as described on p. 234 of K&R). -SWIG wraps simple C declarations by creating an interface that closely matches the way in which the declarations would be used in a C program. For example, consider the following interface file:
@@ -3794,9 +4188,9 @@ STATUS and VERSION. When SWIG creates an extension module,Whenever possible, SWIG creates an interface that closely matches the underlying C/C++ code. However, due to subtle differences between languages, run-time environments, and semantics, it is not always - possible to do so. The next few sections describes various aspects of + possible to do so. The next few sections describe various aspects of this mapping.
-In order to build an interface, SWIG has to convert C/C++ datatypes to equivalent types in the target language. Generally, scripting languages provide a more limited set of primitive types than C. @@ -3893,7 +4287,7 @@ Typemaps for details about this.
Unicode characters in the target language will use the same internal representation (e.g., UCS-2 vs. UCS-4). You may need to write some special conversion functions. -Whenever possible, SWIG maps C/C++ global variables into scripting language variables. For example,
Constants can be created using #define, enumerations, or a special %constant directive. The following interface file shows a few valid constant declarations :
@@ -3985,7 +4379,7 @@ EXTERN (what would the value be?). In general, SWIG will not create reasons even a constant with a simple cast will be ignored, such as-#define F_CONST (double) 5 // A floating pointer constant with cast +#define F_CONST (double) 5 // A floating point constant with cast
The use of constant expressions is allowed, but SWIG does not @@ -4000,12 +4394,11 @@ EXTERN (what would the value be?). In general, SWIG will not create values as assigned by the C compiler.
The %constant directive is used to more precisely create constants corresponding to different C datatypes. Although it is not - usually not needed for simple values, it is more useful when working - with pointers and other more complex datatypes. Typically, -%constant is only used when you want to add constants to the - scripting language interface that are not defined in the original - header file.
-A common confusion with C programming is the semantic meaning of the const qualifier in declarations--especially when it is mixed with pointers and other type modifiers. In fact, previous versions of @@ -4080,14 +4473,14 @@ const int spam = 42;
Before going any further, there is one bit of caution involving char * that must now be mentioned. When strings are passed from a scripting language to a C char *, the pointer usually points to string data stored inside the interpreter. It is almost always a really bad idea to modify this data. Furthermore, some languages may explicitly disallow it. For instance, in Python, strings are supposed - be immutable. If you violate this, you will probably receive a vast + to be immutable. If you violate this, you will probably receive a vast amount of wrath when you unleash your module on the world.
The primary source of problems are functions that might modify string data in place. A classic example would be a function like this:
@@ -4104,10 +4497,10 @@ char *strcat(char *s, const char *t)The bottom line: don't rely on char * for anything other than read-only input values. However, it must be noted that you could change the behavior of SWIG using typemaps.
-Most C programs manipulate arrays, structures, and other types of objects. This section discusses the handling of these datatypes.
-Pointers to primitive C datatypes such as
@@ -4156,7 +4549,7 @@ _f8ac_pp_char
By allowing pointers to be manipulated from a scripting language, extension modules effectively bypass compile-time type checking in the C/C++ compiler. To prevent errors, a type signature is encoded into all @@ -4170,7 +4563,7 @@ NULL pointers can be passed to any function that expects to receive pointers are also sometimes used as sentinel values or to denote a missing/empty value. Therefore, SWIG leaves NULL pointer checking up to the application.
-For everything else (structs, classes, arrays, etc...) SWIG applies a very simple rule :
# Copy a file def filecopy(source,target): - f1 = fopen(source,"r") - f2 = fopen(target,"w") - buffer = malloc(8192) - nbytes = fread(buffer,8192,1,f1) - while (nbytes > 0): - fwrite(buffer,8192,1,f2) - nbytes = fread(buffer,8192,1,f1) - free(buffer) - + f1 = fopen(source,"r") + f2 = fopen(target,"w") + buffer = malloc(8192) + nbytes = fread(buffer,8192,1,f1) + while (nbytes > 0): + fwrite(buffer,8192,1,f2) + nbytes = fread(buffer,8192,1,f1) + free(buffer)
In this case f1, f2, and buffer are all opaque objects containing C pointers. It doesn't matter what value they contain--our program works just fine without this knowledge.
-When SWIG encounters an undeclared datatype, it automatically assumes that it is a structure or class. For example, suppose the following function appeared in a SWIG input file:
@@ -4256,7 +4648,7 @@ TypeError: expected a _p_size_t. declare type names using typedef. -Like C, typedef can be used to define new type names in SWIG. For example:
The corresponding wrapper function will accept arguments of type unsigned int * or size_t *.
-So far, this chapter has presented almost everything you need to know to use SWIG for simple interfaces. However, some C programs use idioms that are somewhat more difficult to map to a scripting language interface. This section describes some of these issues.
-Sometimes a C function takes structure parameters that are passed by value. For example, consider the following function:
In the target language, the dot_product() function now accepts pointers to Vectors instead of Vectors. For the most part, this transformation is transparent so you might not notice.
-C functions that return structures or classes datatypes by value are more difficult to handle. Consider the following function:
When global variables or class members involving structures are encountered, SWIG handles them as pointers. For example, a global variable like this
@@ -4400,10 +4792,10 @@ Vector unit_i;Vector *unit_i_get() { - return &unit_i; + return &unit_i; } void unit_i_set(Vector *value) { - unit_i = *value; + unit_i = *value; }
When a global variable of type char * appears, SWIG uses malloc() or new to allocate memory for the new value. Specifically, if you have a variable like this
@@ -4505,7 +4897,7 @@ const char *foo = "Hello World\n"; pointer to point to the new value. However, repeated modifications of the value will result in a memory leak since the old value is not released. -Arrays are fully supported by SWIG, but they are always handled as pointers instead of mapping them to a special array object or list in the target language. Thus, the following declarations :
@@ -4525,7 +4917,7 @@ void transpose(double (*a)[20]);Like C, SWIG does not perform array bounds checking. It is up to the - user to make sure the pointer points a suitably allocated region of + user to make sure the pointer points to a suitably allocated region of memory.
Multi-dimensional arrays are transformed into a pointer to an array of one less dimension. For example:
@@ -4606,19 +4998,19 @@ void pathname_set(char *value) {In the target language, the value can be set like a normal variable.
-A read-only variable can be created by using the %immutable directive as shown :
// File : interface.i -int a; // Can read/write +int a; // Can read/write %immutable; -int b,c,d // Read only variables +int b,c,d; // Read only variables %mutable; -double x,y // read/write +double x,y; // read/write
The %immutable directive enables read-only mode until it is @@ -4669,10 +5061,10 @@ char * const version="1.0"; /* Read only variable */ Although these directives still work, they generate a warning message. Simply change the directives to %immutable; and %mutable; to silence the warning. Don't forget the extra semicolon!
-Normally, the name of a C declaration is used when that declaration is wrapped into the target language. However, this may generate a conflict with a keyword or already existing function in the scripting @@ -4752,8 +5144,8 @@ void print(const char *);
This directive is still supported, but it is deprecated and should probably be avoided. The %rename directive is more powerful and better supports wrapping of raw header file information.
-While writing %rename for specific declarations is simple enough, sometimes the same renaming rule needs to be applied to many, maybe all, identifiers in the SWIG input. For example, it may be @@ -4832,6 +5224,11 @@ print_it
are exactly equivalent and %rename can be used to selectively ignore multiple declarations using the previously described matching possibilities.
-As explained in the previous sections, it is possible to either rename individual declarations or apply a rename rule to all of them at once. In practice, the latter is however rarely appropriate as there @@ -4969,8 +5376,8 @@ match="class" restricts the match to class declarations only (in methods or C++ methods which use default arguments. This is described in the Ambiguity resolution and renaming section in the C++ chapter.
-Using the techniques described above it is possible to ignore everything in a header and then selectively wrap a few chosen methods or classes. For example, consider a header, myheader.h which @@ -5004,7 +5411,7 @@ match="class" restricts the match to class declarations only (in %include "myheader.h" -
SWIG supports default arguments in both C and C++ code. For example:
@@ -5016,8 +5423,8 @@ int plot(double x, double y, int color=WHITE); function could be used in Tcl as follows :@@ -5032,7 +5439,7 @@ int plot(double x, double y, int color=WHITE); generated for each defaulted argument. Please refer to the section on default arguments in the C++ chapter for further details. --% plot -3.4 7.5 # Use default value -% plot -3.4 7.5 10 # set color to 10 instead +% plot -3.4 7.5 # Use default value +% plot -3.4 7.5 10 # set color to 10 instead5.4.9 Pointers to functions and callbacks
+5.4.9 Pointers to functions and callbacks
Occasionally, a C library may include functions that expect to receive pointers to functions--possibly to serve as callbacks. SWIG provides full support for function pointers provided that the callback @@ -5131,8 +5538,8 @@ int mul(int,int);
Notice that when the function is used as a callback, special names - such as add_cb is used instead. To call the function normally, - just use the original function name such as add().
+ such as add_cb are used instead. To call the function + normally, just use the original function name such as add().SWIG provides a number of extensions to standard C printf formatting that may be useful in this context. For instance, the following variation installs the callbacks as all upper case constants such as @@ -5156,20 +5563,20 @@ int mul(int,int); advanced SWIG features. See the Typemaps chapter for more about typemaps and individual target language chapters for more on callbacks and the 'director' feature.
-This section describes the behavior of SWIG when processing ANSI C structures and union declarations. Extensions to handle C++ are described in the next section.
If SWIG encounters the definition of a structure or union, it creates a set of accessor functions. Although SWIG does not need - structure definitions to build an interface, providing definitions make - it possible to access structure members. The accessor functions + structure definitions to build an interface, providing definitions + makes it possible to access structure members. The accessor functions generated by SWIG simply take a pointer to an object and allow access to an individual member. For example, the declaration :
struct Vector { - double x,y,z; + double x,y,z; }@@ -5178,22 +5585,22 @@ struct Vector {
double Vector_x_get(struct Vector *obj) { - return obj->x; + return obj->x; } double Vector_y_get(struct Vector *obj) { - return obj->y; + return obj->y; } double Vector_z_get(struct Vector *obj) { - return obj->z; + return obj->z; } void Vector_x_set(struct Vector *obj, double value) { - obj->x = value; + obj->x = value; } void Vector_y_set(struct Vector *obj, double value) { - obj->y = value; + obj->y = value; } void Vector_z_set(struct Vector *obj, double value) { - obj->z = value; + obj->z = value; }
However, most of SWIG's language modules also provide a high-level interface that is more convenient. Keep reading.
-SWIG supports the following construct which is quite common in C programs :
typedef struct { - double x,y,z; + double x,y,z; } Vector;@@ -5241,7 +5648,7 @@ struct keyword on its generated code. For example:
double Vector_x_get(Vector *obj) { - return obj->x; + return obj->x; }
typedef struct vector_struct { - double x,y,z; + double x,y,z; } Vector;@@ -5259,19 +5666,19 @@ typedef struct vector_struct { later in the interface use the type struct vector_struct, SWIG knows that this is the same as Vector and it generates the appropriate type-checking code. -
Structures involving character strings require some care. SWIG assumes that all members of type char * have been dynamically allocated using malloc() and that they are NULL-terminated - ASCII strings. When such a member is modified, the previously contents + ASCII strings. When such a member is modified, the previous contents will be released, and the new contents allocated. For example :
%module mymodule ... struct Foo { - char *name; - ... + char *name; + ... }@@ -5280,14 +5687,15 @@ struct Foo {
char *Foo_name_get(Foo *obj) { - return Foo->name; + return Foo->name; } char *Foo_name_set(Foo *obj, char *c) { - if (obj->name) free(obj->name); - obj->name = (char *) malloc(strlen(c)+1); - strcpy(obj->name,c); - return obj->name; + if (obj->name) + free(obj->name); + obj->name = (char *) malloc(strlen(c)+1); + strcpy(obj->name,c); + return obj->name; }
Note: If the -c++ option is used, new and delete are used to perform memory allocation.
-Arrays may appear as the members of structures, but they will be read-only. SWIG will write an accessor function that returns the pointer to the first element of the array, but will not write a @@ -5311,8 +5719,8 @@ interface.i:116. Warning. Array member will be read-only
To eliminate the warning message, typemaps can be used, but this is discussed in a later chapter. In many cases, the warning message is harmless.
-Occasionally, a structure will contain data members that are themselves structures. For example:
When a structure member is wrapped, it is handled as a pointer, unless the %naturalvar directive is used where it is handled more like a C++ reference (see C++ - Member data). The accessors to the member variable as a pointer is + Member data). The accessors to the member variable as a pointer are effectively wrapped as follows:
@@ -5393,7 +5801,7 @@ void Foo_w_set(FOO *f, WORD value) { existing code. However, if you need to tell SWIG that an undeclared datatype is really a struct, simply use a forward struct declaration such as "struct Foo;". -5.5.5 C constructors and destructors
+5.5.5 C constructors and destructors
When wrapping structures, it is generally useful to have a mechanism for creating and destroying objects. If you don't do anything, SWIG will automatically generate functions for creating and destroying @@ -5432,9 +5840,9 @@ struct Bar { // Default constructor generated. };
Since ignoring the implicit or default destructors most of the times - produce memory leaks, SWIG will always try to generate them. If needed, - however, you can selectively disable the generation of the +
Since ignoring the implicit or default destructors most of the time + produces memory leaks, SWIG will always try to generate them. If + needed, however, you can selectively disable the generation of the default/implicit destructor by using %nodefaultdtor
@@ -5455,9 +5863,9 @@ struct Bar { // Default destructor generated.@@ -5490,23 +5898,23 @@ typedef struct Vector { %include "vector.h" // Just grab original C header file %extend Vector { // Attach these functions to struct Vector - Vector(double x, double y, double z) { - Vector *v; - v = (Vector *) malloc(sizeof(Vector)); - v->x = x; - v->y = y; - v->z = z; - return v; - } - ~Vector() { - free($self); - } - double magnitude() { - return sqrt($self->x*$self->x+$self->y*$self->y+$self->z*$self->z); - } - void print() { - printf("Vector [%g, %g, %g]\n", $self->x,$self->y,$self->z); - } + Vector(double x, double y, double z) { + Vector *v; + v = (Vector *) malloc(sizeof(Vector)); + v->x = x; + v->y = y; + v->z = z; + return v; + } + ~Vector() { + free($self); + } + double magnitude() { + return sqrt($self->x*$self->x+$self->y*$self->y+$self->z*$self->z); + } + void print() { + printf("Vector [%g, %g, %g]\n", $self->x,$self->y,$self->z); + } }; @@ -5543,12 +5951,12 @@ typedef struct Vector { %} typedef struct Vector { - double x,y,z; - %extend { - Vector(double x, double y, double z) { ... } - ~Vector() { ... } - ... - } + double x,y,z; + %extend { + Vector(double x, double y, double z) { ... } + ~Vector() { ... } + ... + } } Vector;Note: There are also the -nodefault option and %nodefault directive, which disable both the default or implicit destructor generation. This could lead to memory leaks across the - target languages, and is highly recommended you don't use them.
-5.5.6 Adding member - functions to C structures
+ target languages, and it is highly recommended you don't use them. +5.5.6 Adding member functions + to C structures
Most languages provide a mechanism for creating classes and supporting object oriented programming. From a C standpoint, object oriented programming really just boils down to the process of attaching @@ -5473,7 +5881,7 @@ struct Bar { // Default destructor generated. /* file : vector.h */ ... typedef struct Vector { - double x,y,z; + double x,y,z; } Vector;
typedef struct Integer { - int value; + int value; } Int; %extend Integer { ... } /* Correct name */ %extend Int { ... } /* Incorrect name */ struct Float { - float value; + float value; }; typedef struct Float FloatValue; %extend Float { ... } /* Correct name */ @@ -5617,7 +6025,7 @@ typedef struct Float FloatValue;typedef struct { - double value; + double value; } Double; %extend Double { ... } /* Okay */@@ -5699,18 +6107,18 @@ void Person_name_set(Person *p, char *val) { name for the %addmethods directive. Since %addmethods could be used to extend a structure with more than just methods, a more suitable directive name has been chosen. -5.5.7 Nested structures
+5.5.7 Nested structures
Occasionally, a C program will involve structures like this :
typedef struct Object { - int objtype; - union { - int ivalue; - double dvalue; - char *strvalue; - void *ptrvalue; - } intRep; + int objtype; + union { + int ivalue; + double dvalue; + char *strvalue; + void *ptrvalue; + } intRep; } Object;@@ -5721,15 +6129,15 @@ typedef struct Object {typedef union { - int ivalue; - double dvalue; - char *strvalue; - void *ptrvalue; + int ivalue; + double dvalue; + char *strvalue; + void *ptrvalue; } Object_intRep; typedef struct Object { - int objType; - Object_intRep intRep; + int objType; + Object_intRep intRep; } Object;@@ -5740,16 +6148,16 @@ typedef struct Object {-Object_intRep *Object_intRep_get(Object *o) { - return (Object_intRep *) &o->intRep; + return (Object_intRep *) &o->intRep; } int Object_intRep_ivalue_get(Object_intRep *o) { - return o->ivalue; + return o->ivalue; } int Object_intRep_ivalue_set(Object_intRep *o, int value) { - return (o->ivalue = value); + return (o->ivalue = value); } double Object_intRep_dvalue_get(Object_intRep *o) { - return o->dvalue; + return o->dvalue; } ... etc ... @@ -5771,8 +6179,8 @@ $o->{intRep}->{ivalue} = 7 # Change value of o.intRep.ivalue in certain cases.Finally, note that nesting is handled differently in C++ mode, see Nested classes.
-5.5.8 Other things to note about structure - wrapping
+5.5.8 Other things to note about structure + wrapping
SWIG doesn't care if the declaration of a structure in a .i file exactly matches that used in the underlying C code (except in the case of nested structures). For this reason, there are no problems @@ -5816,13 +6224,13 @@ _wrap_Vector_x_get(ClientData clientData, Tcl_Interp *interp, choose to build a more advanced interface. Although you may never use the low-level interface described here, most of SWIG's language modules use it in some way or another.
-5.6 Code Insertion
+5.6 Code Insertion
Sometimes it is necessary to insert special code into the resulting wrapper file generated by SWIG. For example, you may want to include additional C code to perform initialization or other operations. There are four common ways to insert code, but it's useful to know how the output of SWIG is structured first.
-5.6.1 The output of SWIG
+5.6.1 The output of SWIG
When SWIG creates its output file, it is broken up into five sections corresponding to runtime code, headers, wrapper functions, and module initialization code (in that order).
@@ -5844,7 +6252,7 @@ _wrap_Vector_x_get(ClientData clientData, Tcl_Interp *interp,
The function generated by SWIG to initialize the module upon loading. -5.6.2 Code insertion blocks
+5.6.2 Code insertion blocks
Code is inserted into the appropriate code section by using one of the code insertion directives listed below. The order of the sections in the wrapper file is as shown:
@@ -5904,7 +6312,7 @@ void some_extra_function() { %{ /* Create a new vector */ static Vector *new_Vector() { - return (Vector *) malloc(sizeof(Vector)); + return (Vector *) malloc(sizeof(Vector)); } %} @@ -5912,7 +6320,7 @@ static Vector *new_Vector() { Vector *new_Vector();5.6.3 Inlined code blocks
+5.6.3 Inlined code blocks
Since the process of writing helper functions is fairly common, there is a special inlined form of code block that is used as follows :
@@ -5920,7 +6328,7 @@ Vector *new_Vector(); %inline %{ /* Create a new vector */ Vector *new_Vector() { - return (Vector *) malloc(sizeof(Vector)); + return (Vector *) malloc(sizeof(Vector)); } %} @@ -5933,7 +6341,7 @@ Vector *new_Vector() { declaration. Since the code inside an %inline %{ ... %} block is given to both the C compiler and SWIG, it is illegal to include any SWIG directives inside a %{ ... %} block. -5.6.4 Initialization blocks
+5.6.4 Initialization blocks
When code is included in the %init section, it is copied directly into the module initialization function. For example, if you needed to perform some extra initialization on module loading, you @@ -5941,24 +6349,24 @@ Vector *new_Vector() {
-%init %{ - init_variables(); + init_variables(); %}5.7 An Interface Building Strategy
-This section describes the general approach for building interface +
5.7 An Interface Building Strategy
+This section describes the general approach for building interfaces with SWIG. The specifics related to a particular scripting language are found in later chapters.
-5.7.1 Preparing a C program for SWIG
+5.7.1 Preparing a C program for SWIG
SWIG doesn't require modifications to your C code, but if you feed it a collection of raw C header files or source code, the results might not be what you expect---in fact, they might be awful. Here's a series of steps you can follow to make an interface for a C program :
-
- Identify the functions that you want to wrap. It's probably not - necessary to access every single function in a C program--thus, a + necessary to access every single function of a C program--thus, a little forethought can dramatically simplify the resulting scripting - language interface. C header files are particularly good source for + language interface. C header files are a particularly good source for finding things to wrap.
- Create a new interface file to describe the scripting language interface to your program.
@@ -5974,7 +6382,7 @@ Vector *new_Vector() { available if it is needed, whereas SWIG will usually not warn or error out as it is designed to work without full type information. However, if type information is not specified correctly, the wrappers can be - sub-optimal and even result in uncompileable C/C++ code. + sub-optimal and even result in uncompilable C/C++ code.- If your program has a main() function, you may need to rename it (read on).
- Run SWIG and compile.
@@ -5988,9 +6396,9 @@ Vector *new_Vector() { parser--you should report parsing errors to the swig-devel mailing list or to the SWIG bug tracker. -5.7.2 The SWIG interface file
-The preferred method of using SWIG is to generate separate interface - file. Suppose you have the following C header file :
+5.7.2 The SWIG interface file
+The preferred method of using SWIG is to generate a separate + interface file. Suppose you have the following C header file :
-/* File : header.h */ @@ -6036,7 +6444,7 @@ extern void dump(FILE *f); complex projects, an interface file containing numerous %include and #include statements like this is one of the most common approaches to interface file design due to lower maintenance overhead. -5.7.3 Why use separate interface files?
+5.7.3 Why use separate interface files?
Although SWIG can parse many header files, it is more common to write a special .i file defining the interface to a package. There are several reasons why you might want to do this:
@@ -6055,7 +6463,7 @@ extern void dump(FILE *f); interface file and immediately see what is available without having to dig it out of header files. -5.7.4 Getting the right header files
+5.7.4 Getting the right header files
Sometimes, it is necessary to use certain header files in order for the code generated by SWIG to compile properly. Make sure you include certain header files by using a %{,%} block like this:
@@ -6067,11 +6475,11 @@ extern void dump(FILE *f); #include <GL/glu.h> %} -// Put rest of declarations here +// Put the rest of the declarations here ...5.7.5 What to do with main()
+5.7.5 What to do with main()
If your program defines a main() function, you may need to get rid of it or rename it in order to use a scripting language. Most scripting languages define their own main() procedure that is @@ -6096,7 +6504,7 @@ extern void dump(FILE *f); by using a scripting language, you are probably trying to create a program that is more interactive. In many cases, the old main() program can be completely replaced by a Perl, Python, or Tcl script.
-Note: If some cases, you might be inclined to create a +
Note: In some cases, you might be inclined to create a scripting language wrapper for main(). If you do this, the compilation will probably work and your module might even load correctly. The only trouble is that when you call your main() @@ -6105,7 +6513,7 @@ extern void dump(FILE *f); effect of the symbol binding mechanism used in the dynamic linker. The bottom line: don't do this.
-6 SWIG and C++
+6 SWIG and C++
@@ -6182,7 +6590,7 @@ extern void dump(FILE *f); Basics to see how SWIG wraps ANSI C. Support for C++ builds upon ANSI C wrapping and that material will be useful in understanding this chapter. --6.1 Comments on C++ Wrapping
+6.1 Comments on C++ Wrapping
Because of its complexity and the fact that C++ can be difficult to integrate with itself let alone other languages, SWIG only provides support for a subset of C++ features. Fortunately, this is now a rather @@ -6213,7 +6621,7 @@ extern void dump(FILE *f); complicates the problem of crossing language boundaries and provides many opportunities to shoot yourself in the foot. You will just have to be careful.
-6.2 Approach
+6.2 Approach
To wrap C++, SWIG uses a layered approach to code generation. At the lowest level, SWIG generates a collection of procedural ANSI-C style wrappers. These wrappers take care of basic type conversion, type @@ -6245,7 +6653,7 @@ extern void dump(FILE *f); mind that the target languages also provide the high-level OO interface via proxy classes. More detailed coverage can be found in the documentation for each target language.
-6.3 Supported C++ features
+6.3 Supported C++ features
SWIG currently supports most C++ features including the following:
- Classes
@@ -6265,8 +6673,6 @@ extern void dump(FILE *f);The following C++ features are not currently supported:
- Overloaded versions of certain operators (new, delete, etc.)
-- Nested classes, see Nested - classes for workarounds.
As a rule of thumb, SWIG should not be used on raw C++ source files, use header files only.
@@ -6274,7 +6680,7 @@ extern void dump(FILE *f); limitations may be lifted in future releases. However, we make no promises. Also, submitting a bug report is a very good way to get problems fixed (wink). -6.4 Command line options and compilation
+6.4 Command line options and compilation
When wrapping C++ code, it is critical that SWIG be called with the `-c++' option. This changes the way a number of critical features such as memory management are handled. It also enables the @@ -6286,7 +6692,7 @@ extern void dump(FILE *f);
@@ -6297,7 +6703,7 @@ $ c++ example_wrap.o $(OBJS) -o example.so flattened low-level C style API to C++ classes by default. The -noproxy commandline option is recognised by many target languages and will generate just this interface as in earlier versions. -$ swig -c++ -tcl example.i -$ c++ -c example_wrap.cxx +$ c++ -fPIC -c example_wrap.cxx $ c++ example_wrap.o $(OBJS) -o example.so6.5 Proxy classes
+6.5 Proxy classes
In order to provide a natural mapping from C++ classes to the target language classes, SWIG's target languages mostly wrap C++ classes with special proxy classes. These proxy classes are typically implemented in @@ -6305,7 +6711,7 @@ $ c++ example_wrap.o $(OBJS) -o example.so module, each C++ class is wrapped by a Python proxy class. Or if you're building a Java module, each C++ class is wrapped by a Java proxy class.
-6.5.1 Construction of proxy classes
+6.5.1 Construction of proxy classes
Proxy classes are always constructed as an extra layer of wrapping that uses low-level accessor functions. To illustrate, suppose you had a C++ class like this:
@@ -6372,7 +6778,7 @@ class Foo: proxies try to take advantage of language features that are similar to C++. This might include operator overloading, exception handling, and other features. -6.5.2 Resource management in proxies
+6.5.2 Resource management in proxies
A major issue with proxies concerns the memory management of wrapped objects. Consider the following C++ code:
@@ -6494,11 +6900,11 @@ class SpamProxy { management problem. However, proxies do provide a mechanism for manual control that can be used (if necessary) to address some of the more tricky memory management problems. --6.5.3 Language specific details
+6.5.3 Language specific details
Language specific details on proxy classes are contained in the chapters describing each target language. This chapter has merely introduced the topic in a very general way.
-6.6 Simple C++ wrapping
+6.6 Simple C++ wrapping
The following code shows a SWIG interface file for a simple C++ class.
@@ -6526,22 +6932,22 @@ static void print(List *l);To generate wrappers for this class, SWIG first reduces the class to a collection of low-level C-style accessor functions which are then used by the proxy classes.
-6.6.1 Constructors and destructors
+6.6.1 Constructors and destructors
C++ constructors and destructors are translated into accessor functions such as the following :
-List * new_List(void) { - return new List; + return new List; } void delete_List(List *l) { - delete l; + delete l; }6.6.2 Default constructors, copy - constructors and implicit destructors
+6.6.2 Default constructors, copy constructors + and implicit destructors
Following the C++ rules for implicit constructor and destructors, SWIG will automatically assume there is one even when they are not explicitly declared in the class interface.
@@ -6640,8 +7046,8 @@ class Foo { // No destructor is generated, unless one is declared options described above, which disable both the default constructor and the implicit destructors, could lead to memory leaks, and so it is strongly recommended to not use them. -6.6.3 When constructor wrappers aren't - created
+6.6.3 When constructor wrappers aren't + created
If a class defines a constructor, SWIG normally tries to generate a wrapper for it. However, SWIG will not generate a constructor wrapper if it thinks that it will result in illegal wrapper code. There are @@ -6699,7 +7105,7 @@ public:
More information about %feature can be found in the Customization features chapter.
-6.6.4 Copy constructors
+6.6.4 Copy constructors
If a class defines more than one constructor, its behavior depends on the capabilities of the target language. If overloading is supported, the copy constructor is accessible using the normal @@ -6770,13 +7176,13 @@ public: copy-constructor handling if the constructor has been manually renamed. For instance, in the above example, the name of the constructor is set to new_CopyFoo(). This is the same as in older versions.
-6.6.5 Member functions
+6.6.5 Member functions
All member functions are roughly translated into accessor functions like this :
-int List_search(List *obj, char *value) { - return obj->search(value); + return obj->search(value); }@@ -6789,23 +7195,23 @@ int List_search(List *obj, char *value) { wrapper functions. However, the name and calling convention of the low-level procedural wrappers match the accessor function prototype described above. -6.6.6 Static members
+6.6.6 Static members
Static member functions are called directly without making any special transformations. For example, the static member function print(List *l) directly invokes List::print(List *l) in the generated wrapper code.
-6.6.7 Member data
+6.6.7 Member data
Member data is handled in exactly the same manner as for C structures. A pair of accessor functions are effectively created. For example :
int List_length_get(List *obj) { - return obj->length; + return obj->length; } int List_length_set(List *obj, int value) { - obj->length = value; - return value; + obj->length = value; + return value; }@@ -6821,7 +7227,7 @@ class List { public: ... %immutable; - int length; + int length; %mutable; ... }; @@ -6842,8 +7248,10 @@ class List {Similarly, all data attributes declared as const are wrapped as read-only members.
-There are some subtle issues when wrapping data members that are - themselves classes. For instance, if you had another class like this,
+By default, SWIG uses the const reference typemaps for members that + are primitive types. There are some subtle issues when wrapping data + members that are not primitive types, such as classes. For instance, if + you had another class like this,
class Foo { @@ -6873,8 +7281,22 @@ void Foo_items_set(Foo *self, List *value) { variables to be wrapped as a string in the target language, rather than a pointer to this class. The const reference typemaps offer this type of marshalling, so there is a feature to tell SWIG to use the const - reference typemaps rather than the pointer typemaps. It is the -%naturalvar directive and is used as follows: + reference typemaps rather than the pointer typemaps. It is the + naturalvar feature and can be used to effectively change the way + accessors are generated to the following: ++++const List &Foo_items_get(Foo *self) { + return self->items; +} +void Foo_items_set(Foo *self, const List &value) { + self->items = value; +} ++The %naturalvar directive is a macro for, and hence + equivalent to, %feature("naturalvar"). It can be used as + follows:
// All List variables will use const List& typemaps @@ -6886,37 +7308,31 @@ struct Foo { List myList; }; -// All variables will use const reference typemaps +// All non-primitive types will use const reference typemaps %naturalvar;The observant reader will notice that %naturalvar works like any other feature flag - directive, except it can also be attached to class types. The first of - the example usages above show %naturalvar attaching to the -List class. Effectively this feature changes the way accessors are - generated to the following:
----const List &Foo_items_get(Foo *self) { - return self->items; -} -void Foo_items_set(Foo *self, const List &value) { - self->items = value; -} --In fact it is generally a good idea to use this feature globally as - the reference typemaps have extra NULL checking compared to the pointer + directive but with some extra flexibility. The first of the example + usages above shows %naturalvar attaching to the myList +'s variable type, that is the List class. The second usage + shows %naturalvar attaching to the variable name. Hence the + naturalvar feature can be used on either the variable's name or type. + Note that using the naturalvar feature on a variable's name overrides + any naturalvar feature attached to the variable's type.
+It is generally a good idea to use this feature globally as the + reference typemaps have extra NULL checking compared to the pointer typemaps. A pointer can be NULL, whereas a reference cannot, so the extra checking ensures that the target language user does not pass in a value that translates to a NULL pointer and thereby preventing any potential NULL pointer dereferences. The %naturalvar feature will apply to global variables in addition to member variables in some language modules, eg C# and Java.
-Other alternatives for turning this feature on globally are to use - the swig -naturalvar commandline option or the module mode - option, %module(naturalvar=1)
+The naturalvar behavior can also be turned on as a global setting + via the -naturalvar commandline option or the module mode + option, %module(naturalvar=1). However, any use of +%feature("naturalvar") will override the global setting.
Compatibility note: The %naturalvar feature was introduced in SWIG-1.3.28, prior to which it was necessary to manually apply the const reference typemaps, eg %apply const std::string & { @@ -6945,7 +7361,7 @@ struct Foo { involving size_t. This change is subtle, but it smooths over a few problems related to structure wrapping and some of SWIG's customization features.
-6.7 Default arguments
+6.7 Default arguments
SWIG will wrap all types of functions that have default arguments. For example member functions:
@@ -7020,17 +7436,20 @@ public: };-This produces uncompileable wrapper code because default values in +
This produces uncompilable wrapper code because default values in C++ are evaluated in the same scope as the member function whereas SWIG evaluates them in the scope of a wrapper function (meaning that the values have to be public).
-This feature is automatically turned on when wrapping -C code with default arguments and whenever keyword arguments - (kwargs) are specified for either C or C++ code. Keyword arguments are - a language feature of some scripting languages, for example Ruby and - Python. SWIG is unable to support kwargs when wrapping overloaded - methods, so the default approach cannot be used.
-6.8 Protection
+The compactdefaultargs feature is automatically turned on + when wrapping C code with default + arguments. Some target languages will also automatically turn on + this feature if the keyword arguments feature (kwargs) is specified for + either C or C++ functions, and the target language supports kwargs, the + compactdefaultargs feature is also automatically turned on. + Keyword arguments are a language feature of some scripting languages, + for example Ruby and Python. SWIG is unable to support kwargs when + wrapping overloaded methods, so the default approach cannot be used.
+6.8 Protection
SWIG wraps class members that are public following the C++ conventions, i.e., by explicit public declaration or by the use of the using directive. In general, anything specified in a private or @@ -7042,7 +7461,7 @@ using directive. In general, anything specified in a private or
By default, members of a class definition are assumed to be private until you explicitly give a `public:' declaration (This is the same convention used by C++).
-6.9 Enums and constants
+6.9 Enums and constants
Enumerations and constants are handled differently by the different language modules and are described in detail in the appropriate language chapter. However, many languages map enums and constants in a @@ -7052,7 +7471,7 @@ using directive. In general, anything specified in a private or
class Swig { public: - enum {ALE, LAGER, PORTER, STOUT}; + enum {ALE, LAGER, PORTER, STOUT}; };@@ -7070,7 +7489,7 @@ Swig_STOUT = Swig::STOUTMembers declared as const are wrapped as read-only members and do not create constants.
-6.10 Friends
+6.10 Friends
Friend declarations are recognised by SWIG. For example, if you have this code:
@@ -7114,14 +7533,14 @@ namespace bar {and a wrapper for the method 'blah' will not be generated.
-6.11 References and pointers
+6.11 References and pointers
C++ references are supported, but SWIG transforms them back into pointers. For example, a declaration like this :
@@ -7129,7 +7548,7 @@ public:class Foo { public: - double bar(double &a); + double bar(double &a); }@@ -7185,7 +7604,7 @@ const int &bar(); datatypes is necessary to provide more seamless integration with more advanced C++ wrapping applications---especially related to templates and the STL. This was first added in SWIG-1.3.12. -double Foo_bar(Foo *obj, double *a) { - obj->bar(*a); + obj->bar(*a); }6.12 Pass and return by value
+6.12 Pass and return by value
Occasionally, a C++ program will pass and return class objects by value. For example, a function like this might appear:
@@ -7260,7 +7679,7 @@ struct B {Note: The use of this template only occurs when objects are passed or returned by value. It is not used for C++ pointers or references.
-6.13 Inheritance
+6.13 Inheritance
SWIG supports C++ inheritance of classes and allows both single and multiple inheritance, as limited or allowed by the target language. The SWIG type-checker knows about the relationship between base and derived @@ -7271,7 +7690,7 @@ struct B { spirit, and target language capabilities, as possible. In most cases, this means that SWIG will parse the non-public inheritance declarations, but that will have no effect in the generated code, - besides the implicit policies derived for constructor and destructors.
+ besides the implicit policies derived for constructors and destructors.The following example shows how SWIG handles inheritance. For clarity, the full C++ code has been omitted.
@@ -7284,24 +7703,24 @@ struct B { class Shape { public: - double x,y; - virtual double area() = 0; - virtual double perimeter() = 0; - void set_location(double x, double y); + double x,y; + virtual double area() = 0; + virtual double perimeter() = 0; + void set_location(double x, double y); }; class Circle : public Shape { public: - Circle(double radius); - ~Circle(); - double area(); - double perimeter(); + Circle(double radius); + ~Circle(); + double area(); + double perimeter(); }; class Square : public Shape { public: - Square(double size); - ~Square(); - double area(); - double perimeter(); + Square(double size); + ~Square(); + double area(); + double perimeter(); }@@ -7406,8 +7825,8 @@ Square_set_location(). This behavior resulted in huge amounts of using the -fvirtual option, which avoids the regenerating of wrapper functions for virtual members that are already defined in a base class. -6.14 A brief discussion of multiple - inheritance, pointers, and type checking
+6.14 A brief discussion of multiple + inheritance, pointers, and type checking
When a target scripting language refers to a C++ object, it normally uses a tagged pointer object that contains both the value of the pointer and a type string. For example, in Tcl, a C++ pointer might be @@ -7507,8 +7926,8 @@ int y = B_function((B *) pB);
In practice, the pointer is held as an integral number in the target language proxy class.
-6.15 Wrapping Overloaded - Functions and Methods
+6.15 Wrapping Overloaded + Functions and Methods
In many language modules, SWIG provides partial support for overloaded functions, methods, and constructors. For example, if you supply SWIG with overloaded functions like this:
@@ -7554,7 +7973,7 @@ public: >>> f.bar("hello",2)6.15.1 Dispatch function generation
+6.15.1 Dispatch function generation
The implementation of overloaded functions and methods is somewhat complicated due to the dynamic nature of scripting languages. Unlike C++, which binds overloaded methods at compile time, SWIG must @@ -7651,7 +8070,7 @@ rank appear in this ranking.
If you're still confused, don't worry about it---SWIG is probably doing the right thing.
-6.15.2 Ambiguity in Overloading
+6.15.2 Ambiguity in Overloading
Regrettably, SWIG is not able to support every possible use of valid C++ overloading. Consider the following example:
@@ -7706,18 +8125,19 @@ at example.i:3 used. they appear in the interface file. Therefore, earlier methods will shadow methods that appear later.When wrapping an overloaded function, there is a chance that you - will get an error message like this:
+ will get a warning message like this:-example.i:3: Warning 467: Overloaded foo(int) not supported (no type checking -rule for 'int'). +example.i:3: Warning 467: Overloaded foo(int) not supported (incomplete type checking rule - +no precedence level in typecheck typemap for 'int').This error means that the target language module supports overloading, but for some reason there is no type-checking rule that can be used to generate a working dispatch function. The resulting behavior is then undefined. You should report this as a bug to the -SWIG bug tracking database.
+SWIG bug tracking database if this is due to one of the typemaps + supplied with SWIG.If you get an error message such as the following,
@@ -7730,8 +8150,8 @@ foo.i:5. Previous declaration is Spam::foo(int )it means that the target language module has not yet implemented support for overloaded functions and methods. The only way to fix the problem is to read the next section.
-6.15.3 - Ambiguity resolution and renaming
+6.15.3 Ambiguity + resolution and renaming
If an ambiguity in overload resolution occurs or if a module doesn't allow overloading, there are a few strategies for dealing with the problem. First, you can tell SWIG to ignore one of the methods. This is @@ -7998,7 +8418,8 @@ public:
Currently no resolution is performed in order to match function parameters. This means function parameter types must match exactly. For example, namespace qualifiers and typedefs will not work. The following - usage of typedefs demonstrates this:
+ usage of typedefs demonstrates this: +- +typedef int Integer; @@ -8013,8 +8434,7 @@ public: void foo(int); // Renamed to foo_i };-- -
The name matching rules also use default arguments for finer control when wrapping methods that have default arguments. Recall that methods @@ -8070,7 +8490,7 @@ newbar(2, 2.0), newbar(2) or newbar(). However, the changes to wrapping methods with default arguments was introduced.
6.15.4 Comments on overloading
+6.15.4 Comments on overloading
Support for overloaded methods was first added in SWIG-1.3.14. The implementation is somewhat unusual when compared to similar tools. For instance, the order in which declarations appear is largely irrelevant @@ -8081,7 +8501,7 @@ newbar(2, 2.0), newbar(2) or newbar(). However, support may vary from language to language. As a general rule, statically typed languages like Java are able to provide more support than dynamically typed languages like Perl, Python, Ruby, and Tcl.
-6.16 Wrapping overloaded operators
+6.16 Wrapping overloaded operators
C++ overloaded operator declarations can be wrapped. For example, consider a class like this:
@@ -8105,7 +8525,7 @@ public: } Complex operator*(const Complex &c) const { return Complex(rpart*c.rpart - ipart*c.ipart, - rpart*c.ipart + c.rpart*ipart); + rpart*c.ipart + c.rpart*ipart); } Complex operator-() const { return Complex(-rpart, -ipart); @@ -8218,7 +8638,7 @@ Complex operator+(Complex &, double);@@ -8294,7 +8714,7 @@ struct Derived : Base {- The semantics of certain C++ operators may not match those in the target language.
-6.17 Class extension
+6.17 Class extension
New methods can be added to a class using the %extend directive. This directive is primarily used in conjunction with proxy classes to add additional functionality to an existing class. For @@ -8232,17 +8652,17 @@ Complex operator+(Complex &, double); class Vector { public: - double x,y,z; - Vector(); - ~Vector(); - ... bunch of C++ methods ... - %extend { - char *__str__() { - static char temp[256]; - sprintf(temp,"[ %g, %g, %g ]", $self->x,$self->y,$self->z); - return &temp[0]; - } - } + double x,y,z; + Vector(); + ~Vector(); + ... bunch of C++ methods ... + %extend { + char *__str__() { + static char temp[256]; + sprintf(temp,"[ %g, %g, %g ]", $self->x,$self->y,$self->z); + return &temp[0]; + } + } };
The following special variables are expanded if used within a %extend block: $name, $symname, $overname, $decl, $fulldecl, - $parentname and $parentsymname. The + $parentclassname and $parentclasssymname. The Special variables section provides more information each of these special variables.
The %extend directive follows all of the same conventions @@ -8304,7 +8724,7 @@ Adding member functions to C structures section for further details.
name for the %addmethods directive in SWIG1.1. Since %addmethods could be used to extend a structure with more than just methods, a more suitable directive name has been chosen. -6.18 Templates
+6.18 Templates
Template type names may appear anywhere a type is expected in an interface file. For example:
@@ -8842,7 +9262,7 @@ public: template<class T> class List { ... public: - List() { }; + List() { } T get(int index); ... }; @@ -8883,10 +9303,42 @@ template<class T> void foo(T x, T y) { }; point is that SWIG does not perform extensive error checking of templates! Specifically, SWIG does not perform type checking nor does it check to see if the actual contents of the template declaration - make any sense. Since the C++ compiler will hopefully check this when - it compiles the resulting wrapper file, there is no practical reason - for SWIG to duplicate this functionality (besides, none of the SWIG - developers are masochistic enough to want to implement this right now). + make any sense. Since the C++ compiler checks this when it compiles the + resulting wrapper file, there is no practical reason for SWIG to + duplicate this functionality. + +As SWIG's template support does not perform type checking +%template can be used as early as after a template declaration. You + can, and rarely have to, use %template before the template + parameters have been declared. For example:
+++template <class T> class OuterTemplateClass {}; + +// The nested class OuterClass::InnerClass inherits from the template class +// OuterTemplateClass<OuterClass::InnerStruct> and thus the template needs +// to be expanded with %template before the OuterClass declaration. +%template(OuterTemplateClass_OuterClass__InnerStruct) + OuterTemplateClass<OuterClass::InnerStruct> + + +// Don't forget to use %feature("flatnested") for OuterClass::InnerStruct and +// OuterClass::InnerClass if the target language doesn't support nested classes. +class OuterClass { + public: + // Forward declarations: + struct InnerStruct; + class InnerClass; +}; + +struct OuterClass::InnerStruct {}; + +// Expanding the template at this point with %template is too late as the +// OuterClass::InnerClass declaration is processed inside OuterClass. + +class OuterClass::InnerClass : public OuterTemplateClass<InnerStruct> {}; ++Compatibility Note: The first implementation of template support relied heavily on macro expansion in the preprocessor. Templates have been more tightly integrated into the parser and type @@ -8916,7 +9368,7 @@ template<class T> void foo(T x, T y) { };
Similar changes apply to typemaps and other customization features.
-6.19 Namespaces
+6.19 Namespaces
Support for C++ namespaces is comprehensive, but by default simple, however, some target languages can turn on more advanced namespace support via the nspace feature, @@ -9275,8 +9727,8 @@ namespace foo { modules are currently programmed with any namespace awareness. In the future, language modules may or may not provide more advanced namespace support.
-6.19.1 The nspace feature for - namespaces
+6.19.1 The nspace feature for namespaces +
Some target languages provide support for the nspace feature. The feature can be applied to any class, struct, union or enum declared within a named namespace. The feature wraps the type @@ -9343,8 +9795,8 @@ namespace MyWorld {
Compatibility Note: The nspace feature was first introduced in SWIG-2.0.0.
-6.20 - Renaming templated types in namespaces
+6.20 Renaming + templated types in namespaces
As has been mentioned, when %rename includes parameters, the parameter types must match exactly (no typedef or namespace resolution is performed). SWIG treats templated types slightly differently and has @@ -9415,8 +9867,8 @@ namespace Space { %template(ABCXYZ) Space::ABC<Space::XYZ>;
6.21 Exception - specifications
+6.21 Exception + specifications
When C++ programs utilize exceptions, exceptional behavior is sometimes specified as part of a function or method declaration. For example:
@@ -9456,7 +9908,7 @@ except Error,e: "Exception handling with %exception " section for details. The next section details a way of simulating an exception specification or replacing an existing one. -6.22 Exception handling with %catches
+6.22 Exception handling with %catches
Exceptions are automatically handled for methods with an exception specification. Similar handling can be achieved for methods without exception specifications through the %catches feature. It is @@ -9501,7 +9953,7 @@ Foo::blah(), SWIG will generate catch handlers for all of the types single catch handler for the base class, EBase will be generated to convert the C++ exception into a target language error/exception.
-6.23 Pointers to Members
+6.23 Pointers to Members
Starting with SWIG-1.3.7, there is limited parsing support for pointers to C++ class members. For example:
@@ -9532,8 +9984,8 @@ _ff0d54a800000000_m_Object__f_double_double__double with member pointers. Normally SWIG tries to keep track of inheritance when checking types. However, no such support is currently provided for member pointers. -6.24 Smart pointers and - operator->()
+6.24 Smart pointers and + operator->()
In some C++ programs, objects are often encapsulated by smart-pointers or proxy classes. This is sometimes done to implement automatic memory management (reference counting) or persistence. @@ -9698,10 +10150,11 @@ p = f.__deref__() # Raw pointer from operator->
Note: Smart pointer support was first added in SWIG-1.3.14.
-6.25 C++ reference counted objects - - ref/unref feature
+6.25 C++ reference counted objects - + ref/unref feature
Another similar idiom in C++ is the use of reference counted - objects. Consider for example:
+ objects. Consider for example: ++class RCObj { // implement the ref counting mechanism @@ -9716,11 +10169,11 @@ public: return add_ref(); } - int unref() const { + int unref() const { if (ref_count() == 0 || del_ref() == 0 ) { - delete this; - return 0; - } + delete this; + return 0; + } return ref_count(); } }; @@ -9760,7 +10213,7 @@ int main() { a->unref(); // 'a' unref and deleted (count: 0) }-In the example above, the 'A' class instance 'a' is a reference counted object, which can't be deleted arbitrarily since it is shared between the objects 'b1' and 'b2'. 'A' is derived from a Reference @@ -9836,7 +10289,7 @@ a = AFactory() # SWIG ref 'a' due to %newobject (count: 1) exit # 'a' is released, SWIG unref 'a' called in the destructor wrapper (count: 0)
6.26 Using declarations and inheritance
+6.26 Using declarations and inheritance
using declarations are sometimes used to adjust access to members of base classes. For example:
@@ -9970,134 +10423,61 @@ public:6.27 Nested classes
-There is some support for nested structs and unions when wrapping C - code, see Nested structures for - further details. The added complexity of C++ compared to C means this - approach does not work well for C++ code (when using the -c++ command - line option). For C++, a nested class is treated much like an opaque - pointer, so anything useful within the nested class, such as its - methods and variables, are not accessible from the target language. - True nested class support may be added to SWIG in the future, however, - until then some of the following workarounds can be applied to improve - the situation.
-It might be possible to use partial class information as often you - can accept that the nested class is not needed, especially if it is not - actually used in any methods you need from the target language. Imagine - you are wrapping the following Outer class which contains a - nested class Inner. The easiest thing to do is turn a blind - eye to the warning that SWIG generates, or simply suppress it:
----%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::Inner; - -class Outer { -public: - class Inner { - public: - ... - }; - Inner getInner(); - void useInner(const Inner& inner); - ... -}; --Note that if Inner can be used as an opaque type, the - default wrapping approach suffices. For example, if the nested class - does not need to be created from the target language, but can be - obtained via a method call, such as the getInner() method - above, the returned value can then be passed around, such as passed - into the useInner() method.
-With some more effort the above situation can be improved somewhat - and a nested class can be constructed and used from the target language - much like any other non-nested class. Assuming we have the Outer - class in a header file:
----// File outer.h -class Outer { -public: - class Inner { - public: - int var; - Inner(int v = 0) : var(v) {} - }; - Inner getInner(); - void useInner(const Inner& inner); -}; --The following interface file works around the nested class - limitations by redefining the nested class as a global class. A typedef - for the compiler and the nestedworkaround -feature flag is also required in order for the generated wrappers to - compile. This flag simply removes all the type information from SWIG, - so SWIG treats the nested class as if it had not been parsed at all.
---// File : example.i -%module example - -// Redefine nested class in global scope in order for SWIG to generate -// a proxy class. Only SWIG parses this definition. -class Inner { +6.27 Nested classes
+If the target language supports the nested classes concept (like + Java), the nested C++ classes are wrapped as nested target language + proxy classes. (In case of Java - "static" nested classes.) Only public + nested classes are wrapped. Otherwise there is little difference + between nested and normal classes.
+If the target language doesn't support nested classes directly, or + the support is not implemented in the language module (like for python + currently), then the visible nested classes are moved to the same name + space as the containing class (nesting hierarchy is "flattened"). The + same behaviour may be turned on for C# and Java by the %feature + ("flatnested"); If there is a class with the same name in the outer + namespace the inner class (or the global one) may be renamed or + ignored:
++-+%rename (Bar_Foo) Bar::Foo; +class Foo {}; +class Bar { public: - int var; - Inner(int v = 0) : var(v) {} -}; - -%nestedworkaround Outer::Inner; - -%{ -#include "outer.h" -%} -%include "outer.h" - -// We've fooled SWIG into thinking that Inner is a global class, so now we need -// to trick the C++ compiler into understanding this apparent global type. -%{ -typedef Outer::Inner Inner; -%} --The downside to this approach is a more complex interface file and - having to maintain two definitions of Inner, the real one and - the one in the interface file that SWIG parses. However, the upside is - that all the methods/variables in the nested class are available from - the target language as a proxy class is generated instead of treating - the nested class as an opaque type. The proxy class can be constructed - from the target language and passed into any methods accepting the - nested class. Also note that the original header file is parsed - unmodified.
-Finally, conditional compilation can be used as a workaround to - comment out nested class definitions in the actual headers, assuming - you are able to modify them.
-+ class Foo {}; +}; + ++If a nested class, within an outer class, has to be used as a + template parameter within the outer class, then the template will have + to be instantiated with %template before the beginning of the + outer class. An example can be found in the +Templates section.
+Compatibility Note: Prior to SWIG-3.0.0, there was limited + nested class support. Nested classes were treated as opaque pointers. + However, there was a workaround for nested class support in these older + versions requiring the user to replicate the nested class in the global + scope, adding in a typedef for the nested class in the global scope and + using the "nestedworkaround" feature on the nested class. This resulted + in approximately the same behaviour as the "flatnested" feature. With + proper nested class support now available in SWIG-3.0.0, this feature + has been deprecated and no longer works requiring code changes. If you + see the following warning:
+--// File outer.h -class Outer { -public: -#ifndef SWIG - class Inner { - public: - ... - }; -#endif - ... -}; +example.i:8: Warning 126: The nestedworkaround feature is deprecatedThis workaround used to be common when SWIG could not deal with - nested classes particulary well. This should just be a last resort for - unusual corner cases now as SWIG can parse nested classes and even - handle nested template classes fairly well.
-Compatibility Note: SWIG-1.3.40 and earlier versions did not - have the nestedworkaround feature and the generated code - resulting from parsing nested classes did not always compile. Nested - class warnings could also not be suppressed using %warnfilter.
-6.28 A brief rant about - const-correctness
+consider using the "flatnested" feature discussed above which + generates a non-nested proxy class, like the "nestedworkaround" feature + did. Alternatively, use the default nested class code generation, which + may generate an equivalent to a nested proxy class in the target + language, depending on the target language support.
+SWIG-1.3.40 and earlier versions did not have the +nestedworkaround feature and the generated code resulting from + parsing nested classes did not always compile. Nested class warnings + could also not be suppressed using %warnfilter.
+6.28 A brief rant about const-correctness +
A common issue when working with C++ programs is dealing with all possible ways in which the const qualifier (or lack thereof) will break your program, all programs linked against your program, and @@ -10136,7 +10516,7 @@ void blah() { a problem for most SWIG projects. Of course, you might want to consider using another tool if maintaining constness is the most important part of your project.
-6.29 Where to go for more information
+6.29 Where to go for more information
If you're wrapping serious C++ code, you might want to pick up a copy of "The Annotated C++ Reference Manual" by Ellis and Stroustrup. This is the reference document we use to guide a lot of SWIG's C++ @@ -10151,8793 +10531,10035 @@ void blah() {
-7 Preprocessing
+7 SWIG and C++11
--
- File inclusion
-- File imports
-- Conditional - Compilation
-- Macro Expansion
-- SWIG Macros
-- C99 and GNU Extensions
-- Preprocessing and delimiters -
-
- Preprocessing and %{ ... %} & " ... " - delimiters
-- Preprocessing and { ... } delimiters
+- Introduction
+- Core language changes +
++
+- Rvalue + reference and move semantics
+- Generalized + constant expressions
+- Extern template
+- Initializer lists
+- Uniform initialization +
+- Type inference
+- Range-based for-loop
+- Lambda + functions and expressions
+- Alternate function + syntax
+- Object + construction improvement
+- Explicit overrides + and final
+- Null pointer constant +
+- Strongly typed + enumerations
+- Double angle brackets +
+- Explicit + conversion operators
+- Alias templates
+- Unrestricted unions
+- Variadic templates
+- New string literals
+- User-defined literals +
+- Thread-local storage
+- Explicitly defaulted + functions and deleted functions
+- Type long long int
+- Static assertions
+- Allow sizeof to work on members of + classes without an explicit object
+- Exception specifications and + noexcept
+- Control and query object alignment +
+- Attributes
+- Standard library + changes +
-+
- Threading facilities
+- Tuple types
+- Hash tables
+- Regular expressions
+- +General-purpose smart pointers
+- Extensible + random number facility
+- Wrapper reference
+- +Polymorphous wrappers for function objects
+- Type traits + for metaprogramming
+- +Uniform method for computing return type of function objects
- Preprocessor and Typemaps -
-- Viewing preprocessor output
-- The #error and #warning - directives
SWIG includes its own enhanced version of the C preprocessor. The - preprocessor supports the standard preprocessor directives and macro - expansion rules. However, a number of modifications and enhancements - have been made. This chapter describes some of these modifications.
-7.1 File inclusion
-To include another file into a SWIG interface, use the %include - directive like this:
+7.1 Introduction
+This chapter gives you a brief overview about the SWIG implementation + of the C++11 standard. This part of SWIG is still a work in progress.
+SWIG supports the new C++ syntax changes with some minor limitations + in some areas such as decltype expressions and variadic templates. + Wrappers for the new STL types (unordered_ containers, result_of, + tuples) are incomplete. The wrappers for the new containers would work + much like the C++03 containers and users are welcome to help by + adapting the existing container interface files and submitting them as + a patch for inclusion in future versions of SWIG.
+7.2 Core language + changes
+7.2.1 + Rvalue reference and move semantics
+SWIG correctly parses the rvalue reference syntax '&&', for example + the typical usage of it in the move constructor and move assignment + operator below:
--%include "pointer.i" +class MyClass { +... + std::vector<int> numbers; +public: + MyClass(MyClass &&other) : numbers(std::move(other.numbers)) {} + MyClass & operator=(MyClass &&other) { + numbers = std::move(other.numbers); + return *this; + } +};Unlike, #include, %include includes each file once - (and will not reload the file on subsequent %include - declarations). Therefore, it is not necessary to use include-guards in - SWIG interfaces.
-By default, the #include is ignored unless you run SWIG - with the -includeall option. The reason for ignoring - traditional includes is that you often don't want SWIG to try and wrap - everything included in standard header system headers and auxiliary - files.
-7.2 File imports
-SWIG provides another file inclusion directive with the %import - directive. For example:
+Rvalue references are designed for C++ temporaries and so are not + very useful when used from non-C++ target languages. Generally you + would just ignore them via %ignore before parsing the class. + For example, ignore the move constructor:
--%import "foo.i" +%ignore MyClass::MyClass(MyClass &&);The purpose of %import is to collect certain information - from another SWIG interface file or a header file without actually - generating any wrapper code. Such information generally includes type - declarations (e.g., typedef) as well as C++ classes that might - be used as base-classes for class declarations in the interface. The - use of %import is also important when SWIG is used to generate - extensions as a collection of related modules. This is an advanced - topic and is described in later in the Working with - Modules chapter.
-The -importall directive tells SWIG to follow all -#include statements as imports. This might be useful if you want to - extract type definitions from system header files without generating - any wrappers.
-7.3 Conditional - Compilation
-SWIG fully supports the use of #if, #ifdef, -#ifndef, #else, #endif to conditionally include - parts of an interface. The following symbols are predefined by SWIG - when it is parsing the interface:
-+The plan is to ignore move constructors by default in a future + version of SWIG. Note that both normal assignment operators as well as + move assignment operators are ignored by default in most target + languages with the following warning:
+--SWIG Always defined when SWIG is processing a file -SWIGIMPORTED Defined when SWIG is importing a file with %import -SWIG_VERSION Hexadecimal (binary-coded decimal) number containing SWIG version, - such as 0x010311 (corresponding to SWIG-1.3.11). - -SWIGALLEGROCL Defined when using Allegro CL -SWIGCFFI Defined when using CFFI -SWIGCHICKEN Defined when using CHICKEN -SWIGCLISP Defined when using CLISP -SWIGCSHARP Defined when using C# -SWIGGUILE Defined when using Guile -SWIGJAVA Defined when using Java -SWIGLUA Defined when using Lua -SWIGMODULA3 Defined when using Modula-3 -SWIGMZSCHEME Defined when using Mzscheme -SWIGOCAML Defined when using Ocaml -SWIGOCTAVE Defined when using Octave -SWIGPERL Defined when using Perl -SWIGPHP Defined when using PHP -SWIGPIKE Defined when using Pike -SWIGPYTHON Defined when using Python -SWIGR Defined when using R -SWIGRUBY Defined when using Ruby -SWIGSEXP Defined when using S-expressions -SWIGTCL Defined when using Tcl -SWIGXML Defined when using XML +example.i:18: Warning 503: Can't wrap 'operator =' unless renamed to a valid identifier.In addition, SWIG defines the following set of standard C/C++ - macros:
+7.2.2 + Generalized constant expressions
+SWIG parses and identifies the keyword constexpr, but cannot + fully utilise it. These C++ compile time constants are usable as + runtime constants from the target languages. Below shows example usage + for assigning a C++ compile time constant from a compile time constant + function:
--__LINE__ Current line number -__FILE__ Current file name -__STDC__ Defined to indicate ANSI C -__cplusplus Defined when -c++ option used +constexpr int XXX() { return 10; } +constexpr int YYY = XXX() + 100;Interface files can look at these symbols as necessary to change the - way in which an interface is generated or to mix SWIG directives with C - code. These symbols are also defined within the C code generated by - SWIG (except for the symbol `SWIG' which is only defined - within the SWIG compiler).
-7.4 Macro Expansion
-Traditional preprocessor macros can be used in SWIG interfaces. Be - aware that the #define statement is also used to try and - detect constants. Therefore, if you have something like this in your - file,
+When either of these is used from a target language, a runtime call + is made to obtain the underlying constant.
+7.2.3 Extern template
+SWIG correctly parses the keywords extern template. However, + this template instantiation suppression in a translation unit has no + relevance outside of the C++ compiler and so is not used by SWIG. SWIG + only uses %template for instantiating and wrapping templates.
--#ifndef _FOO_H 1 -#define _FOO_H 1 -... -#endif +template class std::vector<int>; // C++03 explicit instantiation in C++ +extern template class std::vector<int>; // C++11 explicit instantiation suppression in C++ +%template(VectorInt) std::vector<int>; // SWIG instantiationyou may get some extra constants such as _FOO_H showing up - in the scripting interface.
-More complex macros can be defined in the standard way. For example:
-+7.2.4 Initializer lists
+Initializer lists are very much a C++ compiler construct and are not + very accessible from wrappers as they are intended for compile time + initialization of classes using the special std::initializer_list + type. SWIG detects usage of initializer lists and will emit a special + informative warning each time one is used:
+--#define EXTERN extern -#ifdef __STDC__ -#define _ANSI(args) (args) -#else -#define _ANSI(args) () -#endif +example.i:33: Warning 476: Initialization using std::initializer_list.The following operators can appear in macro definitions:
--
-- #x -
-
Converts macro argument x to a string surrounded by double - quotes ("x").- x ## y -
-
Concatenates x and y together to form xy.- `x` -
-
If x is a string surrounded by double quotes, do nothing. - Otherwise, turn into a string like #x. This is a non-standard - SWIG extension.7.5 SWIG Macros
-SWIG provides an enhanced macro capability with the %define - and %enddef directives. For example:
+Initializer lists usually appear in constructors but can appear in + any function or method. They often appear in constructors which are + overloaded with alternative approaches to initializing a class, such as + the std container's push_back method for adding elements to a + container. The recommended approach then is to simply ignore the + initializer-list constructor, for example:
--%define ARRAYHELPER(type,name) -%inline %{ -type *new_ ## name (int nitems) { - return (type *) malloc(sizeof(type)*nitems); -} -void delete_ ## name(type *t) { - free(t); -} -type name ## _get(type *t, int index) { - return t[index]; -} -void name ## _set(type *t, int index, type val) { - t[index] = val; -} -%} -%enddef - -ARRAYHELPER(int, IntArray) -ARRAYHELPER(double, DoubleArray) +%ignore Container::Container(std::initializer_list<int>); +class Container { +public: + Container(std::initializer_list<int>); // initializer-list constructor + Container(); + void push_back(const int &); + ... +};The primary purpose of %define is to define large macros of - code. Unlike normal C preprocessor macros, it is not necessary to - terminate each line with a continuation character (\)--the macro - definition extends to the first occurrence of %enddef. - Furthermore, when such macros are expanded, they are reparsed through - the C preprocessor. Thus, SWIG macros can contain all other - preprocessor directives except for nested %define statements.
-The SWIG macro capability is a very quick and easy way to generate - large amounts of code. In fact, many of SWIG's advanced features and - libraries are built using this mechanism (such as C++ template - support).
-7.6 C99 and GNU Extensions
-SWIG-1.3.12 and newer releases support variadic preprocessor macros. - For example:
+Alternatively you could modify the class and add another constructor + for initialization by some other means, for example by a +std::vector:
--#define DEBUGF(fmt,...) fprintf(stderr,fmt,__VA_ARGS__) +%include <std_vector.i> +class Container { +public: + Container(const std::vector<int> &); + Container(std::initializer_list<int>); // initializer-list constructor + Container(); + void push_back(const int &); + ... +};When used, any extra arguments to ... are placed into the - special variable __VA_ARGS__. This also works with special - SWIG macros defined using %define.
-SWIG allows a variable number of arguments to be empty. However, - this often results in an extra comma (,) and syntax error in the - resulting expansion. For example:
-+And then call this constructor from your target language, for + example, in Python, the following will call the constructor taking the +std::vector:
+--DEBUGF("hello"); --> fprintf(stderr,"hello",); +>>> c = Container( [1,2,3,4] )To get rid of the extra comma, use ## like this:
+If you are unable to modify the class being wrapped, consider + ignoring the initializer-list constructor and using %extend to add in + an alternative constructor:
--#define DEBUGF(fmt,...) fprintf(stderr,fmt, ##__VA_ARGS__) +%include <std_vector.i> +%extend Container { + Container(const std::vector<int> &elements) { + Container *c = new Container(); + for (int element : elements) + c->push_back(element); + return c; + } +} + +%ignore Container::Container(std::initializer_list<int>); + +class Container { +public: + Container(std::initializer_list<int>); // initializer-list constructor + Container(); + void push_back(const int &); + ... +};SWIG also supports GNU-style variadic macros. For example:
+The above makes the wrappers look is as if the class had been + declared as follows:
--#define DEBUGF(fmt, args...) fprintf(stdout,fmt,args) +%include <std_vector.i> +class Container { +public: + Container(const std::vector<int> &); +// Container(std::initializer_list<int>); // initializer-list constructor (ignored) + Container(); + void push_back(const int &); + ... +};Comment: It's not entirely clear how variadic macros might be - useful to interface building. However, they are used internally to - implement a number of SWIG directives and are provided to make SWIG - more compatible with C99 code.
-7.7 Preprocessing and - delimiters
-The preprocessor handles { }, " " and %{ %} delimiters differently.
-7.7.1 Preprocessing and %{ ... %} & " - ... " delimiters
-The SWIG preprocessor does not process any text enclosed in a code - block %{ ... %}. Therefore, if you write code like this,
+std::initializer_list is simply a container that can only + be initialized at compile time. As it is just a C++ type, it is + possible to write typemaps for a target language container to map onto +std::initializer_list. However, this can only be done for a fixed + number of elements as initializer lists are not designed to be + constructed with a variable number of arguments at runtime. The example + below is a very simple approach which ignores any parameters passed in + and merely initializes with a fixed list of fixed integer values chosen + at compile time:
--%{ -#ifdef NEED_BLAH -int blah() { - ... +%typemap(in) std::initializer_list<int> { + $1 = {10, 20, 30, 40, 50}; } -#endif -%} +class Container { +public: + Container(std::initializer_list<int>); // initializer-list constructor + Container(); + void push_back(const int &); + ... +};the contents of the %{ ... %} block are copied without - modification to the output (including all preprocessor directives).
-7.7.2 Preprocessing and { ... } - delimiters
-SWIG always runs the preprocessor on text appearing inside { ... - }. However, sometimes it is desirable to make a preprocessor - directive pass through to the output file. For example:
+Any attempt at passing in values from the target language will be + ignored and be replaced by {10, 20, 30, 40, 50}. Needless to + say, this approach is very limited, but could be improved upon, but + only slightly. A typemap could be written to map a fixed number of + elements on to the std::initializer_list, but with values + decided at runtime. The typemaps would be target language specific.
+Note that the default typemap for std::initializer_list + does nothing but issue the warning and hence any user supplied typemaps + will override it and suppress the warning.
+7.2.5 Uniform + initialization
+The curly brackets {} for member initialization are fully supported + by SWIG:
--%extend Foo { - void bar() { - #ifdef DEBUG - printf("I'm in bar\n"); - #endif - } -} +struct BasicStruct { + int x; + double y; +}; + +struct AltStruct { + AltStruct(int x, double y) : x_{x}, y_{y} {} + + int x_; + double y_; +}; + +BasicStruct var1{5, 3.2}; // only fills the struct components +AltStruct var2{2, 4.3}; // calls the constructorBy default, SWIG will interpret the #ifdef DEBUG statement. - However, if you really wanted that code to actually go into the wrapper - file, prefix the preprocessor directives with % like this:
-+Uniform initialization does not affect usage from the target + language, for example in Python:
+--%extend Foo { - void bar() { - %#ifdef DEBUG - printf("I'm in bar\n"); - %#endif - } -} +>>> a = AltStruct(10, 142.15) +>>> a.x_ +10 +>>> a.y_ +142.15SWIG will strip the extra % and leave the preprocessor - directive in the code.
-7.8 Preprocessor and - Typemaps
-Typemaps support a special attribute called -noblock where the { ... } delimiters can be used, but the - delimiters are not actually generated into the code. The effect is then - similar to using "" or %{ %} delimiters but the code is run - through the preprocessor. For example:
+7.2.6 Type inference
+SWIG supports decltype() with some limitations. Single + variables are allowed, however, expressions are not supported yet. For + example, the following code will work:
--#define SWIG_macro(CAST) (CAST)$input -%typemap(in) Int {$1= SWIG_macro(int);} +int i; +decltype(i) j;might generate
+However, using an expression inside the decltype results in syntax + error:
-- { - arg1=(int)jarg1; - } +int i; int j; +decltype(i+j) k; // syntax errorwhereas
+7.2.7 Range-based + for-loop
+This feature is part of the implementation block only. SWIG ignores + it.
+7.2.8 Lambda + functions and expressions
+SWIG correctly parses most of the Lambda functions syntax. For + example:
--#define SWIG_macro(CAST) (CAST)$input -%typemap(in,noblock=1) Int {$1= SWIG_macro(int);} +auto val = [] { return something; }; +auto sum = [](int x, int y) { return x+y; }; +auto sum = [](int x, int y) -> int { return x+y; };might generate
+The lambda functions are removed from the wrappers for now, because + of the lack of support for closures (scope of the lambda functions) in + the target languages.
+Lambda functions used to create variables can also be parsed, but + due to limited support of auto when the type is deduced from + the expression, the variables are simply ignored.
-- arg1=(int)jarg1; +auto six = [](int x, int y) { return x+y; }(4, 2);and
+Better support should be available in a later release.
+7.2.9 Alternate + function syntax
+SWIG fully supports the new definition of functions. For example:
--#define SWIG_macro(CAST) (CAST)$input -%typemap(in) Int %{$1=SWIG_macro(int);%} +struct SomeStruct { + int FuncName(int x, int y); +};would generate
+can now be written as in C++11:
-- arg1=SWIG_macro(int); +struct SomeStruct { + auto FuncName(int x, int y) -> int; +}; + +auto SomeStruct::FuncName(int x, int y) -> int { + return x + y; +}7.9 Viewing preprocessor output
-Like many compilers, SWIG supports a -E command line option - to display the output from the preprocessor. When the -E - switch is used, SWIG will not generate any wrappers. Instead the - results after the preprocessor has run are displayed. This might be - useful as an aid to debugging and viewing the results of macro - expansions.
-7.10 The #error and - #warning directives
-SWIG supports the commonly used #warning and #error - preprocessor directives. The #warning directive will cause - SWIG to issue a warning then continue processing. The #error - directive will cause SWIG to exit with a fatal error. Example usage:
-+The usage in the target languages remains the same, for example in + Python:
+--#error "This is a fatal error message" -#warning "This is a warning message" +>>> a = SomeStruct() +>>> a.FuncName(10,5) +15The #error behaviour can be made to work like #warning - if the -cpperraswarn commandline option is used. - Alternatively, the #pragma directive can be used to the same - effect, for example:
+SWIG will also deal with type inference for the return type, as per + the limitations described earlier. For example:
- /* Modified behaviour: #error does not cause SWIG to exit with error */ - #pragma SWIG cpperraswarn=1 - /* Normal behaviour: #error does cause SWIG to exit with error */ - #pragma SWIG cpperraswarn=0 +auto square(float a, float b) -> decltype(a);-
-8 SWIG library
- - --- --
-- The %include directive and library search - path
-- C Arrays and Pointers -
--
-- cpointer.i
-- carrays.i
-- cmalloc.i
-- cdata.i
-- C String Handling - -
-- STL/C++ Library - -
-- Utility Libraries -
--
-- exception.i
-To help build extension modules, SWIG is packaged with a library of - support files that you can include in your own interfaces. These files - often define new SWIG directives or provide utility functions that can - be used to access parts of the standard C and C++ libraries. This - chapter provides a reference to the current set of supported library - files.
-Compatibility note: Older versions of SWIG included a number - of library files for manipulating pointers, arrays, and other - structures. Most these files are now deprecated and have been removed - from the distribution. Alternative libraries provide similar - functionality. Please read this chapter carefully if you used the old - libraries.
-8.1 The %include directive and library - search path
-Library files are included using the %include directive. - When searching for files, directories are searched in the following - order:
--
-- The current directory
-- Directories specified with the -I command line option
-- ./swig_lib
-- SWIG library install location as reported by swig -swiglib, - for example /usr/local/share/swig/1.3.30
-- On Windows, a directory Lib relative to the location of -swig.exe is also searched.
-Within directories mentioned in points 3-5, SWIG first looks for a - subdirectory corresponding to a target language (e.g., python, - tcl, etc.). If found, SWIG will search the language specific - directory first. This allows for language-specific implementations of - library files.
-You can ignore the installed SWIG library by setting the -SWIG_LIB environment variable. Set the environment variable to hold - an alternative library directory.
-The directories that are searched are displayed when using --verbose commandline option.
-8.2 C Arrays and Pointers
-This section describes library modules for manipulating low-level C - arrays and pointers. The primary use of these modules is in supporting - C declarations that manipulate bare pointers such as int *, -double *, or void *. The modules can be used to allocate - memory, manufacture pointers, dereference memory, and wrap pointers as - class-like objects. Since these functions provide direct access to - memory, their use is potentially unsafe and you should exercise - caution.
-8.2.1 cpointer.i
-The cpointer.i module defines macros that can be used to - used to generate wrappers around simple C pointers. The primary use of - this module is in generating pointers to primitive datatypes such as -int and double.
-%pointer_functions(type,name)
--Generates a collection of four functions for manipulating a pointer -type *:
-type *new_name()
---Creates a new object of type type and returns a pointer to - it. In C, the object is created using calloc(). In C++, -new is used.
-type *copy_name(type value)
---Creates a new object of type type and returns a pointer to - it. An initial value is set by copying it from value. In C, - the object is created using calloc(). In C++, new is - used.
-type *delete_name(type *obj)
---Deletes an object type type.
-void name_assign(type *obj, type value)
---Assigns *obj = value.
type name_value(type *obj)
---Returns the value of *obj.
-When using this macro, type may be any type and name - must be a legal identifier in the target language. name should - not correspond to any other name used in the interface file.
-Here is a simple example of using %pointer_functions():
+7.2.10 Object + construction improvement
+There are three parts to object construction improvement. The first + improvement is constructor delegation such as the following:
+-%module example -%include "cpointer.i" +class A { +public: + int a; + int b; + int c; -/* Create some functions for working with "int *" */ -%pointer_functions(int, intp); + A() : A(10) {} + A(int aa) : A(aa, 20) {} + A(int aa, int bb) : A(aa, bb, 30) {} + A(int aa, int bb, int cc) { a=aa; b=bb; c=cc; } +}; ++where peer constructors can be called. SWIG handles this without any + issue.
+The second improvement is constructor inheritance via a using + declaration. This is parsed correctly, but the additional constructors + are not currently added to the derived proxy class in the target + language. An example is shown below: + +
++-+class BaseClass { +public: + BaseClass(int iValue); +}; -/* A function that uses an "int *" */ -void add(int x, int y, int *result); +class DerivedClass: public BaseClass { + public: + using BaseClass::BaseClass; // Adds DerivedClass(int) constructor +};Now, in Python:
-+-The final part is member initialization at the site of the + declaration. This kind of initialization is handled by SWIG.
+->>> import example ->>> c = example.new_intp() # Create an "int" for storing result ->>> example.add(3,4,c) # Call function ->>> example.intp_value(c) # Dereference -7 ->>> example.delete_intp(c) # Delete +class SomeClass { +public: + SomeClass() {} + explicit SomeClass(int new_value) : value(new_value) {} + + int value = 5; +};-%pointer_class(type,name)
--+Wraps a pointer of type * inside a class-based interface. - This interface is as follows:
+7.2.11 Explicit + overrides and final
+The special identifiers final and override can be + used on methods and destructors, such as in the following example:
--struct name { - name(); // Create pointer object - ~name(); // Delete pointer object - void assign(type value); // Assign value - type value(); // Get value - type *cast(); // Cast the pointer to original type - static name *frompointer(type *); // Create class wrapper from existing - // pointer +struct BaseStruct { + virtual void ab() const = 0; + virtual void cd(); + virtual void ef(); + virtual ~BaseStruct(); +}; +struct DerivedStruct : BaseStruct { + virtual void ab() const override; + virtual void cd() final; + virtual void ef() final override; + virtual ~DerivedStruct() override; };When using this macro, type is restricted to a simple type - name like int, float, or Foo. Pointers and - other complicated types are not allowed. name must be a valid - identifier not already in use. When a pointer is wrapped as a class, - the "class" may be transparently passed to any function that expects - the pointer.
-If the target language does not support proxy classes, the use of - this macro will produce the example same functions as -%pointer_functions() macro.
-It should be noted that the class interface does introduce a new - object or wrap a pointer inside a special structure. Instead, the raw - pointer is used directly.
-Here is the same example using a class instead:
+7.2.12 Null pointer + constant
+The nullptr constant is mostly unimportant in wrappers. In + the few places it has an effect, it is treated like NULL.
+7.2.13 Strongly + typed enumerations
+SWIG supports strongly typed enumerations and parses the new enum + class syntax and forward declarator for the enums, such as:
+-%module example -%include "cpointer.i" - -/* Wrap a class interface around an "int *" */ -%pointer_class(int, intp); +enum class MyEnum : unsigned int; ++Strongly typed enums are often used to avoid name clashes such as + the following:
++-+struct Color { + enum class RainbowColors : unsigned int { + Red, Orange, Yellow, Green, Blue, Indigo, Violet + }; + + enum class WarmColors { + Yellow, Orange, Red + }; -/* A function that uses an "int *" */ -void add(int x, int y, int *result); + // Note normal enum + enum PrimeColors { + Red=100, Green, Blue + }; +};Now, in Python (using proxy classes)
+There are various ways that the target languages handle enums, so it + is not possible to precisely state how they are handled in this + section. However, generally, most scripting languages mangle in the + strongly typed enumeration's class name, but do not use any additional + mangling for normal enumerations. For example, in Python, the following + code
-->>> import example ->>> c = example.intp() # Create an "int" for storing result ->>> example.add(3,4,c) # Call function ->>> c.value() # Dereference -7 +print Color.RainbowColors_Red, Color.WarmColors_Red, Color.RedOf the two macros, %pointer_class is probably the most - convenient when working with simple pointers. This is because the - pointers are access like objects and they can be easily garbage - collected (destruction of the pointer object destroys the underlying - object).
+results in
++-+0 2 100 +%pointer_cast(type1, type2, name)
--Creates a casting function that converts type1 to type2 -. The name of the function is name. For example:
-+The strongly typed languages often wrap normal enums into an enum + class and so treat normal enums and strongly typed enums the same. The + equivalent in Java is:
+--%pointer_cast(int *, unsigned int *, int_to_uint); +System.out.println(Color.RainbowColors.Red.swigValue() + " " + Color.WarmColors.Red.swigValue() + " " + Color.PrimeColors.Red.swigValue());In this example, the function int_to_uint() would be used - to cast types in the target language.
+7.2.14 Double angle + brackets
+SWIG correctly parses the symbols >> as closing the template block, + if found inside it at the top level, or as the right shift operator >> + otherwise.
++-+std::vector<std::vector<int>> myIntTable; +Note: None of these macros can be used to safely work with - strings (char * or char **).
-Note: When working with simple pointers, typemaps can often - be used to provide more seamless operation.
-8.2.2 carrays.i
-This module defines macros that assist in wrapping ordinary C - pointers as arrays. The module does not provide any safety or an extra - layer of wrapping--it merely provides functionality for creating, - destroying, and modifying the contents of raw C array data.
-%array_functions(type,name)
--Creates four functions.
-type *new_name(int nelements)
--Creates a new array of objects of type type. In C, the - array is allocated using calloc(). In C++, new [] is - used.
+7.2.15 Explicit + conversion operators
+SWIG correctly parses the keyword explicit for operators in + addition to constructors now. For example:
++-+class U { +public: + int u; +}; + +class V { +public: + int v; +}; + +class TestClass { +public: + //implicit converting constructor + TestClass(U const &val) { t=val.u; } + + // explicit constructor + explicit TestClass(V const &val) { t=val.v; } + + int t; +}; + +struct Testable { + // explicit conversion operator + explicit operator bool() const { + return false; + } +}; +type *delete_name(type *ary)
--Deletes an array. In C, free() is used. In C++, delete - [] is used.
+The effect of explicit constructors and operators has little + relevance for the proxy classes as target languages don't have the same + concepts of implicit conversions as C++. Conversion operators either + with or without explicit need renaming to a valid identifier + name in order to make them available as a normal proxy method.
+7.2.16 Alias templates
+The following is an example of an alias template:
+++template< typename T1, typename T2, int > +class SomeType { +public: + T1 a; + T2 b; + int c; +}; + +template< typename T2 > +using TypedefName = SomeType<char*, T2, 5>; ++These are partially supported as SWIG will parse these and identify + them, however, they are ignored as they are not added to the type + system. A warning such as the following is issued:
++-+example.i:13: Warning 342: The 'using' keyword in template aliasing is not fully supported yet. +type name_getitem(type *ary, int index)
---Returns the value ary[index].
+Similarly for non-template type aliasing:
++-+using PFD = void (*)(double); // New introduced syntax +void name_setitem(type *ary, int index, type value)
---Assigns ary[index] = value.
+A warning will be issued:
++-+example.i:17: Warning 341: The 'using' keyword in type aliasing is not fully supported yet. +When using this macro, type may be any type and name - must be a legal identifier in the target language. name should - not correspond to any other name used in the interface file.
-Here is an example of %array_functions(). Suppose you had a - function like this:
+The equivalent old style typedefs can be used as a workaround:
--void print_array(double x[10]) { - int i; - for (i = 0; i < 10; i++) { - printf("[%d] = %g\n", i, x[i]); - } -} +typedef void (*PFD)(double); // The old styleTo wrap it, you might write this:
+7.2.17 Unrestricted unions +
+SWIG fully supports any type inside a union even if it does not + define a trivial constructor. For example, the wrapper for the + following code correctly provides access to all members in the union:
--%module example - -%include "carrays.i" -%array_functions(double, doubleArray); +struct point { + point() {} + point(int x, int y) : x_(x), y_(y) {} + int x_, y_; +}; -void print_array(double x[10]); +#include <new> // For placement 'new' in the constructor below +union P { + int z; + double w; + point p; // Illegal in C++03; legal in C++11. + // Due to the point member, a constructor definition is required. + P() { + new(&p) point(); + } +} p1;Now, in a scripting language, you might write this:
+7.2.18 Variadic templates +
+SWIG supports the variadic templates syntax (inside the <> block, + variadic class inheritance and variadic constructor and initializers) + with some limitations. The following code is correctly parsed:
-a = new_doubleArray(10) # Create an array -for i in range(0,10): - doubleArray_setitem(a,i,2*i) # Set a value -print_array(a) # Pass to C -delete_doubleArray(a) # Destroy array +template <typename... BaseClasses> class ClassName : public BaseClasses... { +public: + ClassName (BaseClasses &&... baseClasses) : BaseClasses(baseClasses)... {} +}-%array_class(type,name)
--+Wraps a pointer of type * inside a class-based interface. - This interface is as follows:
+For now however, the %template directive only accepts one + parameter substitution for the variable template parameters.
--struct name { - name(int nelements); // Create an array - ~name(); // Delete array - type getitem(int index); // Return item - void setitem(int index, type value); // Set item - type *cast(); // Cast to original type - static name *frompointer(type *); // Create class wrapper from - // existing pointer -}; +%template(MyVariant1) ClassName<> // zero argument not supported yet +%template(MyVariant2) ClassName<int> // ok +%template(MyVariant3) ClassName<int, int> // too many arguments not supported yetWhen using this macro, type is restricted to a simple type - name like int or float. Pointers and other - complicated types are not allowed. name must be a valid - identifier not already in use. When a pointer is wrapped as a class, it - can be transparently passed to any function that expects the pointer.
-When combined with proxy classes, the %array_class() macro - can be especially useful. For example:
+Support for the variadic sizeof() function is correctly + parsed:
--%module example -%include "carrays.i" -%array_class(double, doubleArray); - -void print_array(double x[10]); +const int SIZE = sizeof...(ClassName<int, int>);Allows you to do this:
+In the above example SIZE is of course wrapped as a + constant.
+7.2.19 New string literals +
+SWIG supports wide string and Unicode string constants and raw string + literals.
-import example -c = example.doubleArray(10) # Create double[10] -for i in range(0,10): - c[i] = 2*i # Assign values -example.print_array(c) # Pass to C +// New string literals +wstring aa = L"Wide string"; +const char *bb = u8"UTF-8 string"; +const char16_t *cc = u"UTF-16 string"; +const char32_t *dd = U"UTF-32 string"; + +// Raw string literals +const char *xx = ")I'm an \"ascii\" \\ string."; +const char *ee = R"XXX()I'm an "ascii" \ string.)XXX"; // same as xx +wstring ff = LR"XXX(I'm a "raw wide" \ string.)XXX"; +const char *gg = u8R"XXX(I'm a "raw UTF-8" \ string.)XXX"; +const char16_t *hh = uR"XXX(I'm a "raw UTF-16" \ string.)XXX"; +const char32_t *ii = UR"XXX(I'm a "raw UTF-32" \ string.)XXX";-Note: These macros do not encapsulate C arrays inside a - special data structure or proxy. There is no bounds checking or safety - of any kind. If you want this, you should consider using a special - array object rather than a bare pointer.
-Note: %array_functions() and %array_class() - should not be used with types of char or char *.
-8.2.3 cmalloc.i
-This module defines macros for wrapping the low-level C memory - allocation functions malloc(), calloc(), -realloc(), and free().
-%malloc(type [,name=type])
--+Creates a wrapper around malloc() with the following - prototype:
+Non-ASCII string support varies quite a bit among the various target + languages though.
+Note: There is a bug currently where SWIG's preprocessor incorrectly + parses an odd number of double quotes inside raw string literals.
+7.2.20 User-defined + literals
+SWIG parses the declaration of user-defined literals, that is, the +operator "" _mysuffix() function syntax.
+Some examples are the raw literal:
--type *malloc_name(int nbytes = sizeof(type)); +OutputType operator "" _myRawLiteral(const char * value);If type is void, then the size parameter -nbytes is required. The name parameter only needs to be - specified when wrapping a type that is not a valid identifier (e.g., " -int *", "double **", etc.).
+numeric cooked literals:
++-+OutputType operator "" _mySuffixIntegral(unsigned long long); +OutputType operator "" _mySuffixFloat(long double); +%calloc(type [,name=type])
---Creates a wrapper around calloc() with the following - prototype:
+and cooked string literals:
--type *calloc_name(int nobj =1, int sz = sizeof(type)); +OutputType operator "" _mySuffix(const char * string_values, size_t num_chars); +OutputType operator "" _mySuffix(const wchar_t * string_values, size_t num_chars); +OutputType operator "" _mySuffix(const char16_t * string_values, size_t num_chars); +OutputType operator "" _mySuffix(const char32_t * string_values, size_t num_chars);If type is void, then the size parameter sz - is required.
+Like other operators that SWIG parses, a warning is given about + renaming the operator in order for it to be wrapped:
++-+example.i:27: Warning 503: Can't wrap 'operator "" _myRawLiteral' unless renamed to a valid identifier. +%realloc(type [,name=type])
---Creates a wrapper around realloc() with the following - prototype:
+If %rename is used, then it can be called like any other wrapped + method. Currently you need to specify the full declaration including + parameters for %rename:
--type *realloc_name(type *ptr, int nitems); +%rename(MyRawLiteral) operator"" _myRawLiteral(const char * value);Note: unlike the C realloc(), the wrapper generated by this - macro implicitly includes the size of the corresponding type. For - example, realloc_int(p, 100) reallocates p so that it - holds 100 integers.
-%free(type [,name=type])
---Creates a wrapper around free() with the following - prototype:
+Or if you just wish to ignore it altogether:
-void free_name(type *ptr); +%ignore operator "" _myRawLiteral(const char * value);-%sizeof(type [,name=type])
--+Creates the constant:
+Note that use of user-defined literals such as the following still + give a syntax error:
-%constant int sizeof_name = sizeof(type); +OutputType var1 = "1234"_suffix; +OutputType var2 = 1234_suffix; +OutputType var3 = 3.1416_suffix;-%allocators(type [,name=type])
---Generates wrappers for all five of the above operations.
Here is a simple example that illustrates the use of these macros:
+7.2.21 Thread-local + storage
+SWIG correctly parses the thread_local keyword. For example, + variables reachable by the current thread can be defined as:
--// SWIG interface -%module example -%include "cmalloc.i" - -%malloc(int); -%free(int); - -%malloc(int *, intp); -%free(int *, intp); - -%allocators(double); +struct A { + static thread_local int val; +}; +thread_local int global_val;Now, in a script:
-+The use of the thread_local storage specifier does not + affect the wrapping process; it does not modify the wrapper code + compared to when it is not specified. A variable will be thread local + if accessed from different threads from the target language in the same + way that it will be thread local if accessed from C++ code.
+7.2.22 Explicitly defaulted + functions and deleted functions
+SWIG handles explicitly defaulted functions, that is, = default + added to a function declaration. Deleted definitions, which are also + called deleted functions, have = delete added to the function + declaration. For example:
+-->>> from example import * ->>> a = malloc_int() ->>> a -'_000efa70_p_int' ->>> free_int(a) ->>> b = malloc_intp() ->>> b -'_000efb20_p_p_int' ->>> free_intp(b) ->>> c = calloc_double(50) ->>> c -'_000fab98_p_double' ->>> c = realloc_double(100000) ->>> free_double(c) ->>> print sizeof_double -8 ->>> +struct NonCopyable { + NonCopyable & operator=(const NonCopyable &) = delete; /* Removes operator= */ + NonCopyable(const NonCopyable &) = delete; /* Removes copy constructor */ + NonCopyable() = default; /* Explicitly allows the empty constructor */ +};8.2.4 cdata.i
-The cdata.i module defines functions for converting raw C - data to and from strings in the target language. The primary - applications of this module would be packing/unpacking of binary data - structures---for instance, if you needed to extract data from a buffer. - The target language must support strings with embedded binary data in - order for this to work.
-const char *cdata(void *ptr, size_t nbytes)
--Converts nbytes of data at ptr into a string. -ptr can be any pointer.
+Wrappers for deleted functions will not be available in the target + language. Wrappers for defaulted functions will of course be available + in the target language. Explicitly defaulted functions have no direct + effect for SWIG wrapping as the declaration is handled much like any + other method declaration parsed by SWIG.
+Deleted functions are also designed to prevent implicit conversions + when calling the function. For example, the C++ compiler will not + compile any code which attempts to use an int as the type of the + parameter passed to f below:
++-+struct NoInt { + void f(double i); + void f(int) = delete; +}; +void memmove(void *ptr, const char *s)
--Copies all of the string data in s into the memory pointed - to by ptr. The string may contain embedded NULL bytes. This is - actually a wrapper to the standard C library memmove function, - which is declared as void memmove(void *ptr, const void *src, - size_t n). The src and length n parameters - are extracted from the language specific string s in the - underlying wrapper code.
+This is a C++ compile time check and SWIG does not make any attempt + to detect if the target language is using an int instead of a double + though, so in this case it is entirely possible to pass an int instead + of a double to f from Java, Python etc.
+7.2.23 Type long long int +
+SWIG correctly parses and uses the new long long type + already introduced in C99 some time ago.
+7.2.24 Static assertions
+SWIG correctly parses the new static_assert declarations. + This is a C++ compile time directive so there isn't anything useful + that SWIG can do with it.
++-+template <typename T> +struct Check { + static_assert(sizeof(int) <= sizeof(T), "not big enough"); +}; +One use of these functions is packing and unpacking data from - memory. Here is a short example:
+7.2.25 Allow sizeof to work on members + of classes without an explicit object
+SWIG can parse the new sizeof() on types as well as on objects. For + example:
--// SWIG interface -%module example -%include "carrays.i" -%include "cdata.i" +struct A { + int member; +}; -%array_class(int, intArray); +const int SIZE = sizeof(A::member); // does not work with C++03. Okay with C++11Python example:
+In Python:
-->>> a = intArray(10) ->>> for i in range(0,10): -... a[i] = i ->>> b = cdata(a,40) ->>> b -'\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04 -\x00\x00\x00\x05\x00\x00\x00\x06\x00\x00\x00\x07\x00\x00\x00\x08\x00\x00\x00\t' ->>> c = intArray(10) ->>> memmove(c,b) ->>> print c[4] -4 ->>> +>>> SIZE +8Since the size of data is not always known, the following macro is - also defined:
-%cdata(type [,name=type])
---Generates the following function for extracting C data for a given - type.
+7.2.26 Exception specifications and + noexcept
+C++11 added in the noexcept specification to exception + specifications to indicate that a function simply may or may not throw + an exception, without actually naming any exception. SWIG understands + these, although there isn't any useful way that this information can be + taken advantage of by target languages, so it is as good as ignored + during the wrapping process. Below are some examples of noexcept in + function declarations:
--char *cdata_name(type* ptr, int nitems) +static void noex1() noexcept; +int noex2(int) noexcept(true); +int noex3(int, bool) noexcept(false);nitems is the number of items of the given type to extract.
-Note: These functions provide direct access to memory and can - be used to overwrite data. Clearly they are unsafe.
-8.3 C String Handling
-A common problem when working with C programs is dealing with - functions that manipulate raw character data using char *. In - part, problems arise because there are different interpretations of -char *---it could be a NULL-terminated string or it could point to - binary data. Moreover, functions that manipulate raw strings may mutate - data, perform implicit memory allocations, or utilize fixed-sized - buffers.
-The problems (and perils) of using char * are well-known. - However, SWIG is not in the business of enforcing morality. The modules - in this section provide basic functionality for manipulating raw C - strings.
-8.3.1 Default string handling
-Suppose you have a C function with this prototype:
-+7.2.27 Control and query object + alignment
+An alignof operator is used mostly within C++ to return + alignment in number of bytes, but could be used to initialize a + variable as shown below. The variable's value will be available for + access by the target language as any other variable's compile time + initialised value.
+-char *foo(char *s); +const int align1 = alignof(A::member); ++The alignas specifier for variable alignment is not yet + supported. Example usage:
++++struct alignas(16) S { + int num; +}; +alignas(double) unsigned char c[sizeof(double)]; ++Use the preprocessor to work around this for now:
++++#define alignas(T) ++7.2.28 Attributes
+Attributes such as those shown below, are not yet supported and will + give a syntax error.
++++int [[attr1]] i [[attr2, attr3]]; + +[[noreturn, nothrow]] void f [[noreturn]] (); ++7.3 Standard library + changes
+7.3.1 Threading + facilities
+SWIG does not currently wrap or use any of the new threading classes + introduced (thread, mutex, locks, condition variables, task). The main + reason is that SWIG target languages offer their own threading + facilities so there is limited use for them.
+7.3.2 Tuple types
+SWIG does not provide library files for the new tuple types yet. + Variadic template support requires further work to provide substantial + tuple wrappers.
+7.3.3 Hash tables
+The new hash tables in the STL are unordered_set, +unordered_multiset, unordered_map, unordered_multimap +. These are not available in SWIG, but in principle should be easily + implemented by adapting the current STL containers.
+7.3.4 Regular expressions +
+While SWIG could provide wrappers for the new C++11 regular + expressions classes, there is little need as the target languages have + their own regular expression facilities.
+7.3.5 + General-purpose smart pointers
+SWIG provides special smart pointer handling for std::shared_ptr + in the same way it has support for boost::shared_ptr. Please + see the shared_ptr smart pointer + library section. There is no special smart pointer handling available + for std::weak_ptr and std::unique_ptr yet.
+7.3.6 + Extensible random number facility
+This feature extends and standardizes the standard library only and + does not effect the C++ language nor SWIG.
+7.3.7 Wrapper reference
+Wrapper references are similar to normal C++ references but are + copy-constructible and copy-assignable. They could conceivably be used + in public APIs. There is no special support for +std::reference_wrapper in SWIG though. Users would need to write + their own typemaps if wrapper references are being used and these would + be similar to the plain C++ reference typemaps.
++7.3.8 Polymorphous wrappers for function objects
+SWIG supports functor classes in a few languages in a very natural + way. However nothing is provided yet for the new std::function + template. SWIG will parse usage of the template like any other + template.
++-+%rename(__call__) Test::operator(); // Default renaming used for Python + +struct Test { + bool operator()(int x, int y); // function object +}; + +#include <functional> +std::function<void (int, int)> pF = Test; // function template wrapper +The default wrapping behavior for this function is to set s - to a raw char * that refers to the internal string data in the - target language. In other words, if you were using a language like Tcl, - and you wrote this,
-+Example of supported usage of the plain functor from Python is shown + below. It does not involve std::function.
+--% foo Hello +t = Test() +b = t(1,2) # invoke C++ function objectthen s would point to the representation of "Hello" inside - the Tcl interpreter. When returning a char *, SWIG assumes - that it is a NULL-terminated string and makes a copy of it. This gives - the target language its own copy of the result.
-There are obvious problems with the default behavior. First, since a - char * argument points to data inside the target language, it - is NOT safe for a function to modify this data (doing so may - corrupt the interpreter and lead to a crash). Furthermore, the default - behavior does not work well with binary data. Instead, strings are - assumed to be NULL-terminated.
-8.3.2 Passing binary data
-If you have a function that expects binary data,
+7.3.9 Type + traits for metaprogramming
+The type_traits functions to support C++ metaprogramming is useful at + compile time and is aimed specifically at C++ development:
--size_t parity(char *str, size_t len, size_t initial); +#include <type_traits> + +// First way of operating. +template< bool B > struct algorithm { + template< class T1, class T2 > static int do_it(T1 &, T2 &) { /*...*/ return 1; } +}; + +// Second way of operating. +template<> struct algorithm<true> { + template< class T1, class T2 > static int do_it(T1, T2) { /*...*/ return 2; } +}; + +// Instantiating 'elaborate' will automatically instantiate the correct way to operate, depending on the types used. +template< class T1, class T2 > int elaborate(T1 A, T2 B) { + // Use the second way only if 'T1' is an integer and if 'T2' is a floating point, + // otherwise use the first way. + return algorithm< std::is_integral<T1>::value && std::is_floating_point<T2>::value >::do_it(A, B); +}you can wrap the parameters (char *str, size_t len) as a - single argument using a typemap. Just do this:
+SWIG correctly parses the template specialization, template types + etc. However, metaprogramming and the additional support in the + type_traits header is really for compile time and is not much use at + runtime for the target languages. For example, as SWIG requires + explicit instantiation of templates via %template, there isn't + much that std::is_integral<int> is going to provide by itself. + However, template functions using such metaprogramming techniques might + be useful to wrap. For example, the following instantiations could be + made:
--%apply (char *STRING, size_t LENGTH) { (char *str, size_t len) }; -... -size_t parity(char *str, size_t len, size_t initial); +%template(Elaborate) elaborate<int, int>; +%template(Elaborate) elaborate<int, double>;Now, in the target language, you can use binary string data like - this:
-+Then the appropriate algorithm can be called for the subset of types + given by the above %template instantiations from a target + language, such as Python:
+-->>> s = "H\x00\x15eg\x09\x20" ->>> parity(s,0) +>>> Elaborate(0, 0) +1 +>>> Elaborate(0, 0.0) +2In the wrapper function, the passed string will be expanded to a - pointer and length parameter. The (char *STRING, int LENGTH) - multi-argument typemap is also available in addition to (char - *STRING, size_t LENGTH).
-8.3.3 Using %newobject to release memory
-If you have a function that allocates memory like this,
++7.3.10 Uniform method for computing return type of function objects
+The new std::result_of class introduced in the <functional> + header provides a generic way to obtain the return type of a function + type via std::result_of::type. There isn't any library + interface file to support this type. With a bit of work, SWIG will + deduce the return type of functions when used in std::result_of + using the approach shown below. The technique basically forward + declares the std::result_of template class, then partially + specializes it for the function types of interest. SWIG will use the + partial specialization and hence correctly use the +std::result_of::type provided in the partial specialization.
--char *foo() { - char *result = (char *) malloc(...); - ... - return result; +%inline %{ +#include <functional> +typedef double(*fn_ptr)(double); +%} + +namespace std { + // Forward declaration of result_of + template<typename Func> struct result_of; + // Add in a partial specialization of result_of + template<> struct result_of< fn_ptr(double) > { + typedef double type; + }; +} + +%template() std::result_of< fn_ptr(double) >; + +%inline %{ + +double square(double x) { + return (x * x); +} + +template<class Fun, class Arg> +typename std::result_of<Fun(Arg)>::type test_result_impl(Fun fun, Arg arg) { + return fun(arg); } +%} + +%template(test_result) test_result_impl< fn_ptr, double >; +%constant double (*SQUARE)(double) = square;then the SWIG generated wrappers will have a memory leak--the - returned data will be copied into a string object and the old contents - ignored.
-To fix the memory leak, use the %newobject directive.
-+Note the first use of %template which SWIG requires to + instantiate the template. The empty template instantiation suffices as + no proxy class is required for std::result_of<Fun(Arg)>::type + as this type is really just a double. The second %template + instantiates the template function which is being wrapped for use as a + callback. The %constant can then be used for any callback + function as described in Pointers to functions and + callbacks.
+Example usage from Python should give the not too surprising result:
+--%newobject foo; -... -char *foo(); +>>> test_result(SQUARE, 5.0) +25.0This will release the result if the appropriate target language - support is available. SWIG provides the appropriate "newfree" typemap - for char * so that the memory is released, however, you may - need to provide your own "newfree" typemap for other types. See -Object ownership and %newobject for more details.
-8.3.4 cstring.i
-The cstring.i library file provides a collection of macros - for dealing with functions that either mutate string arguments or which - try to output string data through their arguments. An example of such a - function might be this rather questionable implementation:
---void get_path(char *s) { - // Potential buffer overflow---uh, oh. - sprintf(s,"%s/%s", base_directory, sub_directory); -} -... -// Somewhere else in the C program -{ - char path[1024]; - ... - get_path(path); - ... -} -+Phew, that is a lot of hard work to get a callback working. You + could just go with the more attractive option of just using double + as the return type in the function declaration instead of result_of +!
+
+8 Preprocessing
+ + ++-(Off topic rant: If your program really has functions like this, you - would be well-advised to replace them with safer alternatives involving - bounds checking).
-The macros defined in this module all expand to various combinations - of typemaps. Therefore, the same pattern matching rules and ideas - apply.
-%cstring_bounded_output(parm, maxsize)
--Turns parameter parm into an output value. The - output string is assumed to be NULL-terminated and smaller than -maxsize characters. Here is an example:
+ +SWIG includes its own enhanced version of the C preprocessor. The + preprocessor supports the standard preprocessor directives and macro + expansion rules. However, a number of modifications and enhancements + have been made. This chapter describes some of these modifications.
+8.1 File inclusion
+To include another file into a SWIG interface, use the %include + directive like this:
--%cstring_bounded_output(char *path, 1024); -... -void get_path(char *path); +%include "pointer.i"In the target language:
-+-Unlike, #include, %include includes each file once + (and will not reload the file on subsequent %include + declarations). Therefore, it is not necessary to use include-guards in + SWIG interfaces.
+By default, the #include is ignored unless you run SWIG + with the -includeall option. The reason for ignoring + traditional includes is that you often don't want SWIG to try and wrap + everything included in standard header system headers and auxiliary + files.
+8.2 File imports
+SWIG provides another file inclusion directive with the %import + directive. For example:
+-->>> get_path() -/home/beazley/packages/Foo/Bar ->>> +%import "foo.i"Internally, the wrapper function allocates a small buffer (on the - stack) of the requested size and passes it as the pointer value. Data - stored in the buffer is then returned as a function return value. If - the function already returns a value, then the return value and the - output string are returned together (multiple return values). If - more than maxsize bytes are written, your program - will crash with a buffer overflow!
-%cstring_chunk_output(parm, chunksize)
--Turns parameter parm into an output value. The - output string is always chunksize and may contain - binary data. Here is an example:
+The purpose of %import is to collect certain information + from another SWIG interface file or a header file without actually + generating any wrapper code. Such information generally includes type + declarations (e.g., typedef) as well as C++ classes that might + be used as base-classes for class declarations in the interface. The + use of %import is also important when SWIG is used to generate + extensions as a collection of related modules. This is an advanced + topic and is described in later in the Working with + Modules chapter.
+The -importall directive tells SWIG to follow all +#include statements as imports. This might be useful if you want to + extract type definitions from system header files without generating + any wrappers.
+8.3 Conditional + Compilation
+SWIG fully supports the use of #if, #ifdef, +#ifndef, #else, #endif to conditionally include + parts of an interface. The following symbols are predefined by SWIG + when it is parsing the interface:
--%cstring_chunk_output(char *packet, PACKETSIZE); -... -void get_packet(char *packet); +SWIG Always defined when SWIG is processing a file +SWIGIMPORTED Defined when SWIG is importing a file with %import +SWIG_VERSION Hexadecimal (binary-coded decimal) number containing SWIG version, + such as 0x010311 (corresponding to SWIG-1.3.11). + +SWIGALLEGROCL Defined when using Allegro CL +SWIGCFFI Defined when using CFFI +SWIGCHICKEN Defined when using CHICKEN +SWIGCLISP Defined when using CLISP +SWIGCSHARP Defined when using C# +SWIGGUILE Defined when using Guile +SWIGJAVA Defined when using Java +SWIGJAVASCRIPT Defined when using Javascript +SWIG_JAVASCRIPT_JSC Defined when using Javascript for JavascriptCore +SWIG_JAVASCRIPT_V8 Defined when using Javascript for v8 or node.js +SWIGLUA Defined when using Lua +SWIGMODULA3 Defined when using Modula-3 +SWIGMZSCHEME Defined when using Mzscheme +SWIGOCAML Defined when using Ocaml +SWIGOCTAVE Defined when using Octave +SWIGPERL Defined when using Perl +SWIGPHP Defined when using PHP +SWIGPIKE Defined when using Pike +SWIGPYTHON Defined when using Python +SWIGR Defined when using R +SWIGRUBY Defined when using Ruby +SWIGSCILAB Defined when using Scilab +SWIGSEXP Defined when using S-expressions +SWIGTCL Defined when using Tcl +SWIGXML Defined when using XMLIn the target language:
-+-In addition, SWIG defines the following set of standard C/C++ + macros:
+-->>> get_packet() -'\xa9Y:\xf6\xd7\xe1\x87\xdbH;y\x97\x7f\xd3\x99\x14V\xec\x06\xea\xa2\x88' ->>> +__LINE__ Current line number +__FILE__ Current file name +__STDC__ Defined to indicate ANSI C +__cplusplus Defined when -c++ option usedThis macro is essentially identical to %cstring_bounded_output -. The only difference is that the result is always chunksize - characters. Furthermore, the result can contain binary data. If - more than maxsize bytes are written, your program - will crash with a buffer overflow!
-%cstring_bounded_mutable(parm, maxsize)
--Turns parameter parm into a mutable string - argument. The input string is assumed to be NULL-terminated and smaller - than maxsize characters. The output string is also - assumed to be NULL-terminated and less than maxsize - characters.
+Interface files can look at these symbols as necessary to change the + way in which an interface is generated or to mix SWIG directives with C + code. These symbols are also defined within the C code generated by + SWIG (except for the symbol `SWIG' which is only defined + within the SWIG compiler).
+8.4 Macro Expansion
+Traditional preprocessor macros can be used in SWIG interfaces. Be + aware that the #define statement is also used to try and + detect constants. Therefore, if you have something like this in your + file,
--%cstring_bounded_mutable(char *ustr, 1024); +#ifndef _FOO_H 1 +#define _FOO_H 1 ... -void make_upper(char *ustr); +#endifIn the target language:
-+-you may get some extra constants such as _FOO_H showing up + in the scripting interface.
+More complex macros can be defined in the standard way. For example:
+-->>> make_upper("hello world") -'HELLO WORLD' ->>> +#define EXTERN extern +#ifdef __STDC__ +#define _ANSI(args) (args) +#else +#define _ANSI(args) () +#endifInternally, this macro is almost exactly the same as -%cstring_bounded_output. The only difference is that the parameter - accepts an input value that is used to initialize the internal buffer. - It is important to emphasize that this function does not mutate the - string value passed---instead it makes a copy of the input value, - mutates it, and returns it as a result. If more than maxsize - bytes are written, your program will crash with a buffer overflow! -
-%cstring_mutable(parm [, expansion])
--Turns parameter parm into a mutable string - argument. The input string is assumed to be NULL-terminated. An - optional parameter expansion specifies the number of - extra characters by which the string might grow when it is modified. - The output string is assumed to be NULL-terminated and less than the - size of the input string plus any expansion characters.
+The following operators can appear in macro definitions:
++
+- #x +
+
Converts macro argument x to a string surrounded by double + quotes ("x").- x ## y +
+
Concatenates x and y together to form xy.- `x` +
+
If x is a string surrounded by double quotes, do nothing. + Otherwise, turn into a string like #x. This is a non-standard + SWIG extension.8.5 SWIG Macros
+SWIG provides an enhanced macro capability with the %define + and %enddef directives. For example:
--%cstring_mutable(char *ustr); -... -void make_upper(char *ustr); +%define ARRAYHELPER(type,name) +%inline %{ +type *new_ ## name (int nitems) { + return (type *) malloc(sizeof(type)*nitems); +} +void delete_ ## name(type *t) { + free(t); +} +type name ## _get(type *t, int index) { + return t[index]; +} +void name ## _set(type *t, int index, type val) { + t[index] = val; +} +%} +%enddef -%cstring_mutable(char *hstr, HEADER_SIZE); -... -void attach_header(char *hstr); +ARRAYHELPER(int, IntArray) +ARRAYHELPER(double, DoubleArray)In the target language:
-+-The primary purpose of %define is to define large macros of + code. Unlike normal C preprocessor macros, it is not necessary to + terminate each line with a continuation character (\)--the macro + definition extends to the first occurrence of %enddef. + Furthermore, when such macros are expanded, they are reparsed through + the C preprocessor. Thus, SWIG macros can contain all other + preprocessor directives except for nested %define statements.
+The SWIG macro capability is a very quick and easy way to generate + large amounts of code. In fact, many of SWIG's advanced features and + libraries are built using this mechanism (such as C++ template + support).
+8.6 C99 and GNU Extensions
+SWIG-1.3.12 and newer releases support variadic preprocessor macros. + For example:
+-->>> make_upper("hello world") -'HELLO WORLD' ->>> attach_header("Hello world") -'header: Hello world' ->>> +#define DEBUGF(fmt,...) fprintf(stderr,fmt,__VA_ARGS__)This macro differs from %cstring_bounded_mutable() in that - a buffer is dynamically allocated (on the heap using malloc/new -). This buffer is always large enough to store a copy of the input value - plus any expansion bytes that might have been requested. It is - important to emphasize that this function does not directly mutate the - string value passed---instead it makes a copy of the input value, - mutates it, and returns it as a result. If the function expands the - result by more than expansion extra bytes, then the - program will crash with a buffer overflow!
-%cstring_output_maxsize(parm, maxparm)
--This macro is used to handle bounded character output functions - where both a char * and a maximum length parameter are - provided. As input, a user simply supplies the maximum length. The - return value is assumed to be a NULL-terminated string.
+When used, any extra arguments to ... are placed into the + special variable __VA_ARGS__. This also works with special + SWIG macros defined using %define.
+SWIG allows a variable number of arguments to be empty. However, + this often results in an extra comma (,) and syntax error in the + resulting expansion. For example:
--%cstring_output_maxsize(char *path, int maxpath); -... -void get_path(char *path, int maxpath); +DEBUGF("hello"); --> fprintf(stderr,"hello",);In the target language:
-+-To get rid of the extra comma, use ## like this:
+-->>> get_path(1024) -'/home/beazley/Packages/Foo/Bar' ->>> +#define DEBUGF(fmt,...) fprintf(stderr,fmt, ##__VA_ARGS__)This macro provides a safer alternative for functions that need to - write string data into a buffer. User supplied buffer size is used to - dynamically allocate memory on heap. Results are placed into that - buffer and returned as a string object.
-%cstring_output_withsize(parm, maxparm)
--This macro is used to handle bounded character output functions - where both a char * and a pointer int * are passed. - Initially, the int * parameter points to a value containing - the maximum size. On return, this value is assumed to contain the - actual number of bytes. As input, a user simply supplies the maximum - length. The output value is a string that may contain binary data.
+SWIG also supports GNU-style variadic macros. For example:
--%cstring_output_withsize(char *data, int *maxdata); -... -void get_data(char *data, int *maxdata); +#define DEBUGF(fmt, args...) fprintf(stdout,fmt,args)In the target language:
-+-Comment: It's not entirely clear how variadic macros might be + useful to interface building. However, they are used internally to + implement a number of SWIG directives and are provided to make SWIG + more compatible with C99 code.
+8.7 Preprocessing and delimiters +
+The preprocessor handles { }, " " and %{ %} delimiters differently.
+8.7.1 Preprocessing and %{ ... %} & " ... + " delimiters
+The SWIG preprocessor does not process any text enclosed in a code + block %{ ... %}. Therefore, if you write code like this,
+-->>> get_data(1024) -'x627388912' ->>> get_data(1024) -'xyzzy' ->>> +%{ +#ifdef NEED_BLAH +int blah() { + ... +} +#endif +%}This macro is a somewhat more powerful version of -%cstring_output_chunk(). Memory is dynamically allocated and can be - arbitrary large. Furthermore, a function can control how much data is - actually returned by changing the value of the maxparm - argument.
-%cstring_output_allocate(parm, release)
--+This macro is used to return strings that are allocated within the - program and returned in a parameter of type char **. For - example:
+the contents of the %{ ... %} block are copied without + modification to the output (including all preprocessor directives).
+8.7.2 Preprocessing and { ... } + delimiters
+SWIG always runs the preprocessor on text appearing inside { ... + }. However, sometimes it is desirable to make a preprocessor + directive pass through to the output file. For example:
--void foo(char **s) { - *s = (char *) malloc(64); - sprintf(*s, "Hello world\n"); +%extend Foo { + void bar() { + #ifdef DEBUG + printf("I'm in bar\n"); + #endif + } }The returned string is assumed to be NULL-terminated. -release specifies how the allocated memory is to be released - (if applicable). Here is an example:
+By default, SWIG will interpret the #ifdef DEBUG statement. + However, if you really wanted that code to actually go into the wrapper + file, prefix the preprocessor directives with % like this:
--%cstring_output_allocate(char **s, free(*$1)); -... -void foo(char **s); +%extend Foo { + void bar() { + %#ifdef DEBUG + printf("I'm in bar\n"); + %#endif + } +}In the target language:
-+-SWIG will strip the extra % and leave the preprocessor + directive in the code.
+8.8 Preprocessor and + Typemaps
+Typemaps support a special attribute called +noblock where the { ... } delimiters can be used, but the + delimiters are not actually generated into the code. The effect is then + similar to using "" or %{ %} delimiters but the code is run + through the preprocessor. For example:
+->>> foo() -'Hello world\n' ->>> +#define SWIG_macro(CAST) (CAST)$input +%typemap(in) Int {$1= SWIG_macro(int);}-%cstring_output_allocate_size(parm, szparm, release)
--+This macro is used to return strings that are allocated within the - program and returned in two parameters of type char ** and -int *. For example:
+might generate
--void foo(char **s, int *sz) { - *s = (char *) malloc(64); - *sz = 64; - // Write some binary data - ... -} + { + arg1=(int)jarg1; + }The returned string may contain binary data. release - specifies how the allocated memory is to be released (if applicable). - Here is an example:
+whereas
--%cstring_output_allocate_size(char **s, int *slen, free(*$1)); -... -void foo(char **s, int *slen); +#define SWIG_macro(CAST) (CAST)$input +%typemap(in,noblock=1) Int {$1= SWIG_macro(int);}In the target language:
-+-might generate
+-->>> foo() -'\xa9Y:\xf6\xd7\xe1\x87\xdbH;y\x97\x7f\xd3\x99\x14V\xec\x06\xea\xa2\x88' ->>> + arg1=(int)jarg1;This is the safest and most reliable way to return binary string - data in SWIG. If you have functions that conform to another prototype, - you might consider wrapping them with a helper function. For example, - if you had this:
+and
--char *get_data(int *len); +#define SWIG_macro(CAST) (CAST)$input +%typemap(in) Int %{$1=SWIG_macro(int);%}You could wrap it with a function like this:
+would generate
-void my_get_data(char **result, int *len) { - *result = get_data(len); -} + arg1=SWIG_macro(int);-Comments:
--
-- Support for the cstring.i module depends on the target - language. Not all SWIG modules currently support this library.
-- Reliable handling of raw C strings is a delicate topic. There are - many ways to accomplish this in SWIG. This library provides support for - a few common techniques.
-- If used in C++, this library uses new and delete [] - for memory allocation. If using ANSI C, the library uses malloc() - and free().
-- Rather than manipulating char * directly, you might - consider using a special string structure or class instead.
-8.4 STL/C++ Library
-The library modules in this section provide access to parts of the - standard C++ library including the STL. SWIG support for the STL is an - ongoing effort. Support is quite comprehensive for some language - modules but some of the lesser used modules do not have quite as much - library code written.
-The following table shows which C++ classes are supported and the - equivalent SWIG interface library file for the C++ library.
--
-- C++ class C++ Library file -SWIG Interface library file - std::deque deque std_deque.i - std::list list std_list.i - std::map map std_map.i - std::pair utility std_pair.i - std::set set std_set.i - std::string string std_string.i - std::vector vector std_vector.i - std::shared_ptr shared_ptr std_shared_ptr.i The list is by no means complete; some language modules support a - subset of the above and some support additional STL classes. Please - look for the library files in the appropriate language library - directory.
-8.4.1 std::string
-The std_string.i library provides typemaps for converting - C++ std::string objects to and from strings in the target - scripting language. For example:
+8.9 Viewing preprocessor output
+Like many compilers, SWIG supports a -E command line option + to display the output from the preprocessor. When the -E + switch is used, SWIG will not generate any wrappers. Instead the + results after the preprocessor has run are displayed. This might be + useful as an aid to debugging and viewing the results of macro + expansions.
+8.10 The #error and #warning + directives
+SWIG supports the commonly used #warning and #error + preprocessor directives. The #warning directive will cause + SWIG to issue a warning then continue processing. The #error + directive will cause SWIG to exit with a fatal error. Example usage:
--%module example -%include "std_string.i" - -std::string foo(); -void bar(const std::string &x); +#error "This is a fatal error message" +#warning "This is a warning message"In the target language:
-+The #error behaviour can be made to work like #warning + if the -cpperraswarn commandline option is used. + Alternatively, the #pragma directive can be used to the same + effect, for example:
+-x = foo(); # Returns a string object -bar("Hello World"); # Pass string as std::string + /* Modified behaviour: #error does not cause SWIG to exit with error */ + #pragma SWIG cpperraswarn=1 + /* Normal behaviour: #error does cause SWIG to exit with error */ + #pragma SWIG cpperraswarn=0+
+9 SWIG library
+ + ++-+
- The %include directive and library search + path
+- C Arrays and Pointers +
++
+- cpointer.i
+- carrays.i
+- cmalloc.i
+- cdata.i
+- C String Handling + +
+- STL/C++ Library + +
+- Utility Libraries +
++
+- exception.i
+A common problem that people encounter is that of classes/structures - containing a std::string. This can be overcome by defining a - typemap. For example:
+ +To help build extension modules, SWIG is packaged with a library of + support files that you can include in your own interfaces. These files + often define new SWIG directives or provide utility functions that can + be used to access parts of the standard C and C++ libraries. This + chapter provides a reference to the current set of supported library + files.
+Compatibility note: Older versions of SWIG included a number + of library files for manipulating pointers, arrays, and other + structures. Most these files are now deprecated and have been removed + from the distribution. Alternative libraries provide similar + functionality. Please read this chapter carefully if you used the old + libraries.
+9.1 The %include directive and library search + path
+Library files are included using the %include directive. + When searching for files, directories are searched in the following + order:
++
+- The current directory
+- Directories specified with the -I command line option
+- ./swig_lib
+- SWIG library install location as reported by swig -swiglib, + for example /usr/local/share/swig/1.3.30
+- On Windows, a directory Lib relative to the location of +swig.exe is also searched.
+Within directories mentioned in points 3-5, SWIG first looks for a + subdirectory corresponding to a target language (e.g., python, + tcl, etc.). If found, SWIG will search the language specific + directory first. This allows for language-specific implementations of + library files.
+You can ignore the installed SWIG library by setting the +SWIG_LIB environment variable. Set the environment variable to hold + an alternative library directory.
+The directories that are searched are displayed when using +-verbose commandline option.
+9.2 C Arrays and Pointers
+This section describes library modules for manipulating low-level C + arrays and pointers. The primary use of these modules is in supporting + C declarations that manipulate bare pointers such as int *, +double *, or void *. The modules can be used to allocate + memory, manufacture pointers, dereference memory, and wrap pointers as + class-like objects. Since these functions provide direct access to + memory, their use is potentially unsafe and you should exercise + caution.
+9.2.1 cpointer.i
+The cpointer.i module defines macros that can be used to + used to generate wrappers around simple C pointers. The primary use of + this module is in generating pointers to primitive datatypes such as +int and double.
+%pointer_functions(type,name)
+++Generates a collection of four functions for manipulating a pointer +type *:
+type *new_name()
+++Creates a new object of type type and returns a pointer to + it. In C, the object is created using calloc(). In C++, +new is used.
+type *copy_name(type value)
+++Creates a new object of type type and returns a pointer to + it. An initial value is set by copying it from value. In C, + the object is created using calloc(). In C++, new is + used.
+type *delete_name(type *obj)
+++Deletes an object type type.
+void name_assign(type *obj, type value)
+++Assigns *obj = value.
+type name_value(type *obj)
+++Returns the value of *obj.
+When using this macro, type may be any type and name + must be a legal identifier in the target language. name should + not correspond to any other name used in the interface file.
+Here is a simple example of using %pointer_functions():
-%module example -%include "std_string.i" +%include "cpointer.i" -%apply const std::string& {std::string* foo}; +/* Create some functions for working with "int *" */ +%pointer_functions(int, intp); -struct my_struct -{ - std::string foo; -}; +/* A function that uses an "int *" */ +void add(int x, int y, int *result);In the target language:
+Now, in Python:
-x = my_struct(); -x.foo="Hello World"; # assign with string -print x.foo; # print as string +>>> import example +>>> c = example.new_intp() # Create an "int" for storing result +>>> example.add(3,4,c) # Call function +>>> example.intp_value(c) # Dereference +7 +>>> example.delete_intp(c) # Delete ++%pointer_class(type,name)
+++Wraps a pointer of type * inside a class-based interface. + This interface is as follows:
++-+struct name { + name(); // Create pointer object + ~name(); // Delete pointer object + void assign(type value); // Assign value + type value(); // Get value + type *cast(); // Cast the pointer to original type + static name *frompointer(type *); // Create class wrapper from existing + // pointer +};This module only supports types std::string and const - std::string &. Pointers and non-const references are left - unmodified and returned as SWIG pointers.
-This library file is fully aware of C++ namespaces. If you export -std::string or rename it with a typedef, make sure you include - those declarations in your interface. For example:
+When using this macro, type is restricted to a simple type + name like int, float, or Foo. Pointers and + other complicated types are not allowed. name must be a valid + identifier not already in use. When a pointer is wrapped as a class, + the "class" may be transparently passed to any function that expects + the pointer.
+If the target language does not support proxy classes, the use of + this macro will produce the example same functions as +%pointer_functions() macro.
+It should be noted that the class interface does introduce a new + object or wrap a pointer inside a special structure. Instead, the raw + pointer is used directly.
+Here is the same example using a class instead:
-%module example -%include "std_string.i" +%include "cpointer.i" -using namespace std; -typedef std::string String; -... -void foo(string s, const String &t); // std_string typemaps still applied +/* Wrap a class interface around an "int *" */ +%pointer_class(int, intp); + +/* A function that uses an "int *" */ +void add(int x, int y, int *result);8.4.2 std::vector
-The std_vector.i library provides support for the C++ -std::vector class in the STL. Using this library involves the use - of the %template directive. All you need to do is to - instantiate different versions of vector for the types that - you want to use. For example:
+Now, in Python (using proxy classes)
++++>>> import example +>>> c = example.intp() # Create an "int" for storing result +>>> example.add(3,4,c) # Call function +>>> c.value() # Dereference +7 ++Of the two macros, %pointer_class is probably the most + convenient when working with simple pointers. This is because the + pointers are access like objects and they can be easily garbage + collected (destruction of the pointer object destroys the underlying + object).
+%pointer_cast(type1, type2, name)
+++Creates a casting function that converts type1 to type2 +. The name of the function is name. For example:
--%module example -%include "std_vector.i" - -namespace std { - %template(vectori) vector<int>; - %template(vectord) vector<double>; -}; +%pointer_cast(int *, unsigned int *, int_to_uint);When a template vector<X> is instantiated a number of - things happen:
--
-- A class that exposes the C++ API is created in the target language . - This can be used to create objects, invoke methods, etc. This class is - currently a subset of the real STL vector class.
-- Input typemaps are defined for vector<X>, const - vector<X> &, and const vector<X> *. For each of these, a - pointer vector<X> * may be passed or a native list object in - the target language.
-- An output typemap is defined for vector<X>. In this case, - the values in the vector are expanded into a list object in the target - language.
-- For all other variations of the type, the wrappers expect to receive - a vector<X> * object in the usual manner.
-- An exception handler for std::out_of_range is defined.
-- Optionally, special methods for indexing, item retrieval, slicing, - and element assignment may be defined. This depends on the target - language.
-To illustrate the use of this library, consider the following - functions:
+In this example, the function int_to_uint() would be used + to cast types in the target language.
+Note: None of these macros can be used to safely work with + strings (char * or char **).
+Note: When working with simple pointers, typemaps can often + be used to provide more seamless operation.
+9.2.2 carrays.i
+This module defines macros that assist in wrapping ordinary C + pointers as arrays. The module does not provide any safety or an extra + layer of wrapping--it merely provides functionality for creating, + destroying, and modifying the contents of raw C array data.
+%array_functions(type,name)
+++Creates four functions.
+type *new_name(int nelements)
+++Creates a new array of objects of type type. In C, the + array is allocated using calloc(). In C++, new [] is + used.
+type *delete_name(type *ary)
+++Deletes an array. In C, free() is used. In C++, delete + [] is used.
+type name_getitem(type *ary, int index)
+++Returns the value ary[index].
+void name_setitem(type *ary, int index, type value)
+++Assigns ary[index] = value.
+When using this macro, type may be any type and name + must be a legal identifier in the target language. name should + not correspond to any other name used in the interface file.
+Here is an example of %array_functions(). Suppose you had a + function like this:
--/* File : example.h */ - -#include <vector> -#include <algorithm> -#include <functional> -#include <numeric> - -double average(std::vector<int> v) { - return std::accumulate(v.begin(),v.end(),0.0)/v.size(); -} - -std::vector<double> half(const std::vector<double>& v) { - std::vector<double> w(v); - for (unsigned int i=0; i<w.size(); i++) - w[i] /= 2.0; - return w; -} - -void halve_in_place(std::vector<double>& v) { - std::transform(v.begin(),v.end(),v.begin(), - std::bind2nd(std::divides<double>(),2.0)); +void print_array(double x[10]) { + int i; + for (i = 0; i < 10; i++) { + printf("[%d] = %g\n", i, x[i]); + } }To wrap with SWIG, you might write the following:
+To wrap it, you might write this:
-%module example -%{ -#include "example.h" -%} -%include "std_vector.i" -// Instantiate templates used by example -namespace std { - %template(IntVector) vector<int>; - %template(DoubleVector) vector<double>; -} +%include "carrays.i" +%array_functions(double, doubleArray); -// Include the header file with above prototypes -%include "example.h" +void print_array(double x[10]);Now, to illustrate the behavior in the scripting interpreter, - consider this Python example:
-++Now, in a scripting language, you might write this:
+->>> from example import * ->>> iv = IntVector(4) # Create an vector<int> ->>> for i in range(0,4): -... iv[i] = i ->>> average(iv) # Call method -1.5 ->>> average([0,1,2,3]) # Call with list -1.5 ->>> half([1,2,3]) # Half a list -(0.5,1.0,1.5) ->>> halve_in_place([1,2,3]) # Oops -Traceback (most recent call last): - File "<stdin>", line 1, in ? -TypeError: Type error. Expected _p_std__vectorTdouble_t ->>> dv = DoubleVector(4) ->>> for i in range(0,4): -... dv[i] = i ->>> halve_in_place(dv) # Ok ->>> for i in dv: -... print i -... -0.0 -0.5 -1.0 -1.5 ->>> dv[20] = 4.5 -Traceback (most recent call last): - File "<stdin>", line 1, in ? - File "example.py", line 81, in __setitem__ - def __setitem__(*args): return apply(examplec.DoubleVector___setitem__,args) -IndexError: vector index out of range ->>> +a = new_doubleArray(10) # Create an array +for i in range(0,10): + doubleArray_setitem(a,i,2*i) # Set a value +print_array(a) # Pass to C +delete_doubleArray(a) # Destroy array ++%array_class(type,name)
++Wraps a pointer of type * inside a class-based interface. + This interface is as follows:
++-+struct name { + name(int nelements); // Create an array + ~name(); // Delete array + type getitem(int index); // Return item + void setitem(int index, type value); // Set item + type *cast(); // Cast to original type + static name *frompointer(type *); // Create class wrapper from + // existing pointer +};This library module is fully aware of C++ namespaces. If you use - vectors with other names, make sure you include the appropriate -using or typedef directives. For example:
+When using this macro, type is restricted to a simple type + name like int or float. Pointers and other + complicated types are not allowed. name must be a valid + identifier not already in use. When a pointer is wrapped as a class, it + can be transparently passed to any function that expects the pointer.
+When combined with proxy classes, the %array_class() macro + can be especially useful. For example:
--%include "std_vector.i" - -namespace std { - %template(IntVector) vector<int>; -} - -using namespace std; -typedef std::vector Vector; +%module example +%include "carrays.i" +%array_class(double, doubleArray); -void foo(vector<int> *x, const Vector &x); +void print_array(double x[10]);Note: This module makes use of several advanced SWIG features - including templatized typemaps and template partial specialization. If - you are trying to wrap other C++ code with templates, you might look at - the code contained in std_vector.i. Alternatively, you can - show them the code if you want to make their head explode.
-Note: This module is defined for all SWIG target languages. - However argument conversion details and the public API exposed to the - interpreter vary.
-8.4.3 STL exceptions
-Many of the STL wrapper functions add parameter checking and will - throw a language dependent error/exception should the values not be - valid. The classic example is array bounds checking. The library - wrappers are written to throw a C++ exception in the case of error. The - C++ exception in turn gets converted into an appropriate - error/exception for the target language. By and large this handling - should not need customising, however, customisation can easily be - achieved by supplying appropriate "throws" typemaps. For example:
+Allows you to do this:
--%module example -%include "std_vector.i" -%typemap(throws) std::out_of_range { - // custom exception handler -} -%template(VectInt) std::vector<int>; +import example +c = example.doubleArray(10) # Create double[10] +for i in range(0,10): + c[i] = 2*i # Assign values +example.print_array(c) # Pass to C-The custom exception handler might, for example, log the exception - then convert it into a specific error/exception for the target - language.
-When using the STL it is advisable to add in an exception handler to - catch all STL exceptions. The %exception directive can be used - by placing the following code before any other methods or libraries to - be wrapped:
+Note: These macros do not encapsulate C arrays inside a + special data structure or proxy. There is no bounds checking or safety + of any kind. If you want this, you should consider using a special + array object rather than a bare pointer.
+Note: %array_functions() and %array_class() + should not be used with types of char or char *.
+9.2.3 cmalloc.i
+This module defines macros for wrapping the low-level C memory + allocation functions malloc(), calloc(), +realloc(), and free().
+%malloc(type [,name=type])
+++Creates a wrapper around malloc() with the following + prototype:
--%include "exception.i" - -%exception { - try { - $action - } catch (const std::exception& e) { - SWIG_exception(SWIG_RuntimeError, e.what()); - } -} +type *malloc_name(int nbytes = sizeof(type));Any thrown STL exceptions will then be gracefully handled instead of - causing a crash.
-8.4.4 shared_ptr smart pointer
-Some target languages have support for handling the widely used -boost::shared_ptr smart pointer. This smart pointer is also - available as std::tr1::shared_ptr before it becomes fully - standardized as std::shared_ptr. The boost_shared_ptr.i - library provides support for boost::shared_ptr and -std_shared_ptr.i provides support for std::shared_ptr, but - if the following macro is defined as shown, it can be used for -std::tr1::shared_ptr:
+If type is void, then the size parameter +nbytes is required. The name parameter only needs to be + specified when wrapping a type that is not a valid identifier (e.g., " +int *", "double **", etc.).
+%calloc(type [,name=type])
+++Creates a wrapper around calloc() with the following + prototype:
--#define SWIG_SHARED_PTR_SUBNAMESPACE tr1 -%include <std_shared_ptr.i> +type *calloc_name(int nobj =1, int sz = sizeof(type));You can only use one of these variants of shared_ptr in your - interface file at a time. and all three variants must be used in - conjunction with the %shared_ptr(T) macro, where T is - the underlying pointer type equating to usage shared_ptr<T>. - The type T must be non-primitive. A simple example - demonstrates usage:
+If type is void, then the size parameter sz + is required.
+%realloc(type [,name=type])
++Creates a wrapper around realloc() with the following + prototype:
--%module example -%include <boost_shared_ptr.i> -%shared_ptr(IntValue) - -%inline %{ -#include <boost/shared_ptr.hpp> - -struct IntValue { - int value; - IntValue(int v) : value(v) {} -}; - -static int extractValue(const IntValue &t) { - return t.value; -} - -static int extractValueSmart(boost::shared_ptr<IntValue> t) { - return t->value; -} -%} +type *realloc_name(type *ptr, int nitems);Note that the %shared_ptr(IntValue) declaration occurs - after the inclusion of the boost_shared_ptr.i library which - provides the macro and, very importantly, before any usage or - declaration of the type, IntValue. The %shared_ptr - macro provides, a few things for handling this smart pointer, but - mostly a number of typemaps. These typemaps override the default - typemaps so that the underlying proxy class is stored and passed around - as a pointer to a shared_ptr instead of a plain pointer to the - underlying type. This approach means that any instantiation of the type - can be passed to methods taking the type by value, reference, pointer - or as a smart pointer. The interested reader might want to look at the - generated code, however, usage is simple and no different handling is - required from the target language. For example, a simple use case of - the above code from Java would be:
----IntValue iv = new IntValue(1234); -int val1 = example.extractValue(iv); -int val2 = example.extractValueSmart(iv); -System.out.println(val1 + " " + val2); -+Note: unlike the C realloc(), the wrapper generated by this + macro implicitly includes the size of the corresponding type. For + example, realloc_int(p, 100) reallocates p so that it + holds 100 integers.
This shared_ptr library works quite differently to SWIG's normal, - but somewhat limited, smart pointer - handling. The shared_ptr library does not generate extra wrappers, - just for smart pointer handling, in addition to the proxy class. The - normal proxy class including inheritance relationships is generated as - usual. The only real change introduced by the %shared_ptr - macro is that the proxy class stores a pointer to the shared_ptr - instance instead of a raw pointer to the instance. A proxy class - derived from a base which is being wrapped with shared_ptr can and - must be wrapped as a shared_ptr too. In other words all classes in - an inheritance hierarchy must all be used with the %shared_ptr - macro. For example the following code can be used with the base class - shown earlier:
+%free(type [,name=type])
+++Creates a wrapper around free() with the following + prototype:
--%shared_ptr(DerivedIntValue) -%inline %{ -struct DerivedIntValue : IntValue { - DerivedIntValue(int value) : IntValue(value) {} - ... -}; -%} +void free_name(type *ptr);-A shared_ptr of the derived class can now be passed to a method - where the base is expected in the target language, just as it can in - C++:
-+%sizeof(type [,name=type])
+++Creates the constant:
+-DerivedIntValue div = new DerivedIntValue(5678); -int val3 = example.extractValue(div); -int val4 = example.extractValueSmart(div); +%constant int sizeof_name = sizeof(type);+%allocators(type [,name=type])
++-Generates wrappers for all five of the above operations.
If the %shared_ptr macro is omitted for any class in the - inheritance hierarchy, SWIG will warn about this and the generated code - may or may not result in a C++ compilation error. For example, the - following input:
+Here is a simple example that illustrates the use of these macros:
--%include "boost_shared_ptr.i" -%shared_ptr(Parent); +// SWIG interface +%module example +%include "cmalloc.i" -%inline %{ - #include <boost/shared_ptr.hpp> - struct GrandParent { - virtual ~GrandParent() {} - }; +%malloc(int); +%free(int); - struct Parent : GrandParent { - virtual ~Parent() {} - }; +%malloc(int *, intp); +%free(int *, intp); - struct Child : Parent { - virtual ~Child() {} - }; -%} +%allocators(double);warns about the missing smart pointer information:
-+Now, in a script:
+--example.i:12: Warning 520: Base class 'GrandParent' of 'Parent' is not similarly marked as a smart pointer. -example.i:16: Warning 520: Derived class 'Child' of 'Parent' is not similarly marked as a smart pointer. +>>> from example import * +>>> a = malloc_int() +>>> a +'_000efa70_p_int' +>>> free_int(a) +>>> b = malloc_intp() +>>> b +'_000efb20_p_p_int' +>>> free_intp(b) +>>> c = calloc_double(50) +>>> c +'_000fab98_p_double' +>>> c = realloc_double(100000) +>>> free_double(c) +>>> print sizeof_double +8 +>>>Adding the missing %shared_ptr macros will fix this:
--Note: There is currently no support for %shared_ptr - and the director feature. --%include "boost_shared_ptr.i" -%shared_ptr(GrandParent); -%shared_ptr(Parent); -%shared_ptr(Child); - -... as before ... --8.5 Utility Libraries
-8.5.1 exception.i
-The exception.i library provides a language-independent - function for raising a run-time exception in the target language. This - library is largely used by the SWIG library writers. If possible, use - the error handling scheme available to your target language as there is - greater flexibility in what errors/exceptions can be thrown.
-SWIG_exception(int code, const char *message)
+9.2.4 cdata.i
+The cdata.i module defines functions for converting raw C + data to and from strings in the target language. The primary + applications of this module would be packing/unpacking of binary data + structures---for instance, if you needed to extract data from a buffer. + The target language must support strings with embedded binary data in + order for this to work.
+const char *cdata(void *ptr, size_t nbytes)
--Raises an exception in the target language. code is one of - the following symbolic constants:
----SWIG_MemoryError -SWIG_IOError -SWIG_RuntimeError -SWIG_IndexError -SWIG_TypeError -SWIG_DivisionByZero -SWIG_OverflowError -SWIG_SyntaxError -SWIG_ValueError -SWIG_SystemError --message is a string indicating more information about the - problem.
-The primary use of this module is in writing language-independent - exception handlers. For example:
---%include "exception.i" -%exception std::vector::getitem { - try { - $action - } catch (std::out_of_range& e) { - SWIG_exception(SWIG_IndexError,const_cast<char*>(e.what())); - } -} --
-9 Argument Handling
- - -- +- -Converts nbytes of data at ptr into a string. +ptr can be any pointer.
In Chapter 3, SWIG's treatment of basic datatypes and pointers was - described. In particular, primitive types such as int and -double are mapped to corresponding types in the target language. - For everything else, pointers are used to refer to structures, classes, - arrays, and other user-defined datatypes. However, in certain - applications it is desirable to change SWIG's handling of a specific - datatype. For example, you might want to return multiple values through - the arguments of a function. This chapter describes some of the - techniques for doing this.
-9.1 The typemaps.i library
-This section describes the typemaps.i library - file--commonly used to change certain properties of argument - conversion.
-9.1.1 Introduction
-Suppose you had a C function like this:
---void add(double a, double b, double *result) { - *result = a + b; -} -+void memmove(void *ptr, const char *s)
++-Copies all of the string data in s into the memory pointed + to by ptr. The string may contain embedded NULL bytes. This is + actually a wrapper to the standard C library memmove function, + which is declared as void memmove(void *ptr, const void *src, + size_t n). The src and length n parameters + are extracted from the language specific string s in the + underlying wrapper code.
From reading the source code, it is clear that the function is - storing a value in the double *result parameter. However, - since SWIG does not examine function bodies, it has no way to know that - this is the underlying behavior.
-One way to deal with this is to use the typemaps.i library - file and write interface code like this:
+One use of these functions is packing and unpacking data from + memory. Here is a short example:
--// Simple example using typemaps +// SWIG interface %module example -%include "typemaps.i" +%include "carrays.i" +%include "cdata.i" -%apply double *OUTPUT { double *result }; -%inline %{ -extern void add(double a, double b, double *result); -%} +%array_class(int, intArray);The %apply directive tells SWIG that you are going to apply - a special type handling rule to a type. The "double *OUTPUT" - specification is the name of a rule that defines how to return an - output value from an argument of type double *. This rule gets - applied to all of the datatypes listed in curly braces-- in this case " -double *result".
-When the resulting module is created, you can now use the function - like this (shown for Python):
+Python example:
-->>> a = add(3,4) ->>> print a -7 +>>> a = intArray(10) +>>> for i in range(0,10): +... a[i] = i +>>> b = cdata(a,40) +>>> b +'\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04 +\x00\x00\x00\x05\x00\x00\x00\x06\x00\x00\x00\x07\x00\x00\x00\x08\x00\x00\x00\t' +>>> c = intArray(10) +>>> memmove(c,b) +>>> print c[4] +4 >>>In this case, you can see how the output value normally returned in - the third argument has magically been transformed into a function - return value. Clearly this makes the function much easier to use since - it is no longer necessary to manufacture a special double * - object and pass it to the function somehow.
-Once a typemap has been applied to a type, it stays in effect for - all future occurrences of the type and name. For example, you could - write the following:
+Since the size of data is not always known, the following macro is + also defined:
+%cdata(type [,name=type])
+++Generates the following function for extracting C data for a given + type.
--%module example -%include "typemaps.i" - -%apply double *OUTPUT { double *result }; - -%inline %{ -extern void add(double a, double b, double *result); -extern void sub(double a, double b, double *result); -extern void mul(double a, double b, double *result); -extern void div(double a, double b, double *result); -%} -... +char *cdata_name(type* ptr, int nitems)In this case, the double *OUTPUT rule is applied to all of - the functions that follow.
-Typemap transformations can even be extended to multiple return - values. For example, consider this code:
+nitems is the number of items of the given type to extract.
+Note: These functions provide direct access to memory and can + be used to overwrite data. Clearly they are unsafe.
+9.3 C String Handling
+A common problem when working with C programs is dealing with + functions that manipulate raw character data using char *. In + part, problems arise because there are different interpretations of +char *---it could be a NULL-terminated string or it could point to + binary data. Moreover, functions that manipulate raw strings may mutate + data, perform implicit memory allocations, or utilize fixed-sized + buffers.
+The problems (and perils) of using char * are well-known. + However, SWIG is not in the business of enforcing morality. The modules + in this section provide basic functionality for manipulating raw C + strings.
+9.3.1 Default string handling
+Suppose you have a C function with this prototype:
--%include "typemaps.i" -%apply int *OUTPUT { int *width, int *height }; - -// Returns a pair (width,height) -void getwinsize(int winid, int *width, int *height); +char *foo(char *s);In this case, the function returns multiple values, allowing it to - be used like this:
-+The default wrapping behavior for this function is to set s + to a raw char * that refers to the internal string data in the + target language. In other words, if you were using a language like Tcl, + and you wrote this,
+-->>> w,h = genwinsize(wid) ->>> print w -400 ->>> print h -300 ->>> +% foo HelloIt should also be noted that although the %apply directive - is used to associate typemap rules to datatypes, you can also use the - rule names directly in arguments. For example, you could write this:
+then s would point to the representation of "Hello" inside + the Tcl interpreter. When returning a char *, SWIG assumes + that it is a NULL-terminated string and makes a copy of it. This gives + the target language its own copy of the result.
+There are obvious problems with the default behavior. First, since a + char * argument points to data inside the target language, it + is NOT safe for a function to modify this data (doing so may + corrupt the interpreter and lead to a crash). Furthermore, the default + behavior does not work well with binary data. Instead, strings are + assumed to be NULL-terminated.
+9.3.2 Passing binary data
+If you have a function that expects binary data,
--// Simple example using typemaps -%module example -%include "typemaps.i" - -%{ -extern void add(double a, double b, double *OUTPUT); -%} -extern void add(double a, double b, double *OUTPUT); +size_t parity(char *str, size_t len, size_t initial);Typemaps stay in effect until they are explicitly deleted or - redefined to something else. To clear a typemap, the %clear - directive should be used. For example:
+you can wrap the parameters (char *str, size_t len) as a + single argument using a typemap. Just do this:
--%clear double *result; // Remove all typemaps for double *result +%apply (char *STRING, size_t LENGTH) { (char *str, size_t len) }; +... +size_t parity(char *str, size_t len, size_t initial);9.1.2 Input parameters
-The following typemaps instruct SWIG that a pointer really only - holds a single input value:
+Now, in the target language, you can use binary string data like + this:
--int *INPUT -short *INPUT -long *INPUT -unsigned int *INPUT -unsigned short *INPUT -unsigned long *INPUT -double *INPUT -float *INPUT +>>> s = "H\x00\x15eg\x09\x20" +>>> parity(s,0)When used, it allows values to be passed instead of pointers. For - example, consider this function:
+In the wrapper function, the passed string will be expanded to a + pointer and length parameter. The (char *STRING, int LENGTH) + multi-argument typemap is also available in addition to (char + *STRING, size_t LENGTH).
+9.3.3 Using %newobject to release memory
+If you have a function that allocates memory like this,
--double add(double *a, double *b) { - return *a+*b; +char *foo() { + char *result = (char *) malloc(...); + ... + return result; }Now, consider this SWIG interface:
+then the SWIG generated wrappers will have a memory leak--the + returned data will be copied into a string object and the old contents + ignored.
+To fix the memory leak, use the %newobject directive.
--%module example -%include "typemaps.i" +%newobject foo; ... -%{ -extern double add(double *, double *); -%} -extern double add(double *INPUT, double *INPUT); - --When the function is used in the scripting language interpreter, it - will work like this:
----result = add(3,4) +char *foo();9.1.3 Output parameters
-The following typemap rules tell SWIG that pointer is the output - value of a function. When used, you do not need to supply the argument - when calling the function. Instead, one or more output values are - returned.
+This will release the result if the appropriate target language + support is available. SWIG provides the appropriate "newfree" typemap + for char * so that the memory is released, however, you may + need to provide your own "newfree" typemap for other types. See +Object ownership and %newobject for more details.
+9.3.4 cstring.i
+The cstring.i library file provides a collection of macros + for dealing with functions that either mutate string arguments or which + try to output string data through their arguments. An example of such a + function might be this rather questionable implementation:
--int *OUTPUT -short *OUTPUT -long *OUTPUT -unsigned int *OUTPUT -unsigned short *OUTPUT -unsigned long *OUTPUT -double *OUTPUT -float *OUTPUT - +void get_path(char *s) { + // Potential buffer overflow---uh, oh. + sprintf(s,"%s/%s", base_directory, sub_directory); +} +... +// Somewhere else in the C program +{ + char path[1024]; + ... + get_path(path); + ... +}These methods can be used as shown in an earlier example. For - example, if you have this C function :
+(Off topic rant: If your program really has functions like this, you + would be well-advised to replace them with safer alternatives involving + bounds checking).
+The macros defined in this module all expand to various combinations + of typemaps. Therefore, the same pattern matching rules and ideas + apply.
+%cstring_bounded_output(parm, maxsize)
++Turns parameter parm into an output value. The + output string is assumed to be NULL-terminated and smaller than +maxsize characters. Here is an example:
--void add(double a, double b, double *c) { - *c = a+b; -} +%cstring_bounded_output(char *path, 1024); +... +void get_path(char *path);A SWIG interface file might look like this :
-++In the target language:
+--%module example -%include "typemaps.i" -... -%inline %{ -extern void add(double a, double b, double *OUTPUT); -%} - +>>> get_path() +/home/beazley/packages/Foo/Bar +>>>In this case, only a single output value is returned, but this is - not a restriction. An arbitrary number of output values can be returned - by applying the output rules to more than one argument (as shown - previously).
-If the function also returns a value, it is returned along with the - argument. For example, if you had this:
+Internally, the wrapper function allocates a small buffer (on the + stack) of the requested size and passes it as the pointer value. Data + stored in the buffer is then returned as a function return value. If + the function already returns a value, then the return value and the + output string are returned together (multiple return values). If + more than maxsize bytes are written, your program + will crash with a buffer overflow!
+%cstring_chunk_output(parm, chunksize)
+++Turns parameter parm into an output value. The + output string is always chunksize and may contain + binary data. Here is an example:
--extern int foo(double a, double b, double *OUTPUT); +%cstring_chunk_output(char *packet, PACKETSIZE); +... +void get_packet(char *packet);The function will return two values like this:
+In the target language:
--iresult, dresult = foo(3.5, 2) +>>> get_packet() +'\xa9Y:\xf6\xd7\xe1\x87\xdbH;y\x97\x7f\xd3\x99\x14V\xec\x06\xea\xa2\x88' +>>>9.1.4 Input/Output parameters
-When a pointer serves as both an input and output value you can use - the following typemaps :
+This macro is essentially identical to %cstring_bounded_output +. The only difference is that the result is always chunksize + characters. Furthermore, the result can contain binary data. If + more than maxsize bytes are written, your program + will crash with a buffer overflow!
+%cstring_bounded_mutable(parm, maxsize)
++Turns parameter parm into a mutable string + argument. The input string is assumed to be NULL-terminated and smaller + than maxsize characters. The output string is also + assumed to be NULL-terminated and less than maxsize + characters.
--int *INOUT -short *INOUT -long *INOUT -unsigned int *INOUT -unsigned short *INOUT -unsigned long *INOUT -double *INOUT -float *INOUT - +%cstring_bounded_mutable(char *ustr, 1024); +... +void make_upper(char *ustr);A C function that uses this might be something like this:
-++In the target language:
+--void negate(double *x) { - *x = -(*x); -} - +>>> make_upper("hello world") +'HELLO WORLD' +>>>To make x function as both and input and output value, declare the - function like this in an interface file :
+Internally, this macro is almost exactly the same as +%cstring_bounded_output. The only difference is that the parameter + accepts an input value that is used to initialize the internal buffer. + It is important to emphasize that this function does not mutate the + string value passed---instead it makes a copy of the input value, + mutates it, and returns it as a result. If more than maxsize + bytes are written, your program will crash with a buffer overflow! +
+%cstring_mutable(parm [, expansion])
+++Turns parameter parm into a mutable string + argument. The input string is assumed to be NULL-terminated. An + optional parameter expansion specifies the number of + extra characters by which the string might grow when it is modified. + The output string is assumed to be NULL-terminated and less than the + size of the input string plus any expansion characters.
--%module example -%include "typemaps.i" +%cstring_mutable(char *ustr); ... -%{ -extern void negate(double *); -%} -extern void negate(double *INOUT); +void make_upper(char *ustr); +%cstring_mutable(char *hstr, HEADER_SIZE); +... +void attach_header(char *hstr);Now within a script, you can simply call the function normally :
+In the target language:
--a = negate(3); # a = -3 after calling this +>>> make_upper("hello world") +'HELLO WORLD' +>>> attach_header("Hello world") +'header: Hello world' +>>>One subtle point of the INOUT rule is that many scripting - languages enforce mutability constraints on primitive objects (meaning - that simple objects like integers and strings aren't supposed to - change). Because of this, you can't just modify the object's value in - place as the underlying C function does in this example. Therefore, the - INOUT rule returns the modified value as a new object rather - than directly overwriting the value of the original input object.
-Compatibility note : The INOUT rule used to be known - as BOTH in earlier versions of SWIG. Backwards compatibility - is preserved, but deprecated.
-9.1.5 Using different names
-As previously shown, the %apply directive can be used to - apply the INPUT, OUTPUT, and INOUT typemaps - to different argument names. For example:
+This macro differs from %cstring_bounded_mutable() in that + a buffer is dynamically allocated (on the heap using malloc/new +). This buffer is always large enough to store a copy of the input value + plus any expansion bytes that might have been requested. It is + important to emphasize that this function does not directly mutate the + string value passed---instead it makes a copy of the input value, + mutates it, and returns it as a result. If the function expands the + result by more than expansion extra bytes, then the + program will crash with a buffer overflow!
+%cstring_output_maxsize(parm, maxparm)
++This macro is used to handle bounded character output functions + where both a char * and a maximum length parameter are + provided. As input, a user simply supplies the maximum length. The + return value is assumed to be a NULL-terminated string.
--// Make double *result an output value -%apply double *OUTPUT { double *result }; - -// Make Int32 *in an input value -%apply int *INPUT { Int32 *in }; - -// Make long *x inout -%apply long *INOUT {long *x}; - +%cstring_output_maxsize(char *path, int maxpath); +... +void get_path(char *path, int maxpath);To clear a rule, the %clear directive is used:
-++In the target language:
+--%clear double *result; -%clear Int32 *in, long *x; +>>> get_path(1024) +'/home/beazley/Packages/Foo/Bar' +>>>Typemap declarations are lexically scoped so a typemap takes effect - from the point of definition to the end of the file or a matching -%clear declaration.
-9.2 Applying constraints to input values
-In addition to changing the handling of various input values, it is - also possible to use typemaps to apply constraints. For example, maybe - you want to insure that a value is positive, or that a pointer is - non-NULL. This can be accomplished including the constraints.i - library file.
-9.2.1 Simple constraint example
-The constraints library is best illustrated by the following - interface file :
+This macro provides a safer alternative for functions that need to + write string data into a buffer. User supplied buffer size is used to + dynamically allocate memory on heap. Results are placed into that + buffer and returned as a string object.
+%cstring_output_withsize(parm, maxparm)
++This macro is used to handle bounded character output functions + where both a char * and a pointer int * are passed. + Initially, the int * parameter points to a value containing + the maximum size. On return, this value is assumed to contain the + actual number of bytes. As input, a user simply supplies the maximum + length. The output value is a string that may contain binary data.
--// Interface file with constraints -%module example -%include "constraints.i" - -double exp(double x); -double log(double POSITIVE); // Allow only positive values -double sqrt(double NONNEGATIVE); // Non-negative values only -double inv(double NONZERO); // Non-zero values -void free(void *NONNULL); // Non-NULL pointers only - +%cstring_output_withsize(char *data, int *maxdata); +... +void get_data(char *data, int *maxdata);The behavior of this file is exactly as you would expect. If any of - the arguments violate the constraint condition, a scripting language - exception will be raised. As a result, it is possible to catch bad - values, prevent mysterious program crashes and so on.
-9.2.2 Constraint methods
-The following constraints are currently available
-++In the target language:
+--POSITIVE Any number > 0 (not zero) -NEGATIVE Any number < 0 (not zero) -NONNEGATIVE Any number >= 0 -NONPOSITIVE Any number <= 0 -NONZERO Nonzero number -NONNULL Non-NULL pointer (pointers only). - +>>> get_data(1024) +'x627388912' +>>> get_data(1024) +'xyzzy' +>>>9.2.3 Applying constraints to new - datatypes
-The constraints library only supports the primitive C datatypes, but - it is easy to apply it to new datatypes using %apply. For - example :
+This macro is a somewhat more powerful version of +%cstring_output_chunk(). Memory is dynamically allocated and can be + arbitrary large. Furthermore, a function can control how much data is + actually returned by changing the value of the maxparm + argument.
+%cstring_output_allocate(parm, release)
+++This macro is used to return strings that are allocated within the + program and returned in a parameter of type char **. For + example:
--// Apply a constraint to a Real variable -%apply Number POSITIVE { Real in }; - -// Apply a constraint to a pointer type -%apply Pointer NONNULL { Vector * }; - +void foo(char **s) { + *s = (char *) malloc(64); + sprintf(*s, "Hello world\n"); +}The special types of "Number" and "Pointer" can be applied to any - numeric and pointer variable type respectively. To later remove a - constraint, the %clear directive can be used :
+The returned string is assumed to be NULL-terminated. +release specifies how the allocated memory is to be released + (if applicable). Here is an example:
-%clear Real in; -%clear Vector *; +%cstring_output_allocate(char **s, free(*$1)); +... +void foo(char **s);-
-10 Typemaps
- - --- --
- Introduction - -
-- Typemap specifications - -
-- Pattern matching rules - -
-- Code generation rules - -
-- Common typemap methods - -
-- Some typemap examples - -
-- Typemaps for multiple target languages
-- Optimal code generation when returning - by value
-- Multi-argument typemaps -
-- Typemap warnings
-- Typemap fragments - -
-- The run-time type checker -
--
-- Implementation
-- Usage
-- Typemaps and overloading
-- More about %apply and %clear -
-- Passing data between typemaps
-- C++ "this" pointer
-- Where to go for more information?
-10.1 Introduction
-Chances are, you are reading this chapter for one of two reasons; - you either want to customize SWIG's behavior or you overheard someone - mumbling some incomprehensible drivel about "typemaps" and you asked - yourself "typemaps, what are those?" That said, let's start with a - short disclaimer that "typemaps" are an advanced customization feature - that provide direct access to SWIG's low-level code generator. Not only - that, they are an integral part of the SWIG C++ type system (a - non-trivial topic of its own). Typemaps are generally not a - required part of using SWIG. Therefore, you might want to re-read the - earlier chapters if you have found your way to this chapter with only a - vague idea of what SWIG already does by default.
-10.1.1 Type conversion
-One of the most important problems in wrapper code generation is the - conversion or marshalling of datatypes between programming languages. - Specifically, for every C/C++ declaration, SWIG must somehow generate - wrapper code that allows values to be passed back and forth between - languages. Since every programming language represents data - differently, this is not a simple of matter of simply linking code - together with the C linker. Instead, SWIG has to know something about - how data is represented in each language and how it can be manipulated.
-To illustrate, suppose you had a simple C function like this:
+In the target language:
+++>>> foo() +'Hello world\n' +>>> ++%cstring_output_allocate_size(parm, szparm, release)
+++This macro is used to return strings that are allocated within the + program and returned in two parameters of type char ** and +int *. For example:
--int factorial(int n); +void foo(char **s, int *sz) { + *s = (char *) malloc(64); + *sz = 64; + // Write some binary data + ... +}To access this function from Python, a pair of Python API functions - are used to convert integer values. For example:
+The returned string may contain binary data. release + specifies how the allocated memory is to be released (if applicable). + Here is an example:
--long PyInt_AsLong(PyObject *obj); /* Python --> C */ -PyObject *PyInt_FromLong(long x); /* C --> Python */ +%cstring_output_allocate_size(char **s, int *slen, free(*$1)); +... +void foo(char **s, int *slen);The first function is used to convert the input argument from a - Python integer object to C long. The second function is used - to convert a value from C back into a Python integer object.
-Inside the wrapper function, you might see these functions used like - this:
-+In the target language:
+--PyObject *wrap_factorial(PyObject *self, PyObject *args) { - int arg1; - int result; - PyObject *obj1; - PyObject *resultobj; - - if (!PyArg_ParseTuple("O:factorial", &obj1)) return NULL; - arg1 = PyInt_AsLong(obj1); - result = factorial(arg1); - resultobj = PyInt_FromLong(result); - return resultobj; -} +>>> foo() +'\xa9Y:\xf6\xd7\xe1\x87\xdbH;y\x97\x7f\xd3\x99\x14V\xec\x06\xea\xa2\x88' +>>>Every target language supported by SWIG has functions that work in a - similar manner. For example, in Perl, the following functions are used:
+This is the safest and most reliable way to return binary string + data in SWIG. If you have functions that conform to another prototype, + you might consider wrapping them with a helper function. For example, + if you had this:
--IV SvIV(SV *sv); /* Perl --> C */ -void sv_setiv(SV *sv, IV val); /* C --> Perl */ +char *get_data(int *len);In Tcl:
+You could wrap it with a function like this:
--int Tcl_GetLongFromObj(Tcl_Interp *interp, Tcl_Obj *obj, long *value); -Tcl_Obj *Tcl_NewIntObj(long value); +void my_get_data(char **result, int *len) { + *result = get_data(len); +}-The precise details are not so important. What is important is that - all of the underlying type conversion is handled by collections of - utility functions and short bits of C code like this---you simply have - to read the extension documentation for your favorite language to know - how it works (an exercise left to the reader).
-10.1.2 Typemaps
-Since type handling is so central to wrapper code generation, SWIG - allows it to be completely defined (or redefined) by the user. To do - this, a special %typemap directive is used. For example:
+Comments:
++
+- Support for the cstring.i module depends on the target + language. Not all SWIG modules currently support this library.
+- Reliable handling of raw C strings is a delicate topic. There are + many ways to accomplish this in SWIG. This library provides support for + a few common techniques.
+- If used in C++, this library uses new and delete [] + for memory allocation. If using ANSI C, the library uses malloc() + and free().
+- Rather than manipulating char * directly, you might + consider using a special string structure or class instead.
+9.4 STL/C++ Library
+The library modules in this section provide access to parts of the + standard C++ library including the STL. SWIG support for the STL is an + ongoing effort. Support is quite comprehensive for some language + modules but some of the lesser used modules do not have quite as much + library code written.
+The following table shows which C++ classes are supported and the + equivalent SWIG interface library file for the C++ library.
++
++ C++ class C++ Library file +SWIG Interface library file + std::auto_ptr memory std_auto_ptr.i + std::deque deque std_deque.i + std::list list std_list.i + std::map map std_map.i + std::pair utility std_pair.i + std::set set std_set.i + std::string string std_string.i + std::vector vector std_vector.i + std::array array (C++11) std_array.i + std::shared_ptr shared_ptr (C++11) +std_shared_ptr.i The list is by no means complete; some language modules support a + subset of the above and some support additional STL classes. Please + look for the library files in the appropriate language library + directory.
+9.4.1 std::string
+The std_string.i library provides typemaps for converting + C++ std::string objects to and from strings in the target + scripting language. For example:
--/* Convert from Python --> C */ -%typemap(in) int { - $1 = PyInt_AsLong($input); -} +%module example +%include "std_string.i" -/* Convert from C --> Python */ -%typemap(out) int { - $result = PyInt_FromLong($1); -} +std::string foo(); +void bar(const std::string &x);At first glance, this code will look a little confusing. However, - there is really not much to it. The first typemap (the "in" typemap) is - used to convert a value from the target language to C. The second - typemap (the "out" typemap) is used to convert in the other direction. - The content of each typemap is a small fragment of code that is - inserted directly into the SWIG generated wrapper functions. The code - is usually C or C++ code which will be generated into the C/C++ wrapper - functions. Note that this isn't always the case as some target language - modules allow target language code within the typemaps which gets - generated into target language specific files. Within this code, a - number of special variables prefixed with a $ are expanded. These are - really just placeholders for C/C++ variables that are generated in the - course of creating the wrapper function. In this case, $input - refers to an input object that needs to be converted to C/C++ and -$result refers to an object that is going to be returned by a - wrapper function. $1 refers to a C/C++ variable that has the - same type as specified in the typemap declaration (an int in - this example).
-A short example might make this a little more clear. If you were - wrapping a function like this:
-+In the target language:
+--int gcd(int x, int y); +x = foo(); # Returns a string object +bar("Hello World"); # Pass string as std::stringA wrapper function would look approximately like this:
+A common problem that people encounter is that of classes/structures + containing a std::string. This can be overcome by defining a + typemap. For example:
--PyObject *wrap_gcd(PyObject *self, PyObject *args) { - int arg1; - int arg2; - int result; - PyObject *obj1; - PyObject *obj2; - PyObject *resultobj; - - if (!PyArg_ParseTuple("OO:gcd", &obj1, &obj2)) return NULL; +%module example +%include "std_string.i" - /* "in" typemap, argument 1 */ - { - arg1 = PyInt_AsLong(obj1); - } - - /* "in" typemap, argument 2 */ - { - arg2 = PyInt_AsLong(obj2); - } - - result = gcd(arg1,arg2); +%apply const std::string& {std::string* foo}; - /* "out" typemap, return value */ - { - resultobj = PyInt_FromLong(result); - } - - return resultobj; -} +struct my_struct +{ + std::string foo; +};In this code, you can see how the typemap code has been inserted - into the function. You can also see how the special $ variables have - been expanded to match certain variable names inside the wrapper - function. This is really the whole idea behind typemaps--they simply - let you insert arbitrary code into different parts of the generated - wrapper functions. Because arbitrary code can be inserted, it possible - to completely change the way in which values are converted.
-10.1.3 Pattern matching
-As the name implies, the purpose of a typemap is to "map" C - datatypes to types in the target language. Once a typemap is defined - for a C datatype, it is applied to all future occurrences of that type - in the input file. For example:
+In the target language:
++++x = my_struct(); +x.foo="Hello World"; # assign with string +print x.foo; # print as string ++This module only supports types std::string and const + std::string &. Pointers and non-const references are left + unmodified and returned as SWIG pointers.
+This library file is fully aware of C++ namespaces. If you export +std::string or rename it with a typedef, make sure you include + those declarations in your interface. For example:
--/* Convert from Perl --> C */ -%typemap(in) int { - $1 = SvIV($input); -} +%module example +%include "std_string.i" +using namespace std; +typedef std::string String; ... -int factorial(int n); -int gcd(int x, int y); -int count(char *s, char *t, int max); +void foo(string s, const String &t); // std_string typemaps still appliedThe matching of typemaps to C datatypes is more than a simple - textual match. In fact, typemaps are fully built into the underlying - type system. Therefore, typemaps are unaffected by typedef, - namespaces, and other declarations that might hide the underlying type. - For example, you could have code like this:
+9.4.2 std::vector
+The std_vector.i library provides support for the C++ +std::vector class in the STL. Using this library involves the use + of the %template directive. All you need to do is to + instantiate different versions of vector for the types that + you want to use. For example:
--/* Convert from Ruby--> C */ -%typemap(in) int { - $1 = NUM2INT($input); -} -... -typedef int Integer; -namespace foo { - typedef Integer Number; -}; +%module example +%include "std_vector.i" -int foo(int x); -int bar(Integer y); -int spam(foo::Number a, foo::Number b); +namespace std { + %template(vectori) vector<int>; + %template(vectord) vector<double>; +};In this case, the typemap is still applied to the proper arguments - even though typenames don't always match the text "int". This ability - to track types is a critical part of SWIG--in fact, all of the target - language modules work merely define a set of typemaps for the basic - types. Yet, it is never necessary to write new typemaps for typenames - introduced by typedef.
-In addition to tracking typenames, typemaps may also be specialized - to match against a specific argument name. For example, you could write - a typemap like this:
+When a template vector<X> is instantiated a number of + things happen:
++
+- A class that exposes the C++ API is created in the target language . + This can be used to create objects, invoke methods, etc. This class is + currently a subset of the real STL vector class.
+- Input typemaps are defined for vector<X>, const + vector<X> &, and const vector<X> *. For each of these, a + pointer vector<X> * may be passed or a native list object in + the target language.
+- An output typemap is defined for vector<X>. In this case, + the values in the vector are expanded into a list object in the target + language.
+- For all other variations of the type, the wrappers expect to receive + a vector<X> * object in the usual manner.
+- An exception handler for std::out_of_range is defined.
+- Optionally, special methods for indexing, item retrieval, slicing, + and element assignment may be defined. This depends on the target + language.
+To illustrate the use of this library, consider the following + functions:
--%typemap(in) double nonnegative { - $1 = PyFloat_AsDouble($input); - if ($1 < 0) { - PyErr_SetString(PyExc_ValueError,"argument must be nonnegative."); - return NULL; - } +/* File : example.h */ + +#include <vector> +#include <algorithm> +#include <functional> +#include <numeric> + +double average(std::vector<int> v) { + return std::accumulate(v.begin(),v.end(),0.0)/v.size(); } -... -double sin(double x); -double cos(double x); -double sqrt(double nonnegative); +std::vector<double> half(const std::vector<double>& v) { + std::vector<double> w(v); + for (unsigned int i=0; i<w.size(); i++) + w[i] /= 2.0; + return w; +} -typedef double Real; -double log(Real nonnegative); -... +void halve_in_place(std::vector<double>& v) { + std::transform(v.begin(),v.end(),v.begin(), + std::bind2nd(std::divides<double>(),2.0)); +}For certain tasks such as input argument conversion, typemaps can be - defined for sequences of consecutive arguments. For example:
+To wrap with SWIG, you might write the following:
--%typemap(in) (char *str, int len) { - $1 = PyString_AsString($input); /* char *str */ - $2 = PyString_Size($input); /* int len */ +%module example +%{ +#include "example.h" +%} + +%include "std_vector.i" +// Instantiate templates used by example +namespace std { + %template(IntVector) vector<int>; + %template(DoubleVector) vector<double>; } -... -int count(char *str, int len, char c); + +// Include the header file with above prototypes +%include "example.h"In this case, a single input object is expanded into a pair of C - arguments. This example also provides a hint to the unusual variable - naming scheme involving $1, $2, and so forth.
-10.1.4 Reusing typemaps
-Typemaps are normally defined for specific type and argument name - patterns. However, typemaps can also be copied and reused. One way to - do this is to use assignment like this:
-+Now, to illustrate the behavior in the scripting interpreter, + consider this Python example:
+--%typemap(in) Integer = int; -%typemap(in) (char *buffer, int size) = (char *str, int len); +>>> from example import * +>>> iv = IntVector(4) # Create an vector<int> +>>> for i in range(0,4): +... iv[i] = i +>>> average(iv) # Call method +1.5 +>>> average([0,1,2,3]) # Call with list +1.5 +>>> half([1,2,3]) # Half a list +(0.5,1.0,1.5) +>>> halve_in_place([1,2,3]) # Oops +Traceback (most recent call last): + File "<stdin>", line 1, in ? +TypeError: Type error. Expected _p_std__vectorTdouble_t +>>> dv = DoubleVector(4) +>>> for i in range(0,4): +... dv[i] = i +>>> halve_in_place(dv) # Ok +>>> for i in dv: +... print i +... +0.0 +0.5 +1.0 +1.5 +>>> dv[20] = 4.5 +Traceback (most recent call last): + File "<stdin>", line 1, in ? + File "example.py", line 81, in __setitem__ + def __setitem__(*args): return apply(examplec.DoubleVector___setitem__,args) +IndexError: vector index out of range +>>>A more general form of copying is found in the %apply - directive like this:
+This library module is fully aware of C++ namespaces. If you use + vectors with other names, make sure you include the appropriate +using or typedef directives. For example:
--%typemap(in) int { - /* Convert an integer argument */ - ... -} -%typemap(out) int { - /* Return an integer value */ - ... +%include "std_vector.i" + +namespace std { + %template(IntVector) vector<int>; } -/* Apply all of the integer typemaps to size_t */ -%apply int { size_t }; +using namespace std; +typedef std::vector Vector; + +void foo(vector<int> *x, const Vector &x);%apply merely takes all of the typemaps that are - defined for one type and applies them to other types. Note: you can - include a comma separated set of types in the { ... } part of -%apply.
-It should be noted that it is not necessary to copy typemaps for - types that are related by typedef. For example, if you have - this,
+Note: This module makes use of several advanced SWIG features + including templatized typemaps and template partial specialization. If + you are trying to wrap other C++ code with templates, you might look at + the code contained in std_vector.i. Alternatively, you can + show them the code if you want to make their head explode.
+Note: This module is defined for all SWIG target languages. + However argument conversion details and the public API exposed to the + interpreter vary.
+9.4.3 STL exceptions
+Many of the STL wrapper functions add parameter checking and will + throw a language dependent error/exception should the values not be + valid. The classic example is array bounds checking. The library + wrappers are written to throw a C++ exception in the case of error. The + C++ exception in turn gets converted into an appropriate + error/exception for the target language. By and large this handling + should not need customising, however, customisation can easily be + achieved by supplying appropriate "throws" typemaps. For example:
--typedef int size_t; +%module example +%include "std_vector.i" +%typemap(throws) std::out_of_range { + // custom exception handler +} +%template(VectInt) std::vector<int>;then SWIG already knows that the int typemaps apply. You - don't have to do anything.
-10.1.5 What can be done with typemaps?
-The primary use of typemaps is for defining wrapper generation - behavior at the level of individual C/C++ datatypes. There are - currently six general categories of problems that typemaps address:
-Argument handling
+The custom exception handler might, for example, log the exception + then convert it into a specific error/exception for the target + language.
+When using the STL it is advisable to add in an exception handler to + catch all STL exceptions. The %exception directive can be used + by placing the following code before any other methods or libraries to + be wrapped:
--int foo(int x, double y, char *s); +%include "exception.i" + +%exception { + try { + $action + } catch (const std::exception& e) { + SWIG_exception(SWIG_RuntimeError, e.what()); + } +}-
-- Input argument conversion ("in" typemap).
-- Input argument type checking ("typecheck" typemap).
-- Output argument handling ("argout" typemap).
-- Input argument value checking ("check" typemap).
-- Input argument initialization ("arginit" typemap).
-- Default arguments ("default" typemap).
-- Input argument resource management ("freearg" typemap).
-Return value handling
+Any thrown STL exceptions will then be gracefully handled instead of + causing a crash.
+9.4.4 shared_ptr smart pointer
+Some target languages have support for handling the shared_ptr + reference counted smart pointer. This smart pointer is available in the + standard C++11 library as std::shared_ptr. It was also in TR1 + as std::tr1::shared_ptr before it was fully standardized. + Support for the widely used boost::shared_ptr is also + available.
+In order to use std::shared_ptr, the std_shared_ptr.i + library file should be included:
--int foo(int x, double y, char *s); +%include <std_shared_ptr.i>-
-- Function return value conversion ("out" typemap).
-- Return value resource management ("ret" typemap).
-- Resource management for newly allocated objects ("newfree" typemap).
-Exception handling
+The pre-standard std::tr1::shared_ptr can be used by + including the following macro before including the std_shared_ptr.i + library file:
--int foo(int x, double y, char *s) throw(MemoryError, IndexError); +#define SWIG_SHARED_PTR_SUBNAMESPACE tr1 +%include <std_shared_ptr.i>-
-- Handling of C++ exception specifications. ("throw" typemap).
-Global variables
+In order to use boost::shared_ptr, the +boost_shared_ptr.i library file should be included:
--int foo; +%include <boost_shared_ptr.i>-
-- Assignment of a global variable. ("varin" typemap).
-- Reading a global variable. ("varout" typemap).
-Member variables
+You can only use one of these variants of shared_ptr in your + interface file at a time. and all three variants must be used in + conjunction with the %shared_ptr(T) macro, where T is + the underlying pointer type equating to usage shared_ptr<T>. + The type T must be non-primitive. A simple example + demonstrates usage:
--struct Foo { - int x[20]; +%module example +%include <boost_shared_ptr.i> +%shared_ptr(IntValue) + +%inline %{ +#include <boost/shared_ptr.hpp> + +struct IntValue { + int value; + IntValue(int v) : value(v) {} }; + +static int extractValue(const IntValue &t) { + return t.value; +} + +static int extractValueSmart(boost::shared_ptr<IntValue> t) { + return t->value; +} +%}-
-- Assignment of data to a class/structure member. ("memberin" - typemap).
-Constant creation
-+Note that the %shared_ptr(IntValue) declaration occurs + after the inclusion of the boost_shared_ptr.i library which + provides the macro and, very importantly, before any usage or + declaration of the type, IntValue. The %shared_ptr + macro provides, a few things for handling this smart pointer, but + mostly a number of typemaps. These typemaps override the default + typemaps so that the underlying proxy class is stored and passed around + as a pointer to a shared_ptr instead of a plain pointer to the + underlying type. This approach means that any instantiation of the type + can be passed to methods taking the type by value, reference, pointer + or as a smart pointer. The interested reader might want to look at the + generated code, however, usage is simple and no different handling is + required from the target language. For example, a simple use case of + the above code from Java would be:
+--#define FOO 3 -%constant int BAR = 42; -enum { ALE, LAGER, STOUT }; +IntValue iv = new IntValue(1234); +int val1 = example.extractValue(iv); +int val2 = example.extractValueSmart(iv); +System.out.println(val1 + " " + val2);-
-- Creation of constant values. ("consttab" or "constcode" typemap).
-Details of each of these typemaps will be covered shortly. Also, - certain language modules may define additional typemaps that expand - upon this list. For example, the Java module defines a variety of - typemaps for controlling additional aspects of the Java bindings. - Consult language specific documentation for further details.
-10.1.6 What can't be done with typemaps?
-Typemaps can't be used to define properties that apply to C/C++ - declarations as a whole. For example, suppose you had a declaration - like this,
+This shared_ptr library works quite differently to SWIG's normal, + but somewhat limited, smart pointer + handling. The shared_ptr library does not generate extra wrappers, + just for smart pointer handling, in addition to the proxy class. The + normal proxy class including inheritance relationships is generated as + usual. The only real change introduced by the %shared_ptr + macro is that the proxy class stores a pointer to the shared_ptr + instance instead of a raw pointer to the instance. A proxy class + derived from a base which is being wrapped with shared_ptr can and + must be wrapped as a shared_ptr too. In other words all classes in + an inheritance hierarchy must all be used with the %shared_ptr + macro. For example the following code can be used with the base class + shown earlier:
--Foo *make_Foo(int n); --and you wanted to tell SWIG that make_Foo(int n) returned a - newly allocated object (for the purposes of providing better memory - management). Clearly, this property of make_Foo(int n) is - not a property that would be associated with the datatype Foo - * by itself. Therefore, a completely different SWIG customization - mechanism (%feature) is used for this purpose. Consult the -Customization Features chapter for more information about that.
-Typemaps also can't be used to rearrange or transform the order of - arguments. For example, if you had a function like this:
----void foo(int, char *); +%shared_ptr(DerivedIntValue) +%inline %{ +struct DerivedIntValue : IntValue { + DerivedIntValue(int value) : IntValue(value) {} + ... +}; +%}you can't use typemaps to interchange the arguments, allowing you to - call the function like this:
+A shared_ptr of the derived class can now be passed to a method + where the base is expected in the target language, just as it can in + C++:
--foo("hello",3) # Reversed arguments +DerivedIntValue div = new DerivedIntValue(5678); +int val3 = example.extractValue(div); +int val4 = example.extractValueSmart(div);If you want to change the calling conventions of a function, write a - helper function instead. For example:
+If the %shared_ptr macro is omitted for any class in the + inheritance hierarchy, SWIG will warn about this and the generated code + may or may not result in a C++ compilation error. For example, the + following input:
--%rename(foo) wrap_foo; +%include "boost_shared_ptr.i" +%shared_ptr(Parent); + %inline %{ -void wrap_foo(char *s, int x) { - foo(x,s); -} + #include <boost/shared_ptr.hpp> + struct GrandParent { + virtual ~GrandParent() {} + }; + + struct Parent : GrandParent { + virtual ~Parent() {} + }; + + struct Child : Parent { + virtual ~Child() {} + }; %}10.1.7 Similarities to Aspect - Oriented Programming
-SWIG has parallels to -Aspect Oriented Software Development (AOP). The -AOP terminology with respect to SWIG typemaps can be viewed as - follows:
--
-- Cross-cutting concerns: The cross-cutting concerns are the - modularization of the functionality that the typemaps implement, which - is primarily marshalling of types from/to the target language and - C/C++.
-- Advice: The typemap body contains code which is executed - whenever the marshalling is required.
-- Pointcut: The pointcuts are the positions in the wrapper - code that the typemap code is generated into.
-- Aspect: Aspects are the combination of the pointcut and the - advice, hence each typemap is an aspect.
-SWIG can also be viewed as has having a second set of aspects based - around %feature. Features such as -%exception are also cross-cutting concerns as they encapsulate code - that can be used to add logging or exception handling to any function.
-10.1.8 The rest of this chapter
-The rest of this chapter provides detailed information for people - who want to write new typemaps. This information is of particular - importance to anyone who intends to write a new SWIG target language - module. Power users can also use this information to write application - specific type conversion rules.
-Since typemaps are strongly tied to the underlying C++ type system, - subsequent sections assume that you are reasonably familiar with the - basic details of values, pointers, references, arrays, type qualifiers - (e.g., const), structures, namespaces, templates, and memory - management in C/C++. If not, you would be well-advised to consult a - copy of "The C Programming Language" by Kernighan and Ritchie or "The - C++ Programming Language" by Stroustrup before going any further.
-10.2 Typemap specifications
-This section describes the behavior of the %typemap - directive itself.
-10.2.1 Defining a typemap
-New typemaps are defined using the %typemap declaration. - The general form of this declaration is as follows (parts enclosed in [ - ... ] are optional):
+warns about the missing smart pointer information:
++++example.i:12: Warning 520: Base class 'GrandParent' of 'Parent' is not similarly marked as a smart pointer. +example.i:16: Warning 520: Derived class 'Child' of 'Parent' is not similarly marked as a smart pointer. ++Adding the missing %shared_ptr macros will fix this:
--%typemap(method [, modifiers]) typelist code ; +%include "boost_shared_ptr.i" +%shared_ptr(GrandParent); +%shared_ptr(Parent); +%shared_ptr(Child); + +... as before ...method is a simply a name that specifies what kind of - typemap is being defined. It is usually a name like "in", -"out", or "argout". The purpose of these methods is - described later.
-modifiers is an optional comma separated list of -name="value" values. These are sometimes to attach extra - information to a typemap and is often target-language dependent. They - are also known as typemap attributes.
-typelist is a list of the C++ type patterns that the - typemap will match. The general form of this list is as follows:
-+Note: There is somewhat limited support for %shared_ptr + and the director feature and the degress of success varies among the + different target languages. Please help to improve this support by + providing patches with improvements.
+9.4.5 auto_ptr smart pointer
+While std::auto_ptr is deprecated in C++11, some existing + code may still be using it, so SWIG provides limited support for this + class: std_auto_ptr.i defines the typemaps which apply to the + functions returning objects of this type. Any other use of +std_auto_ptr.i is not directly supported.
+A typical example of use would be
+--typelist : typepattern [, typepattern, typepattern, ... ] ; +%include <std_auto_ptr.i> -typepattern : type [ (parms) ] - | type name [ (parms) ] - | ( typelist ) [ (parms) ] +%auto_ptr(Klass) +%inline %{ +class Klass { +public: + // Factory function creating objects of this class: + static std::auto_ptr<Klass> Create(int value) { + return std::auto_ptr<Klass>(new Klass(value)); + } + int getValue() const { return m_value; } + +private: + DerivedIntValue(int value) : m_value(value) {} + int m_value; +}; +%}Each type pattern is either a simple type, a simple type and - argument name, or a list of types in the case of multi-argument - typemaps. In addition, each type pattern can be parameterized with a - list of temporary variables (parms). The purpose of these variables - will be explained shortly.
-code specifies the code used in the typemap. Usually this is - C/C++ code, but in the statically typed target languages, such as Java - and C#, this can contain target language code for certain typemaps. It - can take any one of the following forms:
-+The returned objects can be used naturally from the target language, + e.g. from C#:
+--code : { ... } - | " ... " - | %{ ... %} +Klass k = Klass.Create(17); +int value = k.getValue();Note that the preprocessor will expand code within the {} - delimiters, but not in the last two styles of delimiters, see -Preprocessor and Typemaps. Here are some examples of valid typemap - specifications:
+9.5 Utility Libraries
+9.5.1 exception.i
+The exception.i library provides a language-independent + function for raising a run-time exception in the target language. This + library is largely used by the SWIG library writers. If possible, use + the error handling scheme available to your target language as there is + greater flexibility in what errors/exceptions can be thrown.
+SWIG_exception(int code, const char *message)
+++Raises an exception in the target language. code is one of + the following symbolic constants:
+-/* Simple typemap declarations */ -%typemap(in) int { - $1 = PyInt_AsLong($input); -} -%typemap(in) int "$1 = PyInt_AsLong($input);"; -%typemap(in) int %{ - $1 = PyInt_AsLong($input); -%} - -/* Typemap with extra argument name */ -%typemap(in) int nonnegative { - ... -} - -/* Multiple types in one typemap */ -%typemap(in) int, short, long { - $1 = SvIV($input); +SWIG_MemoryError +SWIG_IOError +SWIG_RuntimeError +SWIG_IndexError +SWIG_TypeError +SWIG_DivisionByZero +SWIG_OverflowError +SWIG_SyntaxError +SWIG_ValueError +SWIG_SystemError ++message is a string indicating more information about the + problem.
+The primary use of this module is in writing language-independent + exception handlers. For example:
+++%include "exception.i" +%exception std::vector::getitem { + try { + $action + } catch (std::out_of_range& e) { + SWIG_exception(SWIG_IndexError,const_cast<char*>(e.what())); + } } ++
+10 Argument Handling
-/* Typemap with modifiers */ -%typemap(in,doc="integer") int "$1 = scm_to_int($input);"; - -/* Typemap applied to patterns of multiple arguments */ -%typemap(in) (char *str, int len), - (char *buffer, int size) -{ - $1 = PyString_AsString($input); - $2 = PyString_Size($input); + ++ ++ +In Chapter 3, SWIG's treatment of basic datatypes and pointers was + described. In particular, primitive types such as int and +double are mapped to corresponding types in the target language. + For everything else, pointers are used to refer to structures, classes, + arrays, and other user-defined datatypes. However, in certain + applications it is desirable to change SWIG's handling of a specific + datatype. For example, you might want to return multiple values through + the arguments of a function. This chapter describes some of the + techniques for doing this.
+10.1 The typemaps.i library
+This section describes the typemaps.i library + file--commonly used to change certain properties of argument + conversion.
+10.1.1 Introduction
+Suppose you had a C function like this:
++++void add(double a, double b, double *result) { + *result = a + b; } ++From reading the source code, it is clear that the function is + storing a value in the double *result parameter. However, + since SWIG does not examine function bodies, it has no way to know that + this is the underlying behavior.
+One way to deal with this is to use the typemaps.i library + file and write interface code like this:
++-+// Simple example using typemaps +%module example +%include "typemaps.i" -/* Typemap with extra pattern parameters */ -%typemap(in, numinputs=0) int *output (int temp), - long *output (long temp) -{ - $1 = &temp; -} +%apply double *OUTPUT { double *result }; +%inline %{ +extern void add(double a, double b, double *result); +%}Admittedly, it's not the most readable syntax at first glance. - However, the purpose of the individual pieces will become clear.
-10.2.2 Typemap scope
-Once defined, a typemap remains in effect for all of the - declarations that follow. A typemap may be redefined for different - sections of an input file. For example:
+The %apply directive tells SWIG that you are going to apply + a special type handling rule to a type. The "double *OUTPUT" + specification is the name of a rule that defines how to return an + output value from an argument of type double *. This rule gets + applied to all of the datatypes listed in curly braces-- in this case " +double *result".
+When the resulting module is created, you can now use the function + like this (shown for Python):
++++>>> a = add(3,4) +>>> print a +7 +>>> ++In this case, you can see how the output value normally returned in + the third argument has magically been transformed into a function + return value. Clearly this makes the function much easier to use since + it is no longer necessary to manufacture a special double * + object and pass it to the function somehow.
+Once a typemap has been applied to a type, it stays in effect for + all future occurrences of the type and name. For example, you could + write the following:
--// typemap1 -%typemap(in) int { -... -} +%module example +%include "typemaps.i" -int fact(int); // typemap1 -int gcd(int x, int y); // typemap1 +%apply double *OUTPUT { double *result }; -// typemap2 -%typemap(in) int { +%inline %{ +extern void add(double a, double b, double *result); +extern void sub(double a, double b, double *result); +extern void mul(double a, double b, double *result); +extern void div(double a, double b, double *result); +%} ... -} - -int isprime(int); // typemap2One exception to the typemap scoping rules pertains to the -%extend declaration. %extend is used to attach new - declarations to a class or structure definition. Because of this, all - of the declarations in an %extend block are subject to the - typemap rules that are in effect at the point where the class itself is - defined. For example:
+In this case, the double *OUTPUT rule is applied to all of + the functions that follow.
+Typemap transformations can even be extended to multiple return + values. For example, consider this code:
--class Foo { - ... -}; - -%typemap(in) int { - ... -} +%include "typemaps.i" +%apply int *OUTPUT { int *width, int *height }; -%extend Foo { - int blah(int x); // typemap has no effect. Declaration is attached to Foo which - // appears before the %typemap declaration. -}; +// Returns a pair (width,height) +void getwinsize(int winid, int *width, int *height);10.2.3 Copying a typemap
-A typemap is copied by using assignment. For example:
-+In this case, the function returns multiple values, allowing it to + be used like this:
+--%typemap(in) Integer = int; +>>> w,h = genwinsize(wid) +>>> print w +400 +>>> print h +300 +>>>or this:
+It should also be noted that although the %apply directive + is used to associate typemap rules to datatypes, you can also use the + rule names directly in arguments. For example, you could write this:
--%typemap(in) Integer, Number, int32_t = int; +// Simple example using typemaps +%module example +%include "typemaps.i" + +%{ +extern void add(double a, double b, double *OUTPUT); +%} +extern void add(double a, double b, double *OUTPUT);Types are often managed by a collection of different typemaps. For - example:
+Typemaps stay in effect until they are explicitly deleted or + redefined to something else. To clear a typemap, the %clear + directive should be used. For example:
--%typemap(in) int { ... } -%typemap(out) int { ... } -%typemap(varin) int { ... } -%typemap(varout) int { ... } +%clear double *result; // Remove all typemaps for double *resultTo copy all of these typemaps to a new type, use %apply. - For example:
+10.1.2 Input parameters
+The following typemaps instruct SWIG that a pointer really only + holds a single input value:
--%apply int { Integer }; // Copy all int typemaps to Integer -%apply int { Integer, Number }; // Copy all int typemaps to both Integer and Number +int *INPUT +short *INPUT +long *INPUT +unsigned int *INPUT +unsigned short *INPUT +unsigned long *INPUT +double *INPUT +float *INPUTThe patterns for %apply follow the same rules as for -%typemap. For example:
+When used, it allows values to be passed instead of pointers. For + example, consider this function:
--%apply int *output { Integer *output }; // Typemap with name -%apply (char *buf, int len) { (char *buffer, int size) }; // Multiple arguments +double add(double *a, double *b) { + return *a+*b; +}10.2.4 Deleting a typemap
-A typemap can be deleted by simply defining no code. For example:
+Now, consider this SWIG interface:
--%typemap(in) int; // Clears typemap for int -%typemap(in) int, long, short; // Clears typemap for int, long, short -%typemap(in) int *output; +%module example +%include "typemaps.i" +... +%{ +extern double add(double *, double *); +%} +extern double add(double *INPUT, double *INPUT); +The %clear directive clears all typemaps for a given type. - For example:
-+When the function is used in the scripting language interpreter, it + will work like this:
+--%clear int; // Removes all types for int -%clear int *output, long *output; +result = add(3,4)Note: Since SWIG's default behavior is defined by typemaps, - clearing a fundamental type like int will make that type - unusable unless you also define a new set of typemaps immediately after - the clear operation.
-10.2.5 Placement of typemaps
-Typemap declarations can be declared in the global scope, within a - C++ namespace, and within a C++ class. For example:
+10.1.3 Output parameters
+The following typemap rules tell SWIG that pointer is the output + value of a function. When used, you do not need to supply the argument + when calling the function. Instead, one or more output values are + returned.
--%typemap(in) int { - ... -} - -namespace std { - class string; - %typemap(in) string { - ... - } -} +int *OUTPUT +short *OUTPUT +long *OUTPUT +unsigned int *OUTPUT +unsigned short *OUTPUT +unsigned long *OUTPUT +double *OUTPUT +float *OUTPUT -class Bar { -public: - typedef const int & const_reference; - %typemap(out) const_reference { - ... - } -};When a typemap appears inside a namespace or class, it stays in - effect until the end of the SWIG input (just like before). However, the - typemap takes the local scope into account. Therefore, this code
+These methods can be used as shown in an earlier example. For + example, if you have this C function :
--namespace std { - class string; - %typemap(in) string { - ... - } +void add(double a, double b, double *c) { + *c = a+b; }is really defining a typemap for the type std::string. You - could have code like this:
+A SWIG interface file might look like this :
--namespace std { - class string; - %typemap(in) string { /* std::string */ - ... - } -} +%module example +%include "typemaps.i" +... +%inline %{ +extern void add(double a, double b, double *OUTPUT); +%} -namespace Foo { - class string; - %typemap(in) string { /* Foo::string */ - ... - } -}In this case, there are two completely distinct typemaps that apply - to two completely different types (std::string and -Foo::string).
-It should be noted that for scoping to work, SWIG has to know that -string is a typename defined within a particular namespace. In this - example, this is done using the forward class declaration class - string.
-10.3 Pattern matching rules
-The section describes the pattern matching rules by which C/C++ - datatypes are associated with typemaps. The matching rules can be - observed in practice by using the debugging options also described.
-10.3.1 Basic matching rules
-Typemaps are matched using both a type and a name (typically the - name of a argument). For a given TYPE NAME pair, the following - rules are applied, in order, to find a match. The first typemap found - is used.
--
-- Typemaps that exactly match TYPE and NAME.
-- Typemaps that exactly match TYPE only.
-- If TYPE is a C++ template of type T< TPARMS >, - where TPARMS are the template parameters, the type is stripped - of the template parameters and the following checks are then made: -
--
-- Typemaps that exactly match T and NAME.
-- Typemaps that exactly match T only.
-If TYPE includes qualifiers (const, volatile, etc.), each - qualifier is stripped one at a time to form a new stripped type and the - matching rules above are repeated on the stripped type. The left-most - qualifier is stripped first, resulting in the right-most (or top-level) - qualifier being stripped last. For example int const*const is - first stripped to int *const then int *.
-If TYPE is an array. The following transformation is made:
--
-- Replace all dimensions to [ANY] and look for a generic - array typemap.
-To illustrate, suppose that you had a function like this:
+In this case, only a single output value is returned, but this is + not a restriction. An arbitrary number of output values can be returned + by applying the output rules to more than one argument (as shown + previously).
+If the function also returns a value, it is returned along with the + argument. For example, if you had this:
--int foo(const char *s); +extern int foo(double a, double b, double *OUTPUT);To find a typemap for the argument const char *s, SWIG will - search for the following typemaps:
-+The function will return two values like this:
+--const char *s Exact type and name match -const char * Exact type match -char *s Type and name match (qualifier stripped) -char * Type match (qualifier stripped) +iresult, dresult = foo(3.5, 2)When more than one typemap rule might be defined, only the first - match found is actually used. Here is an example that shows how some of - the basic rules are applied:
+10.1.4 Input/Output parameters
+When a pointer serves as both an input and output value you can use + the following typemaps :
--%typemap(in) int *x { - ... typemap 1 -} - -%typemap(in) int * { - ... typemap 2 -} - -%typemap(in) const int *z { - ... typemap 3 -} - -%typemap(in) int [4] { - ... typemap 4 -} - -%typemap(in) int [ANY] { - ... typemap 5 -} +int *INOUT +short *INOUT +long *INOUT +unsigned int *INOUT +unsigned short *INOUT +unsigned long *INOUT +double *INOUT +float *INOUT -void A(int *x); // int *x rule (typemap 1) -void B(int *y); // int * rule (typemap 2) -void C(const int *x); // int *x rule (typemap 1) -void D(const int *z); // const int *z rule (typemap 3) -void E(int x[4]); // int [4] rule (typemap 4) -void F(int x[1000]); // int [ANY] rule (typemap 5)Compatibility note: SWIG-2.0.0 introduced stripping the - qualifiers one step at a time. Prior versions stripped all qualifiers - in one step.
-10.3.2 Typedef reductions - matching
-If no match is found using the rules in the previous section, SWIG - applies a typedef reduction to the type and repeats the typemap search - for the reduced type. To illustrate, suppose you had code like this:
+A C function that uses this might be something like this:
--%typemap(in) int { - ... typemap 1 +void negate(double *x) { + *x = -(*x); } -typedef int Integer; -void blah(Integer x);To find the typemap for Integer x, SWIG will first search - for the following typemaps:
-+To make x function as both and input and output value, declare the + function like this in an interface file :
+--Integer x -Integer +%module example +%include "typemaps.i" +... +%{ +extern void negate(double *); +%} +extern void negate(double *INOUT); +Finding no match, it then applies a reduction Integer -> int - to the type and repeats the search.
-+Now within a script, you can simply call the function normally :
+--int x -int --> match: typemap 1 +a = negate(3); # a = -3 after calling thisEven though two types might be the same via typedef, SWIG allows - typemaps to be defined for each typename independently. This allows for - interesting customization possibilities based solely on the typename - itself. For example, you could write code like this:
+One subtle point of the INOUT rule is that many scripting + languages enforce mutability constraints on primitive objects (meaning + that simple objects like integers and strings aren't supposed to + change). Because of this, you can't just modify the object's value in + place as the underlying C function does in this example. Therefore, the + INOUT rule returns the modified value as a new object rather + than directly overwriting the value of the original input object.
+Compatibility note : The INOUT rule used to be known + as BOTH in earlier versions of SWIG. Backwards compatibility + is preserved, but deprecated.
+10.1.5 Using different names
+As previously shown, the %apply directive can be used to + apply the INPUT, OUTPUT, and INOUT typemaps + to different argument names. For example:
--typedef double pdouble; // Positive double +// Make double *result an output value +%apply double *OUTPUT { double *result }; + +// Make Int32 *in an input value +%apply int *INPUT { Int32 *in }; + +// Make long *x inout +%apply long *INOUT {long *x}; -// typemap 1 -%typemap(in) double { - ... get a double ... -} -// typemap 2 -%typemap(in) pdouble { - ... get a positive double ... -} -double sin(double x); // typemap 1 -pdouble sqrt(pdouble x); // typemap 2When reducing the type, only one typedef reduction is applied at a - time. The search process continues to apply reductions until a match is - found or until no more reductions can be made.
-For complicated types, the reduction process can generate a long - list of patterns. Consider the following:
+To clear a rule, the %clear directive is used:
--typedef int Integer; -typedef Integer Row4[4]; -void foo(Row4 rows[10]); +%clear double *result; +%clear Int32 *in, long *x;To find a match for the Row4 rows[10] argument, SWIG would - check the following patterns, stopping only when it found a match:
+Typemap declarations are lexically scoped so a typemap takes effect + from the point of definition to the end of the file or a matching +%clear declaration.
+10.2 Applying constraints to input values +
+In addition to changing the handling of various input values, it is + also possible to use typemaps to apply constraints. For example, maybe + you want to insure that a value is positive, or that a pointer is + non-NULL. This can be accomplished including the constraints.i + library file.
+10.2.1 Simple constraint example
+The constraints library is best illustrated by the following + interface file :
--Row4 rows[10] -Row4 [10] -Row4 rows[ANY] -Row4 [ANY] +// Interface file with constraints +%module example +%include "constraints.i" -# Reduce Row4 --> Integer[4] -Integer rows[10][4] -Integer [10][4] -Integer rows[ANY][ANY] -Integer [ANY][ANY] +double exp(double x); +double log(double POSITIVE); // Allow only positive values +double sqrt(double NONNEGATIVE); // Non-negative values only +double inv(double NONZERO); // Non-zero values +void free(void *NONNULL); // Non-NULL pointers only -# Reduce Integer --> int -int rows[10][4] -int [10][4] -int rows[ANY][ANY] -int [ANY][ANY]For parameterized types like templates, the situation is even more - complicated. Suppose you had some declarations like this:
+The behavior of this file is exactly as you would expect. If any of + the arguments violate the constraint condition, a scripting language + exception will be raised. As a result, it is possible to catch bad + values, prevent mysterious program crashes and so on.
+10.2.2 Constraint methods
+The following constraints are currently available
--typedef int Integer; -typedef foo<Integer,Integer> fooii; -void blah(fooii *x); +POSITIVE Any number > 0 (not zero) +NEGATIVE Any number < 0 (not zero) +NONNEGATIVE Any number >= 0 +NONPOSITIVE Any number <= 0 +NONZERO Nonzero number +NONNULL Non-NULL pointer (pointers only). +In this case, the following typemap patterns are searched for the - argument fooii *x:
+10.2.3 Applying constraints to new + datatypes
+The constraints library only supports the primitive C datatypes, but + it is easy to apply it to new datatypes using %apply. For + example :
--fooii *x -fooii * - -# Reduce fooii --> foo<Integer,Integer> -foo<Integer,Integer> *x -foo<Integer,Integer> * +// Apply a constraint to a Real variable +%apply Number POSITIVE { Real in }; -# Reduce Integer -> int -foo<int, Integer> *x -foo<int, Integer> * +// Apply a constraint to a pointer type +%apply Pointer NONNULL { Vector * }; -# Reduce Integer -> int -foo<int, int> *x -foo<int, int> *Typemap reductions are always applied to the left-most type that - appears. Only when no reductions can be made to the left-most type are - reductions made to other parts of the type. This behavior means that - you could define a typemap for foo<int,Integer>, but a typemap - for foo<Integer,int> would never be matched. Admittedly, this - is rather esoteric--there's little practical reason to write a typemap - quite like that. Of course, you could rely on this to confuse your - coworkers even more.
-As a point of clarification, it is worth emphasizing that typedef - matching is a typedef reduction process only, that is, SWIG does - not search for every single possible typedef. Given a type in a - declaration, it will only reduce the type, it won't build it up looking - for typedefs. For example, given the type Struct, the typemap - below will not be used for the aStruct parameter, because -Struct is fully reduced:
+The special types of "Number" and "Pointer" can be applied to any + numeric and pointer variable type respectively. To later remove a + constraint, the %clear directive can be used :
-struct Struct {...}; -typedef Struct StructTypedef; - -%typemap(in) StructTypedef { - ... -} - -void go(Struct aStruct); +%clear Real in; +%clear Vector *;+
+11 Typemaps
+ + ++-+
- Introduction + +
+- Typemap specifications + +
+- Pattern matching rules + +
+- Code generation rules + +
+- Common typemap methods + +
+- Some typemap examples + +
+- Typemaps for multiple target languages
+- Optimal code generation when returning + by value
+- Multi-argument typemaps +
+- Typemap warnings
+- Typemap fragments + +
+- The run-time type checker +
++
+- Implementation
+- Usage
+- Typemaps and overloading
+- More about %apply and %clear
+- Passing data between typemaps
+- C++ "this" pointer
+- Where to go for more information?
+10.3.3 Default typemap matching rules
-If the basic pattern matching rules result in no match being made, - even after typedef reductions, the default typemap matching rules are - used to look for a suitable typemap match. These rules match a generic - typemap based on the reserved SWIGTYPE base type. For example - pointers will use SWIGTYPE * and references will use -SWIGTYPE &. More precisely, the rules are based on the C++ class - template partial specialization matching rules used by C++ compilers - when looking for an appropriate partial template specialization. This - means that a match is chosen from the most specialized set of generic - typemap types available. For example, when looking for a match to -int const *, the rules will prefer to match SWIGTYPE const * - if available before matching SWIGTYPE *, before matching -SWIGTYPE.
-Most SWIG language modules use typemaps to define the default - behavior of the C primitive types. This is entirely straightforward. - For example, a set of typemaps for primitives marshalled by value or - const reference are written like this:
+ +11.1 Introduction
+Chances are, you are reading this chapter for one of two reasons; + you either want to customize SWIG's behavior or you overheard someone + mumbling some incomprehensible drivel about "typemaps" and you asked + yourself "typemaps, what are those?" That said, let's start with a + short disclaimer that "typemaps" are an advanced customization feature + that provide direct access to SWIG's low-level code generator. Not only + that, they are an integral part of the SWIG C++ type system (a + non-trivial topic of its own). Typemaps are generally not a + required part of using SWIG. Therefore, you might want to re-read the + earlier chapters if you have found your way to this chapter with only a + vague idea of what SWIG already does by default.
+11.1.1 Type conversion
+One of the most important problems in wrapper code generation is the + conversion or marshalling of datatypes between programming languages. + Specifically, for every C/C++ declaration, SWIG must somehow generate + wrapper code that allows values to be passed back and forth between + languages. Since every programming language represents data + differently, this is not a simple of matter of simply linking code + together with the C linker. Instead, SWIG has to know something about + how data is represented in each language and how it can be manipulated.
+To illustrate, suppose you had a simple C function like this:
--%typemap(in) int "... convert to int ..."; -%typemap(in) short "... convert to short ..."; -%typemap(in) float "... convert to float ..."; -... -%typemap(in) const int & "... convert ..."; -%typemap(in) const short & "... convert ..."; -%typemap(in) const float & "... convert ..."; -... +int factorial(int n);Since typemap matching follows all typedef declarations, - any sort of type that is mapped to a primitive type by value or const - reference through typedef will be picked up by one of these - primitive typemaps. Most language modules also define typemaps for char - pointers and char arrays to handle strings, so these non-default types - will also be used in preference as the basic typemap matching rules - provide a better match than the default typemap matching rules.
-Below is a list of the typical default types supplied by language - modules, showing what the "in" typemap would look like:
+To access this function from Python, a pair of Python API functions + are used to convert integer values. For example:
--%typemap(in) SWIGTYPE & { ... default reference handling ... }; -%typemap(in) SWIGTYPE * { ... default pointer handling ... }; -%typemap(in) SWIGTYPE *const { ... default pointer const handling ... }; -%typemap(in) SWIGTYPE *const& { ... default pointer const reference handling ... }; -%typemap(in) SWIGTYPE[ANY] { ... 1D fixed size arrays handlling ... }; -%typemap(in) SWIGTYPE [] { ... unknown sized array handling ... }; -%typemap(in) enum SWIGTYPE { ... default handling for enum values ... }; -%typemap(in) const enum SWIGTYPE & { ... default handling for const enum reference values ... }; -%typemap(in) SWIGTYPE (CLASS::*) { ... default pointer member handling ... }; -%typemap(in) SWIGTYPE { ... simple default handling ... }; +long PyInt_AsLong(PyObject *obj); /* Python --> C */ +PyObject *PyInt_FromLong(long x); /* C --> Python */If you wanted to change SWIG's default handling for simple pointers, - you would simply redefine the rule for SWIGTYPE *. Note, the - simple default typemap rule is used to match against simple types that - don't match any other rules:
+The first function is used to convert the input argument from a + Python integer object to C long. The second function is used + to convert a value from C back into a Python integer object.
+Inside the wrapper function, you might see these functions used like + this:
--%typemap(in) SWIGTYPE { ... simple default handling ... } +PyObject *wrap_factorial(PyObject *self, PyObject *args) { + int arg1; + int result; + PyObject *obj1; + PyObject *resultobj; + + if (!PyArg_ParseTuple("O:factorial", &obj1)) return NULL; + arg1 = PyInt_AsLong(obj1); + result = factorial(arg1); + resultobj = PyInt_FromLong(result); + return resultobj; +}This typemap is important because it is the rule that gets triggered - when call or return by value is used. For instance, if you have a - declaration like this:
+Every target language supported by SWIG has functions that work in a + similar manner. For example, in Perl, the following functions are used:
--double dot_product(Vector a, Vector b); +IV SvIV(SV *sv); /* Perl --> C */ +void sv_setiv(SV *sv, IV val); /* C --> Perl */The Vector type will usually just get matched against -SWIGTYPE. The default implementation of SWIGTYPE is to - convert the value into pointers (as described in - this earlier section).
-By redefining SWIGTYPE it may be possible to implement - other behavior. For example, if you cleared all typemaps for -SWIGTYPE, SWIG simply won't wrap any unknown datatype (which might - be useful for debugging). Alternatively, you might modify SWIGTYPE to - marshal objects into strings instead of converting them to pointers.
-Let's consider an example where the following typemaps are defined - and SWIG is looking for the best match for the enum shown below:
+In Tcl:
--%typemap(in) const Hello & { ... } -%typemap(in) const enum SWIGTYPE & { ... } -%typemap(in) enum SWIGTYPE & { ... } -%typemap(in) SWIGTYPE & { ... } -%typemap(in) SWIGTYPE { ... } - -enum Hello {}; -const Hello &hi; +int Tcl_GetLongFromObj(Tcl_Interp *interp, Tcl_Obj *obj, long *value); +Tcl_Obj *Tcl_NewIntObj(long value);The typemap at the top of the list will be chosen, not because it is - defined first, but because it is the closest match for the type being - wrapped. If any of the typemaps in the above list were not defined, - then the next one on the list would have precedence.
-The best way to explore the default typemaps is to look at the ones - already defined for a particular language module. Typemap definitions - are usually found in the SWIG library in a file such as java.swg -, csharp.swg etc. However, for many of the target languages the - typemaps are hidden behind complicated macros, so the best way to view - the default typemaps, or any typemaps for that matter, is to look at - the preprocessed output by running swig -E on any interface - file. Finally the best way to view the typemap matching rules in action - is via the debugging typemap - pattern matching options covered later on.
-Compatibility note: The default typemap matching rules were - modified in SWIG-2.0.0 from a slightly simpler scheme to match the - current C++ class template partial specialization matching rules.
-10.3.4 - Multi-arguments typemaps
-When multi-argument typemaps are specified, they take precedence - over any typemaps specified for a single type. For example:
+The precise details are not so important. What is important is that + all of the underlying type conversion is handled by collections of + utility functions and short bits of C code like this---you simply have + to read the extension documentation for your favorite language to know + how it works (an exercise left to the reader).
+11.1.2 Typemaps
+Since type handling is so central to wrapper code generation, SWIG + allows it to be completely defined (or redefined) by the user. To do + this, a special %typemap directive is used. For example:
--%typemap(in) (char *buffer, int len) { - // typemap 1 +/* Convert from Python --> C */ +%typemap(in) int { + $1 = PyInt_AsLong($input); } -%typemap(in) char *buffer { - // typemap 2 +/* Convert from C --> Python */ +%typemap(out) int { + $result = PyInt_FromLong($1); } - -void foo(char *buffer, int len, int count); // (char *buffer, int len) -void bar(char *buffer, int blah); // char *bufferMulti-argument typemaps are also more restrictive in the way that - they are matched. Currently, the first argument follows the matching - rules described in the previous section, but all subsequent arguments - must match exactly.
-10.3.5 Matching - rules compared to C++ templates
-For those intimately familiar with C++ templates, a comparison of - the typemap matching rules and template type deduction is interesting. - The two areas considered are firstly the default typemaps and their - similarities to partial template specialization and secondly, - non-default typemaps and their similarities to full template - specialization.
-For default (SWIGTYPE) typemaps the rules are inspired by C++ class - template partial specialization. For example, given partial - specialization for T const& :
+At first glance, this code will look a little confusing. However, + there is really not much to it. The first typemap (the "in" typemap) is + used to convert a value from the target language to C. The second + typemap (the "out" typemap) is used to convert in the other direction. + The content of each typemap is a small fragment of code that is + inserted directly into the SWIG generated wrapper functions. The code + is usually C or C++ code which will be generated into the C/C++ wrapper + functions. Note that this isn't always the case as some target language + modules allow target language code within the typemaps which gets + generated into target language specific files. Within this code, a + number of special variables prefixed with a $ are expanded. These are + really just placeholders for C/C++ variables that are generated in the + course of creating the wrapper function. In this case, $input + refers to an input object that needs to be converted to C/C++ and +$result refers to an object that is going to be returned by a + wrapper function. $1 refers to a C/C++ variable that has the + same type as specified in the typemap declaration (an int in + this example).
+A short example might make this a little more clear. If you were + wrapping a function like this:
--template <typename T> struct X { void a(); }; -template <typename T> struct X< T const& > { void b(); }; +int gcd(int x, int y);The full (unspecialized) template is matched with most types, such - as:
+A wrapper function would look approximately like this:
--X< int & > x1; x1.a(); +PyObject *wrap_gcd(PyObject *self, PyObject *args) { + int arg1; + int arg2; + int result; + PyObject *obj1; + PyObject *obj2; + PyObject *resultobj; + + if (!PyArg_ParseTuple("OO:gcd", &obj1, &obj2)) return NULL; + + /* "in" typemap, argument 1 */ + { + arg1 = PyInt_AsLong(obj1); + } + + /* "in" typemap, argument 2 */ + { + arg2 = PyInt_AsLong(obj2); + } + + result = gcd(arg1,arg2); + + /* "out" typemap, return value */ + { + resultobj = PyInt_FromLong(result); + } + + return resultobj; +}and the following all match the T const& partial - specialization:
+In this code, you can see how the typemap code has been inserted + into the function. You can also see how the special $ variables have + been expanded to match certain variable names inside the wrapper + function. This is really the whole idea behind typemaps--they simply + let you insert arbitrary code into different parts of the generated + wrapper functions. Because arbitrary code can be inserted, it possible + to completely change the way in which values are converted.
+11.1.3 Pattern matching
+As the name implies, the purpose of a typemap is to "map" C + datatypes to types in the target language. Once a typemap is defined + for a C datatype, it is applied to all future occurrences of that type + in the input file. For example:
--X< int *const& > x2; x2.b(); -X< int const*const& > x3; x3.b(); -X< int const& > x4; x4.b(); +/* Convert from Perl --> C */ +%typemap(in) int { + $1 = SvIV($input); +} + +... +int factorial(int n); +int gcd(int x, int y); +int count(char *s, char *t, int max);Now, given just these two default typemaps, where T is analogous to - SWIGTYPE:
+The matching of typemaps to C datatypes is more than a simple + textual match. In fact, typemaps are fully built into the underlying + type system. Therefore, typemaps are unaffected by typedef, + namespaces, and other declarations that might hide the underlying type. + For example, you could have code like this:
--%typemap(...) SWIGTYPE { ... } -%typemap(...) SWIGTYPE const& { ... } +/* Convert from Ruby--> C */ +%typemap(in) int { + $1 = NUM2INT($input); +} +... +typedef int Integer; +namespace foo { + typedef Integer Number; +}; + +int foo(int x); +int bar(Integer y); +int spam(foo::Number a, foo::Number b);The generic default typemap SWIGTYPE is used with most - types, such as
+In this case, the typemap is still applied to the proper arguments + even though typenames don't always match the text "int". This ability + to track types is a critical part of SWIG--in fact, all of the target + language modules work merely define a set of typemaps for the basic + types. Yet, it is never necessary to write new typemaps for typenames + introduced by typedef.
+In addition to tracking typenames, typemaps may also be specialized + to match against a specific argument name. For example, you could write + a typemap like this:
--int & +%typemap(in) double nonnegative { + $1 = PyFloat_AsDouble($input); + if ($1 < 0) { + PyErr_SetString(PyExc_ValueError,"argument must be nonnegative."); + return NULL; + } +} + +... +double sin(double x); +double cos(double x); +double sqrt(double nonnegative); + +typedef double Real; +double log(Real nonnegative); +...and the following all match the SWIGTYPE const& typemap, - just like the partial template matching:
+For certain tasks such as input argument conversion, typemaps can be + defined for sequences of consecutive arguments. For example:
--int *const& -int const*const& -int const& +%typemap(in) (char *str, int len) { + $1 = PyString_AsString($input); /* char *str */ + $2 = PyString_Size($input); /* int len */ +} +... +int count(char *str, int len, char c);Note that the template and typemap matching rules are not identical - for all default typemaps though, for example, with arrays.
-For non-default typemaps, one might expect SWIG to follow the fully - specialized template rules. This is nearly the case, but not quite. - Consider a very similar example to the earlier partially specialized - template but this time there is a fully specialized template:
+In this case, a single input object is expanded into a pair of C + arguments. This example also provides a hint to the unusual variable + naming scheme involving $1, $2, and so forth.
+11.1.4 Reusing typemaps
+Typemaps are normally defined for specific type and argument name + patterns. However, typemaps can also be copied and reused. One way to + do this is to use assignment like this:
--template <typename T> struct Y { void a(); }; -template <> struct Y< int const & > { void b(); }; +%typemap(in) Integer = int; +%typemap(in) (char *buffer, int size) = (char *str, int len);Only the one type matches the specialized template exactly:
+A more general form of copying is found in the %apply + directive like this:
--Y< int & > y1; y1.a(); -Y< int *const& > y2; y2.a(); -Y< int const *const& > y3; y3.a(); -Y< int const& > y4; y4.b(); // fully specialized match +%typemap(in) int { + /* Convert an integer argument */ + ... +} +%typemap(out) int { + /* Return an integer value */ + ... +} + +/* Apply all of the integer typemaps to size_t */ +%apply int { size_t };Given typemaps with the same types used for the template declared - above, where T is again analogous to SWIGTYPE:
+%apply merely takes all of the typemaps that are + defined for one type and applies them to other types. Note: you can + include a comma separated set of types in the { ... } part of +%apply.
+It should be noted that it is not necessary to copy typemaps for + types that are related by typedef. For example, if you have + this,
--%typemap(...) SWIGTYPE { ... } -%typemap(...) int const& { ... } +typedef int size_t;The comparison between non-default typemaps and fully specialized - single parameter templates turns out to be the same, as just the one - type will match the non-default typemap:
+then SWIG already knows that the int typemaps apply. You + don't have to do anything.
+11.1.5 What can be done with typemaps?
+The primary use of typemaps is for defining wrapper generation + behavior at the level of individual C/C++ datatypes. There are + currently six general categories of problems that typemaps address:
+Argument handling
--int & -int *const& -int const*const& -int const& // matches non-default typemap int const& +int foo(int x, double y, char *s);However, if a non-const type is used instead:
++
+- Input argument conversion ("in" typemap).
+- Input argument type checking ("typecheck" typemap).
+- Output argument handling ("argout" typemap).
+- Input argument value checking ("check" typemap).
+- Input argument initialization ("arginit" typemap).
+- Default arguments ("default" typemap).
+- Input argument resource management ("freearg" typemap).
+Return value handling
--%typemap(...) SWIGTYPE { ... } -%typemap(...) int & { ... } +int foo(int x, double y, char *s);then there is a clear difference to template matching as both the - const and non-const types match the typemap:
++
+- Function return value conversion ("out" typemap).
+- Return value resource management ("ret" typemap).
+- Resource management for newly allocated objects ("newfree" typemap).
+Exception handling
--int & // matches non-default typemap int & -int *const& -int const*const& -int const& // matches non-default typemap int & +int foo(int x, double y, char *s) throw(MemoryError, IndexError);There are other subtle differences such as typedef handling, but at - least it should be clear that the typemap matching rules are similar to - those for specialized template handling.
-10.3.6 Debugging typemap - pattern matching
-There are two useful debug command line options available for - debugging typemaps, -debug-tmsearch and -debug-tmused -.
-The -debug-tmsearch option is a verbose option for - debugging typemap searches. This can be very useful for watching the - pattern matching process in action and for debugging which typemaps are - used. The option displays all the typemaps and types that are looked - for until a successful pattern match is made. As the display includes - searches for each and every type needed for wrapping, the amount of - information displayed can be large. Normally you would manually search - through the displayed information for the particular type that you are - interested in.
-For example, consider some of the code used in the -Typedef reductions section already covered:
++
+- Handling of C++ exception specifications. ("throw" typemap).
+Global variables
--typedef int Integer; -typedef Integer Row4[4]; -void foo(Row4 rows[10]); +int foo;A sample of the debugging output is shown below for the "in" - typemap:
-++
+- Assignment of a global variable. ("varin" typemap).
+- Reading a global variable. ("varout" typemap).
+Member variables
+--swig -perl -debug-tmsearch example.i -... -example.h:3: Searching for a suitable 'in' typemap for: Row4 rows[10] - Looking for: Row4 rows[10] - Looking for: Row4 [10] - Looking for: Row4 rows[ANY] - Looking for: Row4 [ANY] - Looking for: Integer rows[10][4] - Looking for: Integer [10][4] - Looking for: Integer rows[ANY][ANY] - Looking for: Integer [ANY][ANY] - Looking for: int rows[10][4] - Looking for: int [10][4] - Looking for: int rows[ANY][ANY] - Looking for: int [ANY][ANY] - Looking for: SWIGTYPE rows[ANY][ANY] - Looking for: SWIGTYPE [ANY][ANY] - Looking for: SWIGTYPE rows[ANY][] - Looking for: SWIGTYPE [ANY][] - Looking for: SWIGTYPE *rows[ANY] - Looking for: SWIGTYPE *[ANY] - Looking for: SWIGTYPE rows[ANY] - Looking for: SWIGTYPE [ANY] - Looking for: SWIGTYPE rows[] - Looking for: SWIGTYPE [] - Using: %typemap(in) SWIGTYPE [] -... +struct Foo { + int x[20]; +};showing that the best default match supplied by SWIG is the -SWIGTYPE [] typemap. As the example shows, the successful match - displays the used typemap source including typemap method, type and - optional name in one of these simplified formats:
-
-- Using: %typemap(method) type name
-- Using: %typemap(method) type name = type2 name2
-- Using: %apply type2 name2 { type name }
+- Assignment of data to a class/structure member. ("memberin" + typemap).
This information might meet your debugging needs, however, you might - want to analyze further. If you next invoke SWIG with the -E - option to display the preprocessed output, and search for the - particular typemap used, you'll find the full typemap contents (example - shown below for Python):
+Constant creation
--%typemap(in, noblock=1) SWIGTYPE [] (void *argp = 0, int res = 0) { - res = SWIG_ConvertPtr($input, &argp,$descriptor, $disown | 0 ); - if (!SWIG_IsOK(res)) { - SWIG_exception_fail(SWIG_ArgError(res), "in method '" "$symname" "', argument " - "$argnum"" of type '" "$type""'"); - } - $1 = ($ltype)(argp); -} +#define FOO 3 +%constant int BAR = 42; +enum { ALE, LAGER, STOUT };The generated code for the foo wrapper will then contain - the snippets of the typemap with the special variables expanded. The - rest of this chapter will need reading though to fully understand all - of this, however, the relevant parts of the generated code for the - above typemap can be seen below:
++
+- Creation of constant values. ("consttab" or "constcode" typemap).
+Details of each of these typemaps will be covered shortly. Also, + certain language modules may define additional typemaps that expand + upon this list. For example, the Java module defines a variety of + typemaps for controlling additional aspects of the Java bindings. + Consult language specific documentation for further details.
+11.1.6 What can't be done with typemaps?
+Typemaps can't be used to define properties that apply to C/C++ + declarations as a whole. For example, suppose you had a declaration + like this,
--SWIGINTERN PyObject *_wrap_foo(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { -... - void *argp1 = 0 ; - int res1 = 0 ; -... - res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_a_4__int, 0 | 0 ); - if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "foo" "', argument " - "1"" of type '" "int [10][4]""'"); - } - arg1 = (int (*)[4])(argp1); -... -} +Foo *make_Foo(int n);Searches for multi-argument typemaps are not mentioned unless a - matching multi-argument typemap does actually exist. For example, the - output for the code in the -earlier multi-arguments section is as follows:
-+and you wanted to tell SWIG that make_Foo(int n) returned a + newly allocated object (for the purposes of providing better memory + management). Clearly, this property of make_Foo(int n) is + not a property that would be associated with the datatype Foo + * by itself. Therefore, a completely different SWIG customization + mechanism (%feature) is used for this purpose. Consult the +Customization Features chapter for more information about that.
+Typemaps also can't be used to rearrange or transform the order of + arguments. For example, if you had a function like this:
+--... -example.h:39: Searching for a suitable 'in' typemap for: char *buffer - Looking for: char *buffer - Multi-argument typemap found... - Using: %typemap(in) (char *buffer,int len) -... +void foo(int, char *);The second option for debugging is -debug-tmused and this - displays the typemaps used. This option is a less verbose version of - the -debug-tmsearch option as it only displays each - successfully found typemap on a separate single line. The output - displays the type, and name if present, the typemap method in brackets - and then the actual typemap used in the same simplified format output - by the -debug-tmsearch option. Below is the output for the - example code at the start of this section on debugging.
-+you can't use typemaps to interchange the arguments, allowing you to + call the function like this:
+--$ swig -perl -debug-tmused example.i -example.h:3: Typemap for Row4 rows[10] (in) : %typemap(in) SWIGTYPE [] -example.h:3: Typemap for Row4 rows[10] (typecheck) : %typemap(typecheck) SWIGTYPE * -example.h:3: Typemap for Row4 rows[10] (freearg) : %typemap(freearg) SWIGTYPE [] -example.h:3: Typemap for void foo (out) : %typemap(out) void +foo("hello",3) # Reversed argumentsNow, consider the following interface file:
+If you want to change the calling conventions of a function, write a + helper function instead. For example:
--%module example - -%{ -void set_value(const char* val) {} -%} - -%typemap(check) char *NON_NULL { - if (!$1) { - /* ... error handling ... */ - } -} - -// use default pointer handling instead of strings -%apply SWIGTYPE * { const char* val, const char* another_value } - -%typemap(check) const char* val = char* NON_NULL; - -%typemap(arginit, noblock=1) const char* val { - $1 = ""; +%rename(foo) wrap_foo; +%inline %{ +void wrap_foo(char *s, int x) { + foo(x,s); } - -void set_value(const char* val); - --and the output debug:
----swig -perl5 -debug-tmused example.i -example.i:21: Typemap for char const *val (arginit) : %typemap(arginit) char const *val -example.i:21: Typemap for char const *val (in) : %apply SWIGTYPE * { char const *val } -example.i:21: Typemap for char const *val (typecheck) : %apply SWIGTYPE * { char const *val } -example.i:21: Typemap for char const *val (check) : %typemap(check) char const *val = char *NON_NULL -example.i:21: Typemap for char const *val (freearg) : %apply SWIGTYPE * { char const *val } -example.i:21: Typemap for void set_value (out) : %typemap(out) void +%}The following observations about what is displayed can be noted (the - same applies for -debug-tmsearch):
+11.1.7 Similarities to Aspect Oriented + Programming
+SWIG has parallels to +Aspect Oriented Software Development (AOP). The +AOP terminology with respect to SWIG typemaps can be viewed as + follows:
-
-- The relevant typemap is shown, but for typemap copying, the - appropriate %typemap or %apply is displayed, for - example, the "check" and "in" typemaps.
-- The typemap modifiers are not shown, eg the noblock=1 - modifier in the "arginit" typemap.
-- The exact %apply statement might look different to what is - in the actual code. For example, the const char* another_value - is not shown as it is not relevant here. Also the types may be - displayed slightly differently - char const * and not -const char*.
+- Cross-cutting concerns: The cross-cutting concerns are the + modularization of the functionality that the typemaps implement, which + is primarily marshalling of types from/to the target language and + C/C++.
+- Advice: The typemap body contains code which is executed + whenever the marshalling is required.
+- Pointcut: The pointcuts are the positions in the wrapper + code that the typemap code is generated into.
+- Aspect: Aspects are the combination of the pointcut and the + advice, hence each typemap is an aspect.
10.4 Code generation rules
-This section describes rules by which typemap code is inserted into - the generated wrapper code.
-10.4.1 Scope
-When a typemap is defined like this:
+SWIG can also be viewed as has having a second set of aspects based + around %feature. Features such as +%exception are also cross-cutting concerns as they encapsulate code + that can be used to add logging or exception handling to any function.
+11.1.8 The rest of this chapter
+The rest of this chapter provides detailed information for people + who want to write new typemaps. This information is of particular + importance to anyone who intends to write a new SWIG target language + module. Power users can also use this information to write application + specific type conversion rules.
+Since typemaps are strongly tied to the underlying C++ type system, + subsequent sections assume that you are reasonably familiar with the + basic details of values, pointers, references, arrays, type qualifiers + (e.g., const), structures, namespaces, templates, and memory + management in C/C++. If not, you would be well-advised to consult a + copy of "The C Programming Language" by Kernighan and Ritchie or "The + C++ Programming Language" by Stroustrup before going any further.
+11.2 Typemap specifications
+This section describes the behavior of the %typemap + directive itself.
+11.2.1 Defining a typemap
+New typemaps are defined using the %typemap declaration. + The general form of this declaration is as follows (parts enclosed in [ + ... ] are optional):
--%typemap(in) int { - $1 = PyInt_AsLong($input); -} +%typemap(method [, modifiers]) typelist code ;the typemap code is inserted into the wrapper function using a new - block scope. In other words, the wrapper code will look like this:
---wrap_whatever() { - ... - // Typemap code - { - arg1 = PyInt_AsLong(obj1); - } - ... +method is a simply a name that specifies what kind of + typemap is being defined. It is usually a name like "in", +"out", or "argout". The purpose of these methods is + described later.
+modifiers is an optional comma separated list of +name="value" values. These are sometimes to attach extra + information to a typemap and is often target-language dependent. They + are also known as typemap attributes.
+typelist is a list of the C++ type patterns that the + typemap will match. The general form of this list is as follows:
++++typelist : typepattern [, typepattern, typepattern, ... ] ; + +typepattern : type [ (parms) ] + | type name [ (parms) ] + | ( typelist ) [ (parms) ] + ++Each type pattern is either a simple type, a simple type and + argument name, or a list of types in the case of multi-argument + typemaps. In addition, each type pattern can be parameterized with a + list of temporary variables (parms). The purpose of these variables + will be explained shortly.
+code specifies the code used in the typemap. Usually this is + C/C++ code, but in the statically typed target languages, such as Java + and C#, this can contain target language code for certain typemaps. It + can take any one of the following forms:
++++code : { ... } + | " ... " + | %{ ... %} ++Note that the preprocessor will expand code within the {} + delimiters, but not in the last two styles of delimiters, see +Preprocessor and Typemaps. Here are some examples of valid typemap + specifications:
++-+/* Simple typemap declarations */ +%typemap(in) int { + $1 = PyInt_AsLong($input); +} +%typemap(in) int "$1 = PyInt_AsLong($input);"; +%typemap(in) int %{ + $1 = PyInt_AsLong($input); +%} + +/* Typemap with extra argument name */ +%typemap(in) int nonnegative { + ... +} + +/* Multiple types in one typemap */ +%typemap(in) int, short, long { + $1 = SvIV($input); +} + +/* Typemap with modifiers */ +%typemap(in,doc="integer") int "$1 = scm_to_int($input);"; + +/* Typemap applied to patterns of multiple arguments */ +%typemap(in) (char *str, int len), + (char *buffer, int size) +{ + $1 = PyString_AsString($input); + $2 = PyString_Size($input); +} + +/* Typemap with extra pattern parameters */ +%typemap(in, numinputs=0) int *output (int temp), + long *output (long temp) +{ + $1 = &temp; }Because the typemap code is enclosed in its own block, it is legal - to declare temporary variables for use during typemap execution. For - example:
+Admittedly, it's not the most readable syntax at first glance. + However, the purpose of the individual pieces will become clear.
+11.2.2 Typemap scope
+Once defined, a typemap remains in effect for all of the + declarations that follow. A typemap may be redefined for different + sections of an input file. For example:
--%typemap(in) short { - long temp; /* Temporary value */ - if (Tcl_GetLongFromObj(interp, $input, &temp) != TCL_OK) { - return TCL_ERROR; - } - $1 = (short) temp; +// typemap1 +%typemap(in) int { +... +} + +int fact(int); // typemap1 +int gcd(int x, int y); // typemap1 + +// typemap2 +%typemap(in) int { +... } + +int isprime(int); // typemap2Of course, any variables that you declare inside a typemap are - destroyed as soon as the typemap code has executed (they are not - visible to other parts of the wrapper function or other typemaps that - might use the same variable names).
-Occasionally, typemap code will be specified using a few alternative - forms. For example:
+One exception to the typemap scoping rules pertains to the +%extend declaration. %extend is used to attach new + declarations to a class or structure definition. Because of this, all + of the declarations in an %extend block are subject to the + typemap rules that are in effect at the point where the class itself is + defined. For example:
--%typemap(in) int "$1 = PyInt_AsLong($input);"; -%typemap(in) int %{ -$1 = PyInt_AsLong($input); -%} -%typemap(in, noblock=1) int { -$1 = PyInt_AsLong($input); +class Foo { + ... +}; + +%typemap(in) int { + ... } + +%extend Foo { + int blah(int x); // typemap has no effect. Declaration is attached to Foo which + // appears before the %typemap declaration. +};These three forms are mainly used for cosmetics--the specified code - is not enclosed inside a block scope when it is emitted. This sometimes - results in a less complicated looking wrapper function. Note that only - the third of the three typemaps have the typemap code passed through - the SWIG preprocessor.
-10.4.2 Declaring new local variables
-Sometimes it is useful to declare a new local variable that exists - within the scope of the entire wrapper function. A good example of this - might be an application in which you wanted to marshal strings. Suppose - you had a C++ function like this
+11.2.3 Copying a typemap
+A typemap is copied by using assignment. For example:
--int foo(std::string *s); +%typemap(in) Integer = int;and you wanted to pass a native string in the target language as an - argument. For instance, in Perl, you wanted the function to work like - this:
-+or this:
+--$x = foo("Hello World"); +%typemap(in) Integer, Number, int32_t = int;To do this, you can't just pass a raw Perl string as the -std::string * argument. Instead, you have to create a temporary -std::string object, copy the Perl string data into it, and then - pass a pointer to the object. To do this, simply specify the typemap - with an extra parameter like this:
+Types are often managed by a collection of different typemaps. For + example:
--%typemap(in) std::string * (std::string temp) { - unsigned int len; - char *s; - s = SvPV($input,len); /* Extract string data */ - temp.assign(s,len); /* Assign to temp */ - $1 = &temp; /* Set argument to point to temp */ -} +%typemap(in) int { ... } +%typemap(out) int { ... } +%typemap(varin) int { ... } +%typemap(varout) int { ... }In this case, temp becomes a local variable in the scope of - the entire wrapper function. For example:
+To copy all of these typemaps to a new type, use %apply. + For example:
--wrap_foo() { - std::string temp; <--- Declaration of temp goes here - ... - - /* Typemap code */ - { - ... - temp.assign(s,len); - ... - } - ... -} +%apply int { Integer }; // Copy all int typemaps to Integer +%apply int { Integer, Number }; // Copy all int typemaps to both Integer and NumberWhen you set temp to a value, it persists for the duration - of the wrapper function and gets cleaned up automatically on exit.
-It is perfectly safe to use more than one typemap involving local - variables in the same declaration. For example, you could declare a - function as :
+The patterns for %apply follow the same rules as for +%typemap. For example:
--void foo(std::string *x, std::string *y, std::string *z); +%apply int *output { Integer *output }; // Typemap with name +%apply (char *buf, int len) { (char *buffer, int size) }; // Multiple argumentsThis is safely handled because SWIG actually renames all local - variable references by appending an argument number suffix. Therefore, - the generated code would actually look like this:
+11.2.4 Deleting a typemap
+A typemap can be deleted by simply defining no code. For example:
--wrap_foo() { - int *arg1; /* Actual arguments */ - int *arg2; - int *arg3; - std::string temp1; /* Locals declared in the typemap */ - std::string temp2; - std::string temp3; - ... - { - char *s; - unsigned int len; - ... - temp1.assign(s,len); - arg1 = *temp1; - } - { - char *s; - unsigned int len; - ... - temp2.assign(s,len); - arg2 = &temp2; - } - { - char *s; - unsigned int len; - ... - temp3.assign(s,len); - arg3 = &temp3; - } - ... -} +%typemap(in) int; // Clears typemap for int +%typemap(in) int, long, short; // Clears typemap for int, long, short +%typemap(in) int *output;Some typemaps do not recognize local variables (or they may simply - not apply). At this time, only typemaps that apply to argument - conversion support this (input typemaps such as the "in" typemap).
-Note:
-When declaring a typemap for multiple types, each type must have its - own local variable declaration.
+The %clear directive clears all typemaps for a given type. + For example:
--%typemap(in) const std::string *, std::string * (std::string temp) // NO! -// only std::string * has a local variable -// const std::string * does not (oops) -.... - -%typemap(in) const std::string * (std::string temp), std::string * (std::string temp) // Correct -.... +%clear int; // Removes all types for int +%clear int *output, long *output;10.4.3 Special variables
-Within all typemaps, the following special variables are expanded. - This is by no means a complete list as some target languages have - additional special variables which are documented in the language - specific chapters.
-- --
-- Variable Meaning - $n A C local variable corresponding to type - n in the typemap pattern. - $argnum Argument number. Only available in typemaps - related to argument conversion - $n_name Argument name - $n_type Real C datatype of type n. -- $n_ltype ltype of type n - $n_mangle Mangled form of type n. For - example _p_Foo - $n_descriptor Type descriptor structure for - type n. For example SWIGTYPE_p_Foo. This is primarily - used when interacting with the run-time type checker (described later). -- $*n_type Real C datatype of type n - with one pointer removed. - $*n_ltype ltype of type n with one - pointer removed. - $*n_mangle Mangled form of type n with - one pointer removed. - $*n_descriptor Type descriptor structure for - type n with one pointer removed. - $&n_type Real C datatype of type n - with one pointer added. - $&n_ltype ltype of type n with one - pointer added. - $&n_mangle Mangled form of type n with - one pointer added. - $&n_descriptor Type descriptor structure for - type n with one pointer added. - $n_basetype Base typename with all pointers and - qualifiers stripped. Within the table, $n refers to a specific type within the - typemap specification. For example, if you write this
+Note: Since SWIG's default behavior is defined by typemaps, + clearing a fundamental type like int will make that type + unusable unless you also define a new set of typemaps immediately after + the clear operation.
+11.2.5 Placement of typemaps
+Typemap declarations can be declared in the global scope, within a + C++ namespace, and within a C++ class. For example:
--%typemap(in) int *INPUT { +%typemap(in) int { + ... +} +namespace std { + class string; + %typemap(in) string { + ... + } } + +class Bar { +public: + typedef const int & const_reference; + %typemap(out) const_reference { + ... + } +};then $1 refers to int *INPUT. If you have a typemap like - this,
+When a typemap appears inside a namespace or class, it stays in + effect until the end of the SWIG input (just like before). However, the + typemap takes the local scope into account. Therefore, this code
--%typemap(in) (int argc, char *argv[]) { - ... +namespace std { + class string; + %typemap(in) string { + ... + } }then $1 refers to int argc and $2 refers to char - *argv[].
-Substitutions related to types and names always fill in values from - the actual code that was matched. This is useful when a typemap might - match multiple C datatype. For example:
+is really defining a typemap for the type std::string. You + could have code like this:
--%typemap(in) int, short, long { - $1 = ($1_ltype) PyInt_AsLong($input); +namespace std { + class string; + %typemap(in) string { /* std::string */ + ... + } +} + +namespace Foo { + class string; + %typemap(in) string { /* Foo::string */ + ... + } }In this case, $1_ltype is replaced with the datatype that - is actually matched.
-When typemap code is emitted, the C/C++ datatype of the special - variables $1 and $2 is always an "ltype." An "ltype" - is simply a type that can legally appear on the left-hand side of a C - assignment operation. Here are a few examples of types and ltypes:
+In this case, there are two completely distinct typemaps that apply + to two completely different types (std::string and +Foo::string).
+It should be noted that for scoping to work, SWIG has to know that +string is a typename defined within a particular namespace. In this + example, this is done using the forward class declaration class + string.
+11.3 Pattern matching rules
+The section describes the pattern matching rules by which C/C++ + datatypes are associated with typemaps. The matching rules can be + observed in practice by using the debugging options also described.
+11.3.1 Basic matching rules
+Typemaps are matched using both a type and a name (typically the + name of a argument). For a given TYPE NAME pair, the following + rules are applied, in order, to find a match. The first typemap found + is used.
++
+- Typemaps that exactly match TYPE and NAME.
+- Typemaps that exactly match TYPE only.
+- If TYPE is a C++ template of type T< TPARMS >, + where TPARMS are the template parameters, the type is stripped + of the template parameters and the following checks are then made: +
++
+- Typemaps that exactly match T and NAME.
+- Typemaps that exactly match T only.
+If TYPE includes qualifiers (const, volatile, etc.), each + qualifier is stripped one at a time to form a new stripped type and the + matching rules above are repeated on the stripped type. The left-most + qualifier is stripped first, resulting in the right-most (or top-level) + qualifier being stripped last. For example int const*const is + first stripped to int *const then int *.
+If TYPE is an array. The following transformation is made:
++
+- Replace all dimensions to [ANY] and look for a generic + array typemap.
+To illustrate, suppose that you had a function like this:
++++int foo(const char *s); ++To find a typemap for the argument const char *s, SWIG will + search for the following typemaps:
--type ltype ------- ---------------- -int int -const int int -const int * int * -int [4] int * -int [4][5] int (*)[5] +const char *s Exact type and name match +const char * Exact type match +char *s Type and name match (qualifier stripped) +char * Type match (qualifier stripped)In most cases a ltype is simply the C datatype with qualifiers - stripped off. In addition, arrays are converted into pointers.
-Variables such as $&1_type and $*1_type are used - to safely modify the type by removing or adding pointers. Although not - needed in most typemaps, these substitutions are sometimes needed to - properly work with typemaps that convert values between pointers and - values.
-If necessary, type related substitutions can also be used when - declaring locals. For example:
+When more than one typemap rule might be defined, only the first + match found is actually used. Here is an example that shows how some of + the basic rules are applied:
--%typemap(in) int * ($*1_type temp) { - temp = PyInt_AsLong($input); - $1 = &temp; +%typemap(in) int *x { + ... typemap 1 +} + +%typemap(in) int * { + ... typemap 2 +} + +%typemap(in) const int *z { + ... typemap 3 +} + +%typemap(in) int [4] { + ... typemap 4 +} + +%typemap(in) int [ANY] { + ... typemap 5 } + +void A(int *x); // int *x rule (typemap 1) +void B(int *y); // int * rule (typemap 2) +void C(const int *x); // int *x rule (typemap 1) +void D(const int *z); // const int *z rule (typemap 3) +void E(int x[4]); // int [4] rule (typemap 4) +void F(int x[1000]); // int [ANY] rule (typemap 5)There is one word of caution about declaring local variables in this - manner. If you declare a local variable using a type substitution such - as $1_ltype temp, it won't work like you expect for arrays and - certain kinds of pointers. For example, if you wrote this,
+Compatibility note: SWIG-2.0.0 introduced stripping the + qualifiers one step at a time. Prior versions stripped all qualifiers + in one step.
+11.3.2 Typedef reductions + matching
+If no match is found using the rules in the previous section, SWIG + applies a typedef reduction to the type and repeats the typemap search + for the reduced type. To illustrate, suppose you had code like this:
--%typemap(in) int [10][20] { - $1_ltype temp; +%typemap(in) int { + ... typemap 1 } + +typedef int Integer; +void blah(Integer x);then the declaration of temp will be expanded as
-+To find the typemap for Integer x, SWIG will first search + for the following typemaps:
+--int (*)[20] temp; +Integer x +IntegerThis is illegal C syntax and won't compile. There is currently no - straightforward way to work around this problem in SWIG due to the way - that typemap code is expanded and processed. However, one possible - workaround is to simply pick an alternative type such as void * - and use casts to get the correct type when needed. For example:
-+Finding no match, it then applies a reduction Integer -> int + to the type and repeats the search.
+--%typemap(in) int [10][20] { - void *temp; - ... - (($1_ltype) temp)[i][j] = x; /* set a value */ - ... -} +int x +int --> match: typemap 1Another approach, which only works for arrays is to use the -$1_basetype substitution. For example:
+Even though two types might be the same via typedef, SWIG allows + typemaps to be defined for each typename independently. This allows for + interesting customization possibilities based solely on the typename + itself. For example, you could write code like this:
--%typemap(in) int [10][20] { - $1_basetype temp[10][20]; - ... - temp[i][j] = x; /* set a value */ - ... +typedef double pdouble; // Positive double + +// typemap 1 +%typemap(in) double { + ... get a double ... } +// typemap 2 +%typemap(in) pdouble { + ... get a positive double ... +} +double sin(double x); // typemap 1 +pdouble sqrt(pdouble x); // typemap 210.4.4 Special - variable macros
-Special variable macros are like macro functions in that they take - one or more input arguments which are used for the macro expansion. - They look like macro/function calls but use the special variable $ - prefix to the macro name. Note that unlike normal macros, the expansion - is not done by the preprocessor, it is done during the SWIG - parsing/compilation stages. The following special variable macros are - available across all language modules.
-10.4.4.1 - $descriptor(type)
-This macro expands into the type descriptor structure for any C/C++ - type specified in type. It behaves like the $1_descriptor - special variable described above except that the type to expand is - taken from the macro argument rather than inferred from the typemap - type. For example, $descriptor(std::vector<int> *) will expand - into SWIGTYPE_p_std__vectorT_int_t. This macro is mostly used - in the scripting target languages and is demonstrated later in the -Run-time type checker usage section.
-10.4.4.2 - $typemap(method, typepattern)
-This macro uses the pattern - matching rules described earlier to lookup and then substitute the - special variable macro with the code in the matched typemap. The - typemap to search for is specified by the arguments, where method - is the typemap method name and typepattern is a type pattern - as per the %typemap specification in the -Defining a typemap section.
-The special variables within the matched typemap are expanded into - those for the matched typemap type, not the typemap within which the - macro is called. In practice, there is little use for this macro in the - scripting target languages. It is mostly used in the target languages - that are statically typed as a way to obtain the target language type - given the C/C++ type and more commonly only when the C++ type is a - template parameter.
-The example below is for C# only and uses some typemap method names - documented in the C# chapter, but it shows some of the possible syntax - variations.
----%typemap(cstype) unsigned long "uint" -%typemap(cstype) unsigned long bb "bool" -%typemap(cscode) BarClass %{ - void foo($typemap(cstype, unsigned long aa) var1, - $typemap(cstype, unsigned long bb) var2, - $typemap(cstype, (unsigned long bb)) var3, - $typemap(cstype, unsigned long) var4) - { - // do something - } -%} --The result is the following expansion
+When reducing the type, only one typedef reduction is applied at a + time. The search process continues to apply reductions until a match is + found or until no more reductions can be made.
+For complicated types, the reduction process can generate a long + list of patterns. Consider the following:
--%typemap(cstype) unsigned long "uint" -%typemap(cstype) unsigned long bb "bool" -%typemap(cscode) BarClass %{ - void foo(uint var1, - bool var2, - bool var3, - uint var4) - { - // do something - } -%} +typedef int Integer; +typedef Integer Row4[4]; +void foo(Row4 rows[10]);10.5 Common typemap methods
-The set of typemaps recognized by a language module may vary. - However, the following typemap methods are nearly universal:
-10.5.1 "in" typemap
-The "in" typemap is used to convert function arguments from the - target language to C. For example:
+To find a match for the Row4 rows[10] argument, SWIG would + check the following patterns, stopping only when it found a match:
--%typemap(in) int { - $1 = PyInt_AsLong($input); -} +Row4 rows[10] +Row4 [10] +Row4 rows[ANY] +Row4 [ANY] + +# Reduce Row4 --> Integer[4] +Integer rows[10][4] +Integer [10][4] +Integer rows[ANY][ANY] +Integer [ANY][ANY] + +# Reduce Integer --> int +int rows[10][4] +int [10][4] +int rows[ANY][ANY] +int [ANY][ANY]The following special variables are available:
+For parameterized types like templates, the situation is even more + complicated. Suppose you had some declarations like this:
--$input - Input object holding value to be converted. -$symname - Name of function/method being wrapped +typedef int Integer; +typedef foo<Integer,Integer> fooii; +void blah(fooii *x);This is probably the most commonly redefined typemap because it can - be used to implement customized conversions.
-In addition, the "in" typemap allows the number of converted - arguments to be specified. The numinputs attributes - facilitates this. For example:
+In this case, the following typemap patterns are searched for the + argument fooii *x:
--// Ignored argument. -%typemap(in, numinputs=0) int *out (int temp) { - $1 = &temp; -} +fooii *x +fooii * + +# Reduce fooii --> foo<Integer,Integer> +foo<Integer,Integer> *x +foo<Integer,Integer> * + +# Reduce Integer -> int +foo<int, Integer> *x +foo<int, Integer> * + +# Reduce Integer -> int +foo<int, int> *x +foo<int, int> *At this time, only zero or one arguments may be converted. When -numinputs is set to 0, the argument is effectively ignored and - cannot be supplied from the target language. The argument is still - required when making the C/C++ call and the above typemap shows the - value used is instead obtained from a locally declared variable called -temp. Usually numinputs is not specified, whereupon the - default value is 1, that is, there is a one to one mapping of the - number of arguments when used from the target language to the C/C++ - call. Multi-argument - typemaps provide a similar concept where the number of arguments - mapped from the target language to C/C++ can be changed for multiple - adjacent C/C++ arguments.
-Compatibility note: Specifying numinputs=0 is the - same as the old "ignore" typemap.
-10.5.2 "typecheck" typemap
-The "typecheck" typemap is used to support overloaded functions and - methods. It merely checks an argument to see whether or not it matches - a specific type. For example:
+Typemap reductions are always applied to the left-most type that + appears. Only when no reductions can be made to the left-most type are + reductions made to other parts of the type. This behavior means that + you could define a typemap for foo<int,Integer>, but a typemap + for foo<Integer,int> would never be matched. Admittedly, this + is rather esoteric--there's little practical reason to write a typemap + quite like that. Of course, you could rely on this to confuse your + coworkers even more.
+As a point of clarification, it is worth emphasizing that typedef + matching is a typedef reduction process only, that is, SWIG does + not search for every single possible typedef. Given a type in a + declaration, it will only reduce the type, it won't build it up looking + for typedefs. For example, given the type Struct, the typemap + below will not be used for the aStruct parameter, because +Struct is fully reduced:
--%typemap(typecheck,precedence=SWIG_TYPECHECK_INTEGER) int { - $1 = PyInt_Check($input) ? 1 : 0; +struct Struct {...}; +typedef Struct StructTypedef; + +%typemap(in) StructTypedef { + ... } + +void go(Struct aStruct);For typechecking, the $1 variable is always a simple integer that is - set to 1 or 0 depending on whether or not the input argument is the - correct type.
-If you define new "in" typemaps and your program uses - overloaded methods, you should also define a collection of "typecheck" - typemaps. More details about this follow in the -Typemaps and overloading section.
-10.5.3 "out" typemap
-The "out" typemap is used to convert function/method return values - from C into the target language. For example:
+11.3.3 Default typemap matching rules
+If the basic pattern matching rules result in no match being made, + even after typedef reductions, the default typemap matching rules are + used to look for a suitable typemap match. These rules match a generic + typemap based on the reserved SWIGTYPE base type. For example + pointers will use SWIGTYPE * and references will use +SWIGTYPE &. More precisely, the rules are based on the C++ class + template partial specialization matching rules used by C++ compilers + when looking for an appropriate partial template specialization. This + means that a match is chosen from the most specialized set of generic + typemap types available. For example, when looking for a match to +int const *, the rules will prefer to match SWIGTYPE const * + if available before matching SWIGTYPE *, before matching +SWIGTYPE.
+Most SWIG language modules use typemaps to define the default + behavior of the C primitive types. This is entirely straightforward. + For example, a set of typemaps for primitives marshalled by value or + const reference are written like this:
--%typemap(out) int { - $result = PyInt_FromLong($1); -} +%typemap(in) int "... convert to int ..."; +%typemap(in) short "... convert to short ..."; +%typemap(in) float "... convert to float ..."; +... +%typemap(in) const int & "... convert ..."; +%typemap(in) const short & "... convert ..."; +%typemap(in) const float & "... convert ..."; +...The following special variables are available.
+Since typemap matching follows all typedef declarations, + any sort of type that is mapped to a primitive type by value or const + reference through typedef will be picked up by one of these + primitive typemaps. Most language modules also define typemaps for char + pointers and char arrays to handle strings, so these non-default types + will also be used in preference as the basic typemap matching rules + provide a better match than the default typemap matching rules.
+Below is a list of the typical default types supplied by language + modules, showing what the "in" typemap would look like:
--$result - Result object returned to target language. -$symname - Name of function/method being wrapped +%typemap(in) SWIGTYPE & { ... default reference handling ... }; +%typemap(in) SWIGTYPE * { ... default pointer handling ... }; +%typemap(in) SWIGTYPE *const { ... default pointer const handling ... }; +%typemap(in) SWIGTYPE *const& { ... default pointer const reference handling ... }; +%typemap(in) SWIGTYPE[ANY] { ... 1D fixed size arrays handlling ... }; +%typemap(in) SWIGTYPE [] { ... unknown sized array handling ... }; +%typemap(in) enum SWIGTYPE { ... default handling for enum values ... }; +%typemap(in) const enum SWIGTYPE & { ... default handling for const enum reference values ... }; +%typemap(in) SWIGTYPE (CLASS::*) { ... default pointer member handling ... }; +%typemap(in) SWIGTYPE { ... simple default handling ... };The "out" typemap supports an optional attribute flag called - "optimal". This is for code optimisation and is detailed in the -Optimal code generation when returning by value section.
-10.5.4 "arginit" typemap
-The "arginit" typemap is used to set the initial value of a function - argument--before any conversion has occurred. This is not normally - necessary, but might be useful in highly specialized applications. For - example:
+If you wanted to change SWIG's default handling for simple pointers, + you would simply redefine the rule for SWIGTYPE *. Note, the + simple default typemap rule is used to match against simple types that + don't match any other rules:
--// Set argument to NULL before any conversion occurs -%typemap(arginit) int *data { - $1 = NULL; -} +%typemap(in) SWIGTYPE { ... simple default handling ... }10.5.5 "default" typemap
-The "default" typemap is used to turn an argument into a default - argument. For example:
+This typemap is important because it is the rule that gets triggered + when call or return by value is used. For instance, if you have a + declaration like this:
--%typemap(default) int flags { - $1 = DEFAULT_FLAGS; -} -... -int foo(int x, int y, int flags); +double dot_product(Vector a, Vector b);The primary use of this typemap is to either change the wrapping of - default arguments or specify a default argument in a language where - they aren't supported (like C). Target languages that do not support - optional arguments, such as Java and C#, effectively ignore the value - specified by this typemap as all arguments must be given.
-Once a default typemap has been applied to an argument, all - arguments that follow must have default values. See the -Default/optional arguments section for further information on - default argument wrapping.
-10.5.6 "check" typemap
-The "check" typemap is used to supply value checking code during - argument conversion. The typemap is applied after arguments - have been converted. For example:
+The Vector type will usually just get matched against +SWIGTYPE. The default implementation of SWIGTYPE is to + convert the value into pointers (as described in + this earlier section).
+By redefining SWIGTYPE it may be possible to implement + other behavior. For example, if you cleared all typemaps for +SWIGTYPE, SWIG simply won't wrap any unknown datatype (which might + be useful for debugging). Alternatively, you might modify SWIGTYPE to + marshal objects into strings instead of converting them to pointers.
+Let's consider an example where the following typemaps are defined + and SWIG is looking for the best match for the enum shown below:
--%typemap(check) int positive { - if ($1 <= 0) { - SWIG_exception(SWIG_ValueError,"Expected positive value."); - } -} +%typemap(in) const Hello & { ... } +%typemap(in) const enum SWIGTYPE & { ... } +%typemap(in) enum SWIGTYPE & { ... } +%typemap(in) SWIGTYPE & { ... } +%typemap(in) SWIGTYPE { ... } + +enum Hello {}; +const Hello &hi;10.5.7 "argout" typemap
-The "argout" typemap is used to return values from arguments. This - is most commonly used to write wrappers for C/C++ functions that need - to return multiple values. The "argout" typemap is almost always - combined with an "in" typemap---possibly to ignore the input value. For - example:
+The typemap at the top of the list will be chosen, not because it is + defined first, but because it is the closest match for the type being + wrapped. If any of the typemaps in the above list were not defined, + then the next one on the list would have precedence.
+The best way to explore the default typemaps is to look at the ones + already defined for a particular language module. Typemap definitions + are usually found in the SWIG library in a file such as java.swg +, csharp.swg etc. However, for many of the target languages the + typemaps are hidden behind complicated macros, so the best way to view + the default typemaps, or any typemaps for that matter, is to look at + the preprocessed output by running swig -E on any interface + file. Finally the best way to view the typemap matching rules in action + is via the debugging typemap + pattern matching options covered later on.
+Compatibility note: The default typemap matching rules were + modified in SWIG-2.0.0 from a slightly simpler scheme to match the + current C++ class template partial specialization matching rules.
+11.3.4 + Multi-arguments typemaps
+When multi-argument typemaps are specified, they take precedence + over any typemaps specified for a single type. For example:
--/* Set the input argument to point to a temporary variable */ -%typemap(in, numinputs=0) int *out (int temp) { - $1 = &temp; +%typemap(in) (char *buffer, int len) { + // typemap 1 } -%typemap(argout) int *out { - // Append output value $1 to $result - ... +%typemap(in) char *buffer { + // typemap 2 } + +void foo(char *buffer, int len, int count); // (char *buffer, int len) +void bar(char *buffer, int blah); // char *bufferThe following special variables are available.
-+Multi-argument typemaps are also more restrictive in the way that + they are matched. Currently, the first argument follows the matching + rules described in the previous section, but all subsequent arguments + must match exactly.
+11.3.5 Matching + rules compared to C++ templates
+For those intimately familiar with C++ templates, a comparison of + the typemap matching rules and template type deduction is interesting. + The two areas considered are firstly the default typemaps and their + similarities to partial template specialization and secondly, + non-default typemaps and their similarities to full template + specialization.
+For default (SWIGTYPE) typemaps the rules are inspired by C++ class + template partial specialization. For example, given partial + specialization for T const& :
+--$result - Result object returned to target language. -$input - The original input object passed. -$symname - Name of function/method being wrapped +template <typename T> struct X { void a(); }; +template <typename T> struct X< T const& > { void b(); };The code supplied to the "argout" typemap is always placed after the - "out" typemap. If multiple return values are used, the extra return - values are often appended to return value of the function.
-See the typemaps.i library file for examples.
-10.5.8 "freearg" typemap
-The "freearg" typemap is used to cleanup argument data. It is only - used when an argument might have allocated resources that need to be - cleaned up when the wrapper function exits. The "freearg" typemap - usually cleans up argument resources allocated by the "in" typemap. For - example:
+The full (unspecialized) template is matched with most types, such + as:
--// Get a list of integers -%typemap(in) int *items { - int nitems = Length($input); - $1 = (int *) malloc(sizeof(int)*nitems); -} -// Free the list -%typemap(freearg) int *items { - free($1); -} +X< int & > x1; x1.a();The "freearg" typemap inserted at the end of the wrapper function, - just before control is returned back to the target language. This code - is also placed into a special variable $cleanup that may be - used in other typemaps whenever a wrapper function needs to abort - prematurely.
-10.5.9 "newfree" typemap
-The "newfree" typemap is used in conjunction with the %newobject - directive and is used to deallocate memory used by the return result of - a function. For example:
+and the following all match the T const& partial + specialization:
--%typemap(newfree) string * { - delete $1; -} -%typemap(out) string * { - $result = PyString_FromString($1->c_str()); -} -... - -%newobject foo; -... -string *foo(); +X< int *const& > x2; x2.b(); +X< int const*const& > x3; x3.b(); +X< int const& > x4; x4.b();See Object ownership and - %newobject for further details.
-10.5.10 "memberin" typemap
-The "memberin" typemap is used to copy data from an already - converted input value into a structure member. It is typically - used to handle array members and other special cases. For example:
+Now, given just these two default typemaps, where T is analogous to + SWIGTYPE:
--%typemap(memberin) int [4] { - memmove($1, $input, 4*sizeof(int)); -} +%typemap(...) SWIGTYPE { ... } +%typemap(...) SWIGTYPE const& { ... }It is rarely necessary to write "memberin" typemaps---SWIG already - provides a default implementation for arrays, strings, and other - objects.
-10.5.11 "varin" typemap
-The "varin" typemap is used to convert objects in the target - language to C for the purposes of assigning to a C/C++ global variable. - This is implementation specific.
-10.5.12 "varout" typemap
-The "varout" typemap is used to convert a C/C++ object to an object - in the target language when reading a C/C++ global variable. This is - implementation specific.
-10.5.13 "throws" typemap
-The "throws" typemap is only used when SWIG parses a C++ method with - an exception specification or has the %catches feature - attached to the method. It provides a default mechanism for handling - C++ methods that have declared the exceptions they will throw. The - purpose of this typemap is to convert a C++ exception into an error or - exception in the target language. It is slightly different to the other - typemaps as it is based around the exception type rather than the type - of a parameter or variable. For example:
+The generic default typemap SWIGTYPE is used with most + types, such as
--%typemap(throws) const char * %{ - PyErr_SetString(PyExc_RuntimeError, $1); - SWIG_fail; -%} -void bar() throw (const char *); +int &As can be seen from the generated code below, SWIG generates an - exception handler with the catch block comprising the "throws" typemap - content.
+and the following all match the SWIGTYPE const& typemap, + just like the partial template matching:
--... -try { - bar(); -} -catch(char const *_e) { - PyErr_SetString(PyExc_RuntimeError, _e); - SWIG_fail; - -} -... +int *const& +int const*const& +int const&Note that if your methods do not have an exception specification yet - they do throw exceptions, SWIG cannot know how to deal with them. For a - neat way to handle these, see the -Exception handling with %exception section.
-10.6 Some typemap examples
-This section contains a few examples. Consult language module - documentation for more examples.
-10.6.1 Typemaps for arrays
-A common use of typemaps is to provide support for C arrays - appearing both as arguments to functions and as structure members.
-For example, suppose you had a function like this:
+Note that the template and typemap matching rules are not identical + for all default typemaps though, for example, with arrays.
+For non-default typemaps, one might expect SWIG to follow the fully + specialized template rules. This is nearly the case, but not quite. + Consider a very similar example to the earlier partially specialized + template but this time there is a fully specialized template:
--void set_vector(int type, float value[4]); +template <typename T> struct Y { void a(); }; +template <> struct Y< int const & > { void b(); };If you wanted to handle float value[4] as a list of floats, - you might write a typemap similar to this:
+Only the one type matches the specialized template exactly:
-- -%typemap(in) float value[4] (float temp[4]) { - int i; - if (!PySequence_Check($input)) { - PyErr_SetString(PyExc_ValueError,"Expected a sequence"); - return NULL; - } - if (PySequence_Length($input) != 4) { - PyErr_SetString(PyExc_ValueError,"Size mismatch. Expected 4 elements"); - return NULL; - } - for (i = 0; i < 4; i++) { - PyObject *o = PySequence_GetItem($input,i); - if (PyNumber_Check(o)) { - temp[i] = (float) PyFloat_AsDouble(o); - } else { - PyErr_SetString(PyExc_ValueError,"Sequence elements must be numbers"); - return NULL; - } - } - $1 = temp; -} +Y< int & > y1; y1.a(); +Y< int *const& > y2; y2.a(); +Y< int const *const& > y3; y3.a(); +Y< int const& > y4; y4.b(); // fully specialized matchIn this example, the variable temp allocates a small array - on the C stack. The typemap then populates this array and passes it to - the underlying C function.
-When used from Python, the typemap allows the following type of - function call:
-+Given typemaps with the same types used for the template declared + above, where T is again analogous to SWIGTYPE:
+-->>> set_vector(type, [ 1, 2.5, 5, 20 ]) +%typemap(...) SWIGTYPE { ... } +%typemap(...) int const& { ... }If you wanted to generalize the typemap to apply to arrays of all - dimensions you might write this:
+The comparison between non-default typemaps and fully specialized + single parameter templates turns out to be the same, as just the one + type will match the non-default typemap:
--%typemap(in) float value[ANY] (float temp[$1_dim0]) { - int i; - if (!PySequence_Check($input)) { - PyErr_SetString(PyExc_ValueError,"Expected a sequence"); - return NULL; - } - if (PySequence_Length($input) != $1_dim0) { - PyErr_SetString(PyExc_ValueError,"Size mismatch. Expected $1_dim0 elements"); - return NULL; - } - for (i = 0; i < $1_dim0; i++) { - PyObject *o = PySequence_GetItem($input,i); - if (PyNumber_Check(o)) { - temp[i] = (float) PyFloat_AsDouble(o); - } else { - PyErr_SetString(PyExc_ValueError,"Sequence elements must be numbers"); - return NULL; - } - } - $1 = temp; -} +int & +int *const& +int const*const& +int const& // matches non-default typemap int const&In this example, the special variable $1_dim0 is expanded - with the actual array dimensions. Multidimensional arrays can be - matched in a similar manner. For example:
+However, if a non-const type is used instead:
--%typemap(in) float matrix[ANY][ANY] (float temp[$1_dim0][$1_dim1]) { - ... convert a 2d array ... -} +%typemap(...) SWIGTYPE { ... } +%typemap(...) int & { ... }For large arrays, it may be impractical to allocate storage on the - stack using a temporary variable as shown. To work with heap allocated - data, the following technique can be used.
+then there is a clear difference to template matching as both the + const and non-const types match the typemap:
--%typemap(in) float value[ANY] { - int i; - if (!PySequence_Check($input)) { - PyErr_SetString(PyExc_ValueError,"Expected a sequence"); - return NULL; - } - if (PySequence_Length($input) != $1_dim0) { - PyErr_SetString(PyExc_ValueError,"Size mismatch. Expected $1_dim0 elements"); - return NULL; - } - $1 = (float *) malloc($1_dim0*sizeof(float)); - for (i = 0; i < $1_dim0; i++) { - PyObject *o = PySequence_GetItem($input,i); - if (PyNumber_Check(o)) { - $1[i] = (float) PyFloat_AsDouble(o); - } else { - PyErr_SetString(PyExc_ValueError,"Sequence elements must be numbers"); - free($1); - return NULL; - } - } -} -%typemap(freearg) float value[ANY] { - if ($1) free($1); -} +int & // matches non-default typemap int & +int *const& +int const*const& +int const& // matches non-default typemap int &In this case, an array is allocated using malloc. The -freearg typemap is then used to release the argument after the - function has been called.
-Another common use of array typemaps is to provide support for array - structure members. Due to subtle differences between pointers and - arrays in C, you can't just "assign" to a array structure member. - Instead, you have to explicitly copy elements into the array. For - example, suppose you had a structure like this:
+There are other subtle differences such as typedef handling, but at + least it should be clear that the typemap matching rules are similar to + those for specialized template handling.
+11.3.6 Debugging typemap pattern + matching
+There are two useful debug command line options available for + debugging typemaps, -debug-tmsearch and -debug-tmused +.
+The -debug-tmsearch option is a verbose option for + debugging typemap searches. This can be very useful for watching the + pattern matching process in action and for debugging which typemaps are + used. The option displays all the typemaps and types that are looked + for until a successful pattern match is made. As the display includes + searches for each and every type needed for wrapping, the amount of + information displayed can be large. Normally you would manually search + through the displayed information for the particular type that you are + interested in.
+For example, consider some of the code used in the +Typedef reductions section already covered:
--struct SomeObject { - float value[4]; - ... -}; +typedef int Integer; +typedef Integer Row4[4]; +void foo(Row4 rows[10]);When SWIG runs, it won't produce any code to set the vec - member. You may even get a warning message like this:
+A sample of the debugging output is shown below for the "in" + typemap:
--$ swig -python example.i -example.i:10: Warning 462: Unable to set variable of type float [4]. +swig -perl -debug-tmsearch example.i +... +example.h:3: Searching for a suitable 'in' typemap for: Row4 rows[10] + Looking for: Row4 rows[10] + Looking for: Row4 [10] + Looking for: Row4 rows[ANY] + Looking for: Row4 [ANY] + Looking for: Integer rows[10][4] + Looking for: Integer [10][4] + Looking for: Integer rows[ANY][ANY] + Looking for: Integer [ANY][ANY] + Looking for: int rows[10][4] + Looking for: int [10][4] + Looking for: int rows[ANY][ANY] + Looking for: int [ANY][ANY] + Looking for: SWIGTYPE rows[ANY][ANY] + Looking for: SWIGTYPE [ANY][ANY] + Looking for: SWIGTYPE rows[ANY][] + Looking for: SWIGTYPE [ANY][] + Looking for: SWIGTYPE *rows[ANY] + Looking for: SWIGTYPE *[ANY] + Looking for: SWIGTYPE rows[ANY] + Looking for: SWIGTYPE [ANY] + Looking for: SWIGTYPE rows[] + Looking for: SWIGTYPE [] + Using: %typemap(in) SWIGTYPE [] +...These warning messages indicate that SWIG does not know how you want - to set the vec field.
-To fix this, you can supply a special "memberin" typemap like this:
+showing that the best default match supplied by SWIG is the +SWIGTYPE [] typemap. As the example shows, the successful match + displays the used typemap source including typemap method, type and + optional name in one of these simplified formats:
++
+- Using: %typemap(method) type name
+- Using: %typemap(method) type name = type2 name2
+- Using: %apply type2 name2 { type name }
+This information might meet your debugging needs, however, you might + want to analyze further. If you next invoke SWIG with the -E + option to display the preprocessed output, and search for the + particular typemap used, you'll find the full typemap contents (example + shown below for Python):
--%typemap(memberin) float [ANY] { - int i; - for (i = 0; i < $1_dim0; i++) { - $1[i] = $input[i]; - } +%typemap(in, noblock=1) SWIGTYPE [] (void *argp = 0, int res = 0) { + res = SWIG_ConvertPtr($input, &argp,$descriptor, $disown | 0 ); + if (!SWIG_IsOK(res)) { + SWIG_exception_fail(SWIG_ArgError(res), "in method '" "$symname" "', argument " + "$argnum"" of type '" "$type""'"); + } + $1 = ($ltype)(argp); }The memberin typemap is used to set a structure member from data - that has already been converted from the target language to C. In this - case, $input is the local variable in which converted input - data is stored. This typemap then copies this data into the structure.
-When combined with the earlier typemaps for arrays, the combination - of the "in" and "memberin" typemap allows the following usage:
-+The generated code for the foo wrapper will then contain + the snippets of the typemap with the special variables expanded. The + rest of this chapter will need reading though to fully understand all + of this, however, the relevant parts of the generated code for the + above typemap can be seen below:
+-->>> s = SomeObject() ->>> s.x = [1, 2.5, 5, 10] +SWIGINTERN PyObject *_wrap_foo(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { +... + void *argp1 = 0 ; + int res1 = 0 ; +... + res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_a_4__int, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "foo" "', argument " + "1"" of type '" "int [10][4]""'"); + } + arg1 = (int (*)[4])(argp1); +... +}Related to structure member input, it may be desirable to return - structure members as a new kind of object. For example, in this - example, you will get very odd program behavior where the structure - member can be set nicely, but reading the member simply returns a - pointer:
-+Searches for multi-argument typemaps are not mentioned unless a + matching multi-argument typemap does actually exist. For example, the + output for the code in the +earlier multi-arguments section is as follows:
+-->>> s = SomeObject() ->>> s.x = [1, 2.5, 5, 10] ->>> print s.x -_1008fea8_p_float ->>> +... +example.h:39: Searching for a suitable 'in' typemap for: char *buffer + Looking for: char *buffer + Multi-argument typemap found... + Using: %typemap(in) (char *buffer,int len) +...To fix this, you can write an "out" typemap. For example:
+The second option for debugging is -debug-tmused and this + displays the typemaps used. This option is a less verbose version of + the -debug-tmsearch option as it only displays each + successfully found typemap on a separate single line. The output + displays the type, and name if present, the typemap method in brackets + and then the actual typemap used in the same simplified format output + by the -debug-tmsearch option. Below is the output for the + example code at the start of this section on debugging.
++++$ swig -perl -debug-tmused example.i +example.h:3: Typemap for Row4 rows[10] (in) : %typemap(in) SWIGTYPE [] +example.h:3: Typemap for Row4 rows[10] (typecheck) : %typemap(typecheck) SWIGTYPE * +example.h:3: Typemap for Row4 rows[10] (freearg) : %typemap(freearg) SWIGTYPE [] +example.h:3: Typemap for void foo (out) : %typemap(out) void ++Now, consider the following interface file:
--%typemap(out) float [ANY] { - int i; - $result = PyList_New($1_dim0); - for (i = 0; i < $1_dim0; i++) { - PyObject *o = PyFloat_FromDouble((double) $1[i]); - PyList_SetItem($result,i,o); +%module example + +%{ +void set_value(const char* val) {} +%} + +%typemap(check) char *NON_NULL { + if (!$1) { + /* ... error handling ... */ } } + +// use default pointer handling instead of strings +%apply SWIGTYPE * { const char* val, const char* another_value } + +%typemap(check) const char* val = char* NON_NULL; + +%typemap(arginit, noblock=1) const char* val { + $1 = ""; +} + +void set_value(const char* val); +Now, you will find that member access is quite nice:
-+and the output debug:
+-->>> s = SomeObject() ->>> s.x = [1, 2.5, 5, 10] ->>> print s.x -[ 1, 2.5, 5, 10] +swig -perl5 -debug-tmused example.i +example.i:21: Typemap for char const *val (arginit) : %typemap(arginit) char const *val +example.i:21: Typemap for char const *val (in) : %apply SWIGTYPE * { char const *val } +example.i:21: Typemap for char const *val (typecheck) : %apply SWIGTYPE * { char const *val } +example.i:21: Typemap for char const *val (check) : %typemap(check) char const *val = char *NON_NULL +example.i:21: Typemap for char const *val (freearg) : %apply SWIGTYPE * { char const *val } +example.i:21: Typemap for void set_value (out) : %typemap(out) voidCompatibility Note: SWIG1.1 used to provide a special - "memberout" typemap. However, it was mostly useless and has since been - eliminated. To return structure members, simply use the "out" typemap.
-10.6.2 Implementing constraints with - typemaps
-One particularly interesting application of typemaps is the - implementation of argument constraints. This can be done with the - "check" typemap. When used, this allows you to provide code for - checking the values of function arguments. For example:
+The following observations about what is displayed can be noted (the + same applies for -debug-tmsearch):
++
+- The relevant typemap is shown, but for typemap copying, the + appropriate %typemap or %apply is displayed, for + example, the "check" and "in" typemaps.
+- The typemap modifiers are not shown, eg the noblock=1 + modifier in the "arginit" typemap.
+- The exact %apply statement might look different to what is + in the actual code. For example, the const char* another_value + is not shown as it is not relevant here. Also the types may be + displayed slightly differently - char const * and not +const char*.
+11.4 Code generation rules
+This section describes rules by which typemap code is inserted into + the generated wrapper code.
+11.4.1 Scope
+When a typemap is defined like this:
--%module math - -%typemap(check) double posdouble { - if ($1 < 0) { - croak("Expecting a positive number"); - } +%typemap(in) int { + $1 = PyInt_AsLong($input); } - -... -double sqrt(double posdouble); -This provides a sanity check to your wrapper function. If a negative - number is passed to this function, a Perl exception will be raised and - your program terminated with an error message.
-This kind of checking can be particularly useful when working with - pointers. For example:
+the typemap code is inserted into the wrapper function using a new + block scope. In other words, the wrapper code will look like this:
--%typemap(check) Vector * { - if ($1 == 0) { - PyErr_SetString(PyExc_TypeError,"NULL Pointer not allowed"); - return NULL; - } +wrap_whatever() { + ... + // Typemap code + { + arg1 = PyInt_AsLong(obj1); + } + ... } -will prevent any function involving a Vector * from - accepting a NULL pointer. As a result, SWIG can often prevent a - potential segmentation faults or other run-time problems by raising an - exception rather than blindly passing values to the underlying C/C++ - program.
-10.7 Typemaps for multiple target - languages
-The code within typemaps is usually language dependent, however, - many target languages support the same typemaps. In order to - distinguish typemaps across different languages, the preprocessor - should be used. For example, the "in" typemap for Perl and Ruby could - be written as:
+Because the typemap code is enclosed in its own block, it is legal + to declare temporary variables for use during typemap execution. For + example:
--#if defined(SWIGPERL) - %typemap(in) int "$1 = ($1_ltype) SvIV($input);" -#elif defined(SWIGRUBY) - %typemap(in) int "$1 = NUM2INT($input);" -#else - #warning no "in" typemap defined -#endif +%typemap(in) short { + long temp; /* Temporary value */ + if (Tcl_GetLongFromObj(interp, $input, &temp) != TCL_OK) { + return TCL_ERROR; + } + $1 = (short) temp; +}The full set of language specific macros is defined in the -Conditional Compilation section. The example above also shows a - common approach of issuing a warning for an as yet unsupported - language.
-Compatibility note: In SWIG-1.1 different languages could be - distinguished with the language name being put within the %typemap - directive, for example, -
-
%typemap(ruby,in) int "$1 = NUM2INT($input);".10.8 Optimal code generation when - returning by value
-The "out" typemap is the main typemap for return types. This typemap - supports an optional attribute flag called "optimal", which is for - reducing temporary variables and the amount of generated code, thereby - giving the compiler the opportunity to use return value optimization - for generating faster executing code. It only really makes a difference - when returning objects by value and has some limitations on usage, as - explained later on.
-When a function returns an object by value, SWIG generates code that - instantiates the default type on the stack then assigns the value - returned by the function call to it. A copy of this object is then made - on the heap and this is what is ultimately stored and used from the - target language. This will be clearer considering an example. Consider - running the following code through SWIG:
+Of course, any variables that you declare inside a typemap are + destroyed as soon as the typemap code has executed (they are not + visible to other parts of the wrapper function or other typemaps that + might use the same variable names).
+Occasionally, typemap code will be specified using a few alternative + forms. For example:
--%typemap(out) SWIGTYPE %{ - $result = new $1_ltype((const $1_ltype &)$1); -%} - -%inline %{ -#include <iostream> -using namespace std; - -struct XX { - XX() { cout << "XX()" << endl; } - XX(int i) { cout << "XX(" << i << ")" << endl; } - XX(const XX &other) { cout << "XX(const XX &)" << endl; } - XX & operator =(const XX &other) { cout << "operator=(const XX &)" << endl; return *this; } - ~XX() { cout << "~XX()" << endl; } - static XX create() { - return XX(0); - } -}; +%typemap(in) int "$1 = PyInt_AsLong($input);"; +%typemap(in) int %{ +$1 = PyInt_AsLong($input); %} +%typemap(in, noblock=1) int { +$1 = PyInt_AsLong($input); +}The "out" typemap shown is the default typemap for C# when returning - objects by value. When making a call to XX::create() from C#, - the output is as follows:
----XX() -XX(0) -operator=(const XX &) -~XX() -XX(const XX &) -~XX() -~XX() --Note that three objects are being created as well as an assignment. - Wouldn't it be great if the XX::create() method was the only - time a constructor was called? As the method returns by value, this is - asking a lot and the code that SWIG generates by default makes it - impossible for the compiler to use return value optimisation (RVO) -. However, this is where the "optimal" attribute in the "out" typemap - can help out. If the typemap code is kept the same and just the - "optimal" attribute specified like this:
+These three forms are mainly used for cosmetics--the specified code + is not enclosed inside a block scope when it is emitted. This sometimes + results in a less complicated looking wrapper function. Note that only + the third of the three typemaps have the typemap code passed through + the SWIG preprocessor.
+11.4.2 Declaring new local variables
+Sometimes it is useful to declare a new local variable that exists + within the scope of the entire wrapper function. A good example of this + might be an application in which you wanted to marshal strings. Suppose + you had a C++ function like this
--%typemap(out, optimal="1") SWIGTYPE %{ - $result = new $1_ltype((const $1_ltype &)$1); -%} +int foo(std::string *s);then when the code is run again, the output is simply:
+and you wanted to pass a native string in the target language as an + argument. For instance, in Perl, you wanted the function to work like + this:
--XX(0) -~XX() +$x = foo("Hello World");How the "optimal" attribute works is best explained using the - generated code. Without "optimal", the generated code is:
+To do this, you can't just pass a raw Perl string as the +std::string * argument. Instead, you have to create a temporary +std::string object, copy the Perl string data into it, and then + pass a pointer to the object. To do this, simply specify the typemap + with an extra parameter like this:
--SWIGEXPORT void * SWIGSTDCALL CSharp_XX_create() { - void * jresult ; - XX result; - result = XX::create(); - jresult = new XX((const XX &)result); - return jresult; +%typemap(in) std::string * (std::string temp) { + unsigned int len; + char *s; + s = SvPV($input,len); /* Extract string data */ + temp.assign(s,len); /* Assign to temp */ + $1 = &temp; /* Set argument to point to temp */ } -With the "optimal" attribute, the code is:
+In this case, temp becomes a local variable in the scope of + the entire wrapper function. For example:
--SWIGEXPORT void * SWIGSTDCALL CSharp_XX_create() { - void * jresult ; - jresult = new XX((const XX &)XX::create()); - return jresult; +wrap_foo() { + std::string temp; <--- Declaration of temp goes here + ... + + /* Typemap code */ + { + ... + temp.assign(s,len); + ... + } + ... }The major difference is the result temporary variable - holding the value returned from XX::create() is no longer - generated and instead the copy constructor call is made directly from - the value returned by XX::create(). With modern compilers - implementing RVO, the copy is not actually done, in fact the object is - never created on the stack in XX::create() at all, it is - simply created directly on the heap. In the first instance, the $1 - special variable in the typemap is expanded into result. In - the second instance, $1 is expanded into XX::create() - and this is essentially what the "optimal" attribute is telling SWIG to - do.
-The "optimal" attribute optimisation is not turned on by default as - it has a number of restrictions. Firstly, some code cannot be condensed - into a simple call for passing into the copy constructor. One common - occurrence is when %exception is - used. Consider adding the following %exception to the example:
+When you set temp to a value, it persists for the duration + of the wrapper function and gets cleaned up automatically on exit.
+It is perfectly safe to use more than one typemap involving local + variables in the same declaration. For example, you could declare a + function as :
--%exception XX::create() %{ -try { - $action -} catch(const std::exception &e) { - cout << e.what() << endl; -} -%} +void foo(std::string *x, std::string *y, std::string *z);SWIG can detect when the "optimal" attribute cannot be used and will - ignore it and in this case will issue the following warning:
-+This is safely handled because SWIG actually renames all local + variable references by appending an argument number suffix. Therefore, + the generated code would actually look like this:
+--example.i:28: Warning 474: Method XX::create() usage of the optimal attribute ignored -example.i:14: Warning 474: in the out typemap as the following cannot be used to generate -optimal code: -try { - result = XX::create(); -} catch(const std::exception &e) { - cout << e.what() << endl; +wrap_foo() { + int *arg1; /* Actual arguments */ + int *arg2; + int *arg3; + std::string temp1; /* Locals declared in the typemap */ + std::string temp2; + std::string temp3; + ... + { + char *s; + unsigned int len; + ... + temp1.assign(s,len); + arg1 = *temp1; + } + { + char *s; + unsigned int len; + ... + temp2.assign(s,len); + arg2 = &temp2; + } + { + char *s; + unsigned int len; + ... + temp3.assign(s,len); + arg3 = &temp3; + } + ... }It should be clear that the above code cannot be used as the - argument to the copy constructor call, that is, for the $1 - substitution.
-Secondly, if the typemaps uses $1 more than once, then - multiple calls to the wrapped function will be made. Obviously that is - not very optimal. In fact SWIG attempts to detect this and will issue a - warning something like:
-+There is an exception: if the variable name starts with the +_global_ prefix, the argument number is not appended. Such + variables can be used throughout the generated wrapper function. For + example, the above typemap could be rewritten to use _global_temp + instead of temp and the generated code would then contain a + single _global_temp variable instead of temp1, +temp2 and temp3:
+--example.i:21: Warning 475: Multiple calls to XX::create() might be generated due to -example.i:7: Warning 475: optimal attribute usage in the out typemap. +%typemap(in) std::string * (std::string _global_temp) { + ... as above ... +}However, it doesn't always get it right, for example when $1 - is within some commented out code.
-10.9 Multi-argument - typemaps
-So far, the typemaps presented have focused on the problem of - dealing with single values. For example, converting a single input - object to a single argument in a function call. However, certain - conversion problems are difficult to handle in this manner. As an - example, consider the example at the very beginning of this chapter:
+Some typemaps do not recognize local variables (or they may simply + not apply). At this time, only typemaps that apply to argument + conversion support this (input typemaps such as the "in" typemap).
+Note:
+When declaring a typemap for multiple types, each type must have its + own local variable declaration.
--int foo(int argc, char *argv[]); +%typemap(in) const std::string *, std::string * (std::string temp) // NO! +// only std::string * has a local variable +// const std::string * does not (oops) +.... + +%typemap(in) const std::string * (std::string temp), std::string * (std::string temp) // Correct +....Suppose that you wanted to wrap this function so that it accepted a - single list of strings like this:
-+11.4.3 Special variables
+Within all typemaps, the following special variables are expanded. + This is by no means a complete list as some target languages have + additional special variables which are documented in the language + specific chapters.
++ ++
++ Variable Meaning + $n A C local variable corresponding to type + n in the typemap pattern. + $argnum Argument number. Only available in typemaps + related to argument conversion + $n_name Argument name + $n_type Real C datatype of type n. ++ $n_ltype ltype of type n + $n_mangle Mangled form of type n. For + example _p_Foo + $n_descriptor Type descriptor structure for + type n. For example SWIGTYPE_p_Foo. This is primarily + used when interacting with the run-time type checker (described later). ++ $*n_type Real C datatype of type n + with one pointer removed. + $*n_ltype ltype of type n with one + pointer removed. + $*n_mangle Mangled form of type n with + one pointer removed. + $*n_descriptor Type descriptor structure for + type n with one pointer removed. + $&n_type Real C datatype of type n + with one pointer added. + $&n_ltype ltype of type n with one + pointer added. + $&n_mangle Mangled form of type n with + one pointer added. + $&n_descriptor Type descriptor structure for + type n with one pointer added. + $n_basetype Base typename with all pointers and + qualifiers stripped. Within the table, $n refers to a specific type within the + typemap specification. For example, if you write this
+-->>> foo(["ale","lager","stout"]) +%typemap(in) int *INPUT { + +}To do this, you not only need to map a list of strings to char - *argv[], but the value of int argc is implicitly - determined by the length of the list. Using only simple typemaps, this - type of conversion is possible, but extremely painful. Multi-argument - typemaps help in this situation.
-A multi-argument typemap is a conversion rule that specifies how to - convert a single object in the target language to a set of - consecutive function arguments in C/C++. For example, the following - multi-argument maps perform the conversion described for the above - example:
+then $1 refers to int *INPUT. If you have a typemap like + this,
-%typemap(in) (int argc, char *argv[]) { - int i; - if (!PyList_Check($input)) { - PyErr_SetString(PyExc_ValueError, "Expecting a list"); - return NULL; - } - $1 = PyList_Size($input); - $2 = (char **) malloc(($1+1)*sizeof(char *)); - for (i = 0; i < $1; i++) { - PyObject *s = PyList_GetItem($input,i); - if (!PyString_Check(s)) { - free($2); - PyErr_SetString(PyExc_ValueError, "List items must be strings"); - return NULL; - } - $2[i] = PyString_AsString(s); - } - $2[i] = 0; -} - -%typemap(freearg) (int argc, char *argv[]) { - if ($2) free($2); + ... }A multi-argument map is always specified by surrounding the - arguments with parentheses as shown. For example:
+then $1 refers to int argc and $2 refers to char + *argv[].
+Substitutions related to types and names always fill in values from + the actual code that was matched. This is useful when a typemap might + match multiple C datatype. For example:
--%typemap(in) (int argc, char *argv[]) { ... } +%typemap(in) int, short, long { + $1 = ($1_ltype) PyInt_AsLong($input); +}Within the typemap code, the variables $1, $2, and - so forth refer to each type in the map. All of the usual substitutions - apply--just use the appropriate $1 or $2 prefix on - the variable name (e.g., $2_type, $1_ltype, etc.)
-Multi-argument typemaps always have precedence over simple typemaps - and SWIG always performs longest-match searching. Therefore, you will - get the following behavior:
-+In this case, $1_ltype is replaced with the datatype that + is actually matched.
+When typemap code is emitted, the C/C++ datatype of the special + variables $1 and $2 is always an "ltype." An "ltype" + is simply a type that can legally appear on the left-hand side of a C + assignment operation. Here are a few examples of types and ltypes:
+--%typemap(in) int argc { ... typemap 1 ... } -%typemap(in) (int argc, char *argv[]) { ... typemap 2 ... } -%typemap(in) (int argc, char *argv[], char *env[]) { ... typemap 3 ... } - -int foo(int argc, char *argv[]); // Uses typemap 2 -int bar(int argc, int x); // Uses typemap 1 -int spam(int argc, char *argv[], char *env[]); // Uses typemap 3 +type ltype +------ ---------------- +int int +const int int +const int * int * +int [4] int * +int [4][5] int (*)[5]It should be stressed that multi-argument typemaps can appear - anywhere in a function declaration and can appear more than once. For - example, you could write this:
+In most cases a ltype is simply the C datatype with qualifiers + stripped off. In addition, arrays are converted into pointers.
+Variables such as $&1_type and $*1_type are used + to safely modify the type by removing or adding pointers. Although not + needed in most typemaps, these substitutions are sometimes needed to + properly work with typemaps that convert values between pointers and + values.
+If necessary, type related substitutions can also be used when + declaring locals. For example:
--%typemap(in) (int scount, char *swords[]) { ... } -%typemap(in) (int wcount, char *words[]) { ... } - -void search_words(int scount, char *swords[], int wcount, char *words[], int maxcount); +%typemap(in) int * ($*1_type temp) { + temp = PyInt_AsLong($input); + $1 = &temp; +}Other directives such as %apply and %clear also - work with multi-argument maps. For example:
+There is one word of caution about declaring local variables in this + manner. If you declare a local variable using a type substitution such + as $1_ltype temp, it won't work like you expect for arrays and + certain kinds of pointers. For example, if you wrote this,
--%apply (int argc, char *argv[]) { - (int scount, char *swords[]), - (int wcount, char *words[]) -}; -... -%clear (int scount, char *swords[]), (int wcount, char *words[]); -... +%typemap(in) int [10][20] { + $1_ltype temp; +}Although multi-argument typemaps may seem like an exotic, little - used feature, there are several situations where they make sense. - First, suppose you wanted to wrap functions similar to the low-level -read() and write() system calls. For example:
+then the declaration of temp will be expanded as
--typedef unsigned int size_t; - -int read(int fd, void *rbuffer, size_t len); -int write(int fd, void *wbuffer, size_t len); +int (*)[20] temp;As is, the only way to use the functions would be to allocate memory - and pass some kind of pointer as the second argument---a process that - might require the use of a helper function. However, using - multi-argument maps, the functions can be transformed into something - more natural. For example, you might write typemaps like this:
+This is illegal C syntax and won't compile. There is currently no + straightforward way to work around this problem in SWIG due to the way + that typemap code is expanded and processed. However, one possible + workaround is to simply pick an alternative type such as void * + and use casts to get the correct type when needed. For example:
+-// typemap for an outgoing buffer -%typemap(in) (void *wbuffer, size_t len) { - if (!PyString_Check($input)) { - PyErr_SetString(PyExc_ValueError, "Expecting a string"); - return NULL; - } - $1 = (void *) PyString_AsString($input); - $2 = PyString_Size($input); -} - -// typemap for an incoming buffer -%typemap(in) (void *rbuffer, size_t len) { - if (!PyInt_Check($input)) { - PyErr_SetString(PyExc_ValueError, "Expecting an integer"); - return NULL; - } - $2 = PyInt_AsLong($input); - if ($2 < 0) { - PyErr_SetString(PyExc_ValueError, "Positive integer expected"); - return NULL; - } - $1 = (void *) malloc($2); +%typemap(in) int [10][20] { + void *temp; + ... + (($1_ltype) temp)[i][j] = x; /* set a value */ + ... } - -// Return the buffer. Discarding any previous return result -%typemap(argout) (void *rbuffer, size_t len) { - Py_XDECREF($result); /* Blow away any previous result */ - if (result < 0) { /* Check for I/O error */ - free($1); - PyErr_SetFromErrno(PyExc_IOError); - return NULL; - } - $result = PyString_FromStringAndSize($1,result); - free($1); ++Another approach, which only works for arrays is to use the +$1_basetype substitution. For example:
++-+%typemap(in) int [10][20] { + $1_basetype temp[10][20]; + ... + temp[i][j] = x; /* set a value */ + ... }(note: In the above example, $result and result - are two different variables. result is the real C datatype - that was returned by the function. $result is the scripting - language object being returned to the interpreter.).
-Now, in a script, you can write code that simply passes buffers as - strings like this:
-+11.4.4 Special variable + macros
+Special variable macros are like macro functions in that they take + one or more input arguments which are used for the macro expansion. + They look like macro/function calls but use the special variable $ + prefix to the macro name. Note that unlike normal macros, the expansion + is not done by the preprocessor, it is done during the SWIG + parsing/compilation stages. The following special variable macros are + available across all language modules.
+11.4.4.1 + $descriptor(type)
+This macro expands into the type descriptor structure for any C/C++ + type specified in type. It behaves like the $1_descriptor + special variable described above except that the type to expand is + taken from the macro argument rather than inferred from the typemap + type. For example, $descriptor(std::vector<int> *) will expand + into SWIGTYPE_p_std__vectorT_int_t. This macro is mostly used + in the scripting target languages and is demonstrated later in the +Run-time type checker usage section.
+11.4.4.2 $typemap(method, + typepattern)
+This macro uses the pattern + matching rules described earlier to lookup and then substitute the + special variable macro with the code in the matched typemap. The + typemap to search for is specified by the arguments, where method + is the typemap method name and typepattern is a type pattern + as per the %typemap specification in the +Defining a typemap section.
+The special variables within the matched typemap are expanded into + those for the matched typemap type, not the typemap within which the + macro is called. In practice, there is little use for this macro in the + scripting target languages. It is mostly used in the target languages + that are statically typed as a way to obtain the target language type + given the C/C++ type and more commonly only when the C++ type is a + template parameter.
+The example below is for C# only and uses some typemap method names + documented in the C# chapter, but it shows some of the possible syntax + variations.
+-->>> f = example.open("Makefile") ->>> example.read(f,40) -'TOP = ../..\nSWIG = $(TOP)/.' ->>> example.read(f,40) -'./swig\nSRCS = example.c\nTARGET ' ->>> example.close(f) -0 ->>> g = example.open("foo", example.O_WRONLY | example.O_CREAT, 0644) ->>> example.write(g,"Hello world\n") -12 ->>> example.write(g,"This is a test\n") -15 ->>> example.close(g) -0 ->>> +%typemap(cstype) unsigned long "uint" +%typemap(cstype) unsigned long bb "bool" +%typemap(cscode) BarClass %{ + void foo($typemap(cstype, unsigned long aa) var1, + $typemap(cstype, unsigned long bb) var2, + $typemap(cstype, (unsigned long bb)) var3, + $typemap(cstype, unsigned long) var4) + { + // do something + } +%}A number of multi-argument typemap problems also arise in libraries - that perform matrix-calculations--especially if they are mapped onto - low-level Fortran or C code. For example, you might have a function - like this:
+The result is the following expansion
--int is_symmetric(double *mat, int rows, int columns); +%typemap(cstype) unsigned long "uint" +%typemap(cstype) unsigned long bb "bool" +%typemap(cscode) BarClass %{ + void foo(uint var1, + bool var2, + bool var3, + uint var4) + { + // do something + } +%}In this case, you might want to pass some kind of higher-level - object as an matrix. To do this, you could write a multi-argument - typemap like this:
+11.4.5 Special + variables and typemap attributes
+As of SWIG-3.0.7 typemap attributes will also expand special + variables and special variable macros.
+Example usage showing the expansion in the 'out' attribute (C# + specific) as well as the main typemap body:
--%typemap(in) (double *mat, int rows, int columns) { - MatrixObject *a; - a = GetMatrixFromObject($input); /* Get matrix somehow */ - - /* Get matrix properties */ - $1 = GetPointer(a); - $2 = GetRows(a); - $3 = GetColumns(a); -} +%typemap(ctype, out="$*1_ltype") unsigned int& "$*1_ltype"This kind of technique can be used to hook into scripting-language - matrix packages such as Numeric Python. However, it should also be - stressed that some care is in order. For example, when crossing - languages you may need to worry about issues such as row-major vs. - column-major ordering (and perform conversions if needed). Note that - multi-argument typemaps cannot deal with non-consecutive C/C++ - arguments; a workaround such as a helper function re-ordering the - arguments to make them consecutive will need to be written.
-10.10 Typemap warnings
-Warnings can be added to typemaps so that SWIG generates a warning - message whenever the typemap is used. See the information in the -issuing warnings section.
-10.11 Typemap fragments
-The primary purpose of fragments is to reduce code bloat that - repeated use of typemap code can lead to. Fragments are snippets of - code that can be thought of as code dependencies of a typemap. If a - fragment is used by more than one typemap, then the snippet of code - within the fragment is only generated once. Code bloat is typically - reduced by moving typemap code into a support function and then placing - the support function into a fragment.
-For example, if you have a very long typemap
+is equivalent to the following as $*1_ltype expands to +unsigned int:
--%typemap(in) MyClass * { - MyClass *value = 0; - - ... many lines of marshalling code ... - - $result = value; -} +%typemap(ctype, out="unsigned int") unsigned int& "unsigned int"the same marshalling code is often repeated in several typemaps, - such as "in", "varin", "directorout", etc. SWIG copies the code for - each argument that requires the typemap code, easily leading to code - bloat in the generated code. To eliminate this, define a fragment that - includes the common marshalling code:
+11.4.6 Special + variables combined with special variable macros
+Special variables can also be used within special variable macros. + The special variables are expanded before they are used in the special + variable macros.
+Consider the following C# typemaps:
--%fragment("AsMyClass", "header") { - MyClass *AsMyClass(PyObject *obj) { - MyClass *value = 0; - - ... many lines of marshalling code ... - - return value; - } -} - -%typemap(in, fragment="AsMyClass") MyClass * { - $result = AsMyClass($input); -} - -%typemap(varin, fragment="AsMyClass") MyClass * { - $result = AsMyClass($input); -} +%typemap(cstype) unsigned int "uint" +%typemap(cstype, out="$typemap(cstype, $*1_ltype)") unsigned int& "$typemap(cstype, $*1_ltype)"When the "in" or "varin" typemaps for MyClass are required, the - contents of the fragment called "AsMyClass" is added to the "header" - section within the generated code, and then the typemap code is - emitted. Hence, the method AsMyClass will be generated into - the wrapper code before any typemap code that calls it.
-To define a fragment you need a fragment name, a section name for - generating the fragment code into, and the code itself. See -Code insertion blocks for a full list of section names. Usually the - section name used is "header". Different delimiters can be used:
+Special variables are expanded first and hence the above is + equivalent to:
--%fragment("my_name", "header") %{ ... %} -%fragment("my_name", "header") { ... } -%fragment("my_name", "header") " ... " +%typemap(cstype) unsigned int "uint" +%typemap(cstype, out="$typemap(cstype, unsigned int)") unsigned int& "$typemap(cstype, unsigned int)"and these follow the usual preprocessing rules mentioned in the -Preprocessing delimiters section. The following are some rules and - guidelines for using fragments:
--
-- -
-A fragment is added to the wrapping code only once. When using the -MyClass * typemaps above and wrapping the method:
+which then expands to:
--void foo(MyClass *a, MyClass *b); +%typemap(cstype) unsigned int "uint" +%typemap(cstype, out="uint") unsigned int& "uint"the generated code will look something like:
+11.5 Common typemap methods
+The set of typemaps recognized by a language module may vary. + However, the following typemap methods are nearly universal:
+11.5.1 "in" typemap
+The "in" typemap is used to convert function arguments from the + target language to C. For example:
--MyClass *AsMyClass(PyObject *obj) { - ... -} - -void _wrap_foo(...) { - .... - arg1 = AsMyClass(obj1); - arg2 = AsMyClass(obj2); - ... - foo(arg1, arg2); +%typemap(in) int { + $1 = PyInt_AsLong($input); }even as there is duplicated typemap code to process both a - and b, the AsMyClass method will be defined only - once.
-- -
-A fragment should only be defined once. If there is more than one - definition, the first definition is the one used. All other definitions - are silently ignored. For example, if you have
+The following special variables are available:
--%fragment("AsMyClass", "header") { ...definition 1... } -.... -%fragment("AsMyClass", "header") { ...definition 2... } +$input - Input object holding value to be converted. +$symname - Name of function/method being wrappedonly the first definition is used. In this way you can override the - default fragments in a SWIG library by defining your fragment before - the library %include. Note that this behavior is the opposite - to typemaps, where the last typemap defined/applied prevails. Fragments - follow the first-in-first-out convention since they are intended to be - global, while typemaps are intended to be locally specialized.
-- -
-Fragment names cannot contain commas.
-- -
-A fragment can use one or more additional fragments, for example:
+This is probably the most commonly redefined typemap because it can + be used to implement customized conversions.
+In addition, the "in" typemap allows the number of converted + arguments to be specified. The numinputs attributes + facilitates this. For example:
--%fragment("<limits.h>", "header") { - %#include <limits.h> -} - - -%fragment("AsMyClass", "header", fragment="<limits.h>") { - MyClass *AsMyClass(PyObject *obj) { - MyClass *value = 0; - - ... some marshalling code ... - - if (ival < CHAR_MIN /*defined in <limits.h>*/) { - ... - } else { - ... - } - ... - return value; - } +// Ignored argument. +%typemap(in, numinputs=0) int *out (int temp) { + $1 = &temp; }in this case, when the "AsMyClass" fragment is emitted, it also - triggers the inclusion of the "<limits.h>" fragment.
-- -
-A fragment can have dependencies on a number of other fragments, for - example:
+At this time, only zero or one arguments may be converted. When +numinputs is set to 0, the argument is effectively ignored and + cannot be supplied from the target language. The argument is still + required when making the C/C++ call and the above typemap shows the + value used is instead obtained from a locally declared variable called +temp. Usually numinputs is not specified, whereupon the + default value is 1, that is, there is a one to one mapping of the + number of arguments when used from the target language to the C/C++ + call. Multi-argument + typemaps provide a similar concept where the number of arguments + mapped from the target language to C/C++ can be changed for multiple + adjacent C/C++ arguments.
+Compatibility note: Specifying numinputs=0 is the + same as the old "ignore" typemap.
+11.5.2 "typecheck" typemap
+The "typecheck" typemap is used to support overloaded functions and + methods. It merely checks an argument to see whether or not it matches + a specific type. For example:
--%fragment("bigfragment", "header", fragment="frag1", fragment="frag2", fragment="frag3") ""; +%typemap(typecheck,precedence=SWIG_TYPECHECK_INTEGER) int { + $1 = PyInt_Check($input) ? 1 : 0; +}When the "bigfragment" is used, the three dependent fragments - "frag1", "frag2" and "frag3" are also pulled in. Note that as - "bigframent" is empty (the empty string - ""), it does not add any code - itself, but merely triggers the inclusion of the other fragments.
-- -
-A typemap can also use more than one fragment, but since the syntax - is different, you need to specify the dependent fragments in a comma - separated list. Consider:
+For typechecking, the $1 variable is always a simple integer that is + set to 1 or 0 depending on whether or not the input argument is the + correct type.
+If you define new "in" typemaps and your program uses + overloaded methods, you should also define a collection of "typecheck" + typemaps. More details about this follow in the +Typemaps and overloading section.
+11.5.3 "out" typemap
+The "out" typemap is used to convert function/method return values + from C into the target language. For example:
--%typemap(in, fragment="frag1,frag2,frag3") {...} +%typemap(out) int { + $result = PyInt_FromLong($1); +}which is equivalent to:
+The following special variables are available.
--%typemap(in, fragment="bigfragment") {...} +$result - Result object returned to target language. +$symname - Name of function/method being wrappedwhen used with the "bigfragment" defined above.
-- -
-Finally, you can force the inclusion of a fragment at any point in - the generated code as follows:
+The "out" typemap supports an optional attribute flag called + "optimal". This is for code optimisation and is detailed in the +Optimal code generation when returning by value section.
+11.5.4 "arginit" typemap
+The "arginit" typemap is used to set the initial value of a function + argument--before any conversion has occurred. This is not normally + necessary, but might be useful in highly specialized applications. For + example:
--%fragment("bigfragment"); +// Set argument to NULL before any conversion occurs +%typemap(arginit) int *data { + $1 = NULL; +}which is very useful inside a template class, for example.
-Most readers will probably want to skip the next two sub-sections on - advanced fragment usage unless a desire to really get to grips with - some powerful but tricky macro and fragment usage that is used in parts - of the SWIG typemap library.
-10.11.1 Fragment - type specialization
-Fragments can be type specialized. The syntax is as follows:
+11.5.5 "default" typemap
+The "default" typemap is used to turn an argument into a default + argument. For example:
--%fragment("name", "header") { ...a type independent fragment... } -%fragment("name"{type}, "header") { ...a type dependent fragment... } +%typemap(default) int flags { + $1 = DEFAULT_FLAGS; +} +... +int foo(int x, int y, int flags);where type is a C/C++ type. Like typemaps, fragments can - also be used inside templates, for example:
+The primary use of this typemap is to either change the wrapping of + default arguments or specify a default argument in a language where + they aren't supported (like C). Target languages that do not support + optional arguments, such as Java and C#, effectively ignore the value + specified by this typemap as all arguments must be given.
+Once a default typemap has been applied to an argument, all + arguments that follow must have default values. See the +Default/optional arguments section for further information on + default argument wrapping.
+11.5.6 "check" typemap
+The "check" typemap is used to supply value checking code during + argument conversion. The typemap is applied after arguments + have been converted. For example:
--template <class T> -struct A { - %fragment("incode"{A<T>}, "header") { - ... 'incode' specialized fragment ... - } - - %typemap(in, fragment="incode"{A<T>}) { - ... here we use the 'type specialized' fragment "incode"{A<T>} ... - } -}; +%typemap(check) int positive { + if ($1 <= 0) { + SWIG_exception(SWIG_ValueError,"Expected positive value."); + } +}10.11.2 Fragments - and automatic typemap specialization
-Since fragments can be type specialized, they can be elegantly used - to specialize typemaps. For example, if you have something like:
+11.5.7 "argout" typemap
+The "argout" typemap is used to return values from arguments. This + is most commonly used to write wrappers for C/C++ functions that need + to return multiple values. The "argout" typemap is almost always + combined with an "in" typemap---possibly to ignore the input value. For + example:
--%fragment("incode"{float}, "header") { - float in_method_float(PyObject *obj) { - ... - } -} - -%fragment("incode"{long}, "header") { - float in_method_long(PyObject *obj) { - ... - } +/* Set the input argument to point to a temporary variable */ +%typemap(in, numinputs=0) int *out (int temp) { + $1 = &temp; } -// %my_typemaps macro definition -%define %my_typemaps(Type) -%typemap(in, fragment="incode"{Type}) Type { - value = in_method_##Type(obj); +%typemap(argout) int *out { + // Append output value $1 to $result + ... } -%enddef - -%my_typemaps(float); -%my_typemaps(long);then the proper "incode"{float} or "incode"{long} - fragment will be used, and the in_method_float and -in_method_long methods will be called whenever the float - or long types are used as input parameters.
-This feature is used a lot in the typemaps shipped in the SWIG - library for some scripting languages. The interested (or very brave) - reader can take a look at the fragments.swg file shipped with SWIG to - see this in action.
-10.12 The run-time type - checker
-Most scripting languages need type information at run-time. This - type information can include how to construct types, how to garbage - collect types, and the inheritance relationships between types. If the - language interface does not provide its own type information storage, - the generated SWIG code needs to provide it.
-Requirements for the type system:
--
-- Store inheritance and type equivalence information and be able to - correctly re-create the type pointer.
-- Share type information between modules.
-- Modules can be loaded in any order, irregardless of actual type - dependency.
-- Avoid the use of dynamically allocated memory, and library/system - calls in general.
-- Provide a reasonably fast implementation, minimizing the lookup time - for all language modules.
-- Custom, language specific information can be attached to types.
-- Modules can be unloaded from the type system.
-10.12.1 Implementation
-The run-time type checker is used by many, but not all, of SWIG's - supported target languages. The run-time type checker features are not - required and are thus not used for statically typed languages such as - Java and C#. The scripting and scheme based languages rely on it and it - forms a critical part of SWIG's operation for these languages.
-When pointers, arrays, and objects are wrapped by SWIG, they are - normally converted into typed pointer objects. For example, an instance - of Foo * might be a string encoded like this:
+The following special variables are available.
--_108e688_p_Foo +$result - Result object returned to target language. +$input - The original input object passed. +$symname - Name of function/method being wrappedAt a basic level, the type checker simply restores some type-safety - to extension modules. However, the type checker is also responsible for - making sure that wrapped C++ classes are handled correctly---especially - when inheritance is used. This is especially important when an - extension module makes use of multiple inheritance. For example:
+The code supplied to the "argout" typemap is always placed after the + "out" typemap. If multiple return values are used, the extra return + values are often appended to return value of the function.
+See the typemaps.i library file for examples.
+11.5.8 "freearg" typemap
+The "freearg" typemap is used to cleanup argument data. It is only + used when an argument might have allocated resources that need to be + cleaned up when the wrapper function exits. The "freearg" typemap + usually cleans up argument resources allocated by the "in" typemap. For + example:
--class Foo { - int x; -}; - -class Bar { - int y; -}; - -class FooBar : public Foo, public Bar { - int z; -}; +// Get a list of integers +%typemap(in) int *items { + int nitems = Length($input); + $1 = (int *) malloc(sizeof(int)*nitems); +} +// Free the list +%typemap(freearg) int *items { + free($1); +}When the class FooBar is organized in memory, it contains - the contents of the classes Foo and Bar as well as - its own data members. For example:
-+The "freearg" typemap inserted at the end of the wrapper function, + just before control is returned back to the target language. This code + is also placed into a special variable $cleanup that may be + used in other typemaps whenever a wrapper function needs to abort + prematurely.
+11.5.9 "newfree" typemap
+The "newfree" typemap is used in conjunction with the %newobject + directive and is used to deallocate memory used by the return result of + a function. For example:
+--FooBar --> | -----------| <-- Foo - | int x | - |------------| <-- Bar - | int y | - |------------| - | int z | - |------------| +%typemap(newfree) string * { + delete $1; +} +%typemap(out) string * { + $result = PyString_FromString($1->c_str()); +} +... + +%newobject foo; +... +string *foo();Because of the way that base class data is stacked together, the - casting of a Foobar * to either of the base classes may change - the actual value of the pointer. This means that it is generally not - safe to represent pointers using a simple integer or a bare void * ----type tags are needed to implement correct handling of pointer values - (and to make adjustments when needed).
-In the wrapper code generated for each language, pointers are - handled through the use of special type descriptors and conversion - functions. For example, if you look at the wrapper code for Python, you - will see code like this:
+See Object ownership and + %newobject for further details.
+11.5.10 "memberin" typemap
+The "memberin" typemap is used to copy data from an already + converted input value into a structure member. It is typically + used to handle array members and other special cases. For example:
--if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_Foo,1)) == -1) return NULL; +%typemap(memberin) int [4] { + memmove($1, $input, 4*sizeof(int)); +}In this code, SWIGTYPE_p_Foo is the type descriptor that - describes Foo *. The type descriptor is actually a pointer to - a structure that contains information about the type name to use in the - target language, a list of equivalent typenames (via typedef or - inheritance), and pointer value handling information (if applicable). - The SWIG_ConvertPtr() function is simply a utility function - that takes a pointer object in the target language and a - type-descriptor objects and uses this information to generate a C++ - pointer. However, the exact name and calling conventions of the - conversion function depends on the target language (see language - specific chapters for details).
-The actual type code is in swigrun.swg, and gets inserted near the - top of the generated swig wrapper file. The phrase "a type X that can - cast into a type Y" means that given a type X, it can be converted into - a type Y. In other words, X is a derived class of Y or X is a typedef - of Y. The structure to store type information looks like this:
+It is rarely necessary to write "memberin" typemaps---SWIG already + provides a default implementation for arrays, strings, and other + objects.
+11.5.11 "varin" typemap
+The "varin" typemap is used to convert objects in the target + language to C for the purposes of assigning to a C/C++ global variable. + This is implementation specific.
+11.5.12 "varout" typemap
+The "varout" typemap is used to convert a C/C++ object to an object + in the target language when reading a C/C++ global variable. This is + implementation specific.
+11.5.13 "throws" typemap
+The "throws" typemap is only used when SWIG parses a C++ method with + an exception specification or has the %catches feature + attached to the method. It provides a default mechanism for handling + C++ methods that have declared the exceptions they will throw. The + purpose of this typemap is to convert a C++ exception into an error or + exception in the target language. It is slightly different to the other + typemaps as it is based around the exception type rather than the type + of a parameter or variable. For example:
--/* Structure to store information on one type */ -typedef struct swig_type_info { - const char *name; /* mangled name of this type */ - const char *str; /* human readable name for this type */ - swig_dycast_func dcast; /* dynamic cast function down a hierarchy */ - struct swig_cast_info *cast; /* Linked list of types that can cast into this type */ - void *clientdata; /* Language specific type data */ -} swig_type_info; - -/* Structure to store a type and conversion function used for casting */ -typedef struct swig_cast_info { - swig_type_info *type; /* pointer to type that is equivalent to this type */ - swig_converter_func converter; /* function to cast the void pointers */ - struct swig_cast_info *next; /* pointer to next cast in linked list */ - struct swig_cast_info *prev; /* pointer to the previous cast */ -} swig_cast_info; +%typemap(throws) const char * %{ + PyErr_SetString(PyExc_RuntimeError, $1); + SWIG_fail; +%} +void bar() throw (const char *);Each swig_type_info stores a linked list of types that it - is equivalent to. Each entry in this doubly linked list stores a - pointer back to another swig_type_info structure, along with a pointer - to a conversion function. This conversion function is used to solve the - above problem of the FooBar class, correctly returning a pointer to the - type we want.
-The basic problem we need to solve is verifying and building - arguments passed to functions. So going back to the -SWIG_ConvertPtr() function example from above, we are expecting a -Foo * and need to check if obj0 is in fact a Foo * -. From before, SWIGTYPE_p_Foo is just a pointer to the -swig_type_info structure describing Foo *. So we loop - through the linked list of swig_cast_info structures attached - to SWIGTYPE_p_Foo. If we see that the type of obj0 is - in the linked list, we pass the object through the associated - conversion function and then return a positive. If we reach the end of - the linked list without a match, then obj0 can not be - converted to a Foo * and an error is generated.
-Another issue needing to be addressed is sharing type information - between multiple modules. More explicitly, we need to have ONE -swig_type_info for each type. If two modules both use the type, the - second module loaded must lookup and use the swig_type_info structure - from the module already loaded. Because no dynamic memory is used and - the circular dependencies of the casting information, loading the type - information is somewhat tricky, and not explained here. A complete - description is in the Lib/swiginit.swg file (and near the top - of any generated file).
-Each module has one swig_module_info structure which looks like - this:
+As can be seen from the generated code below, SWIG generates an + exception handler with the catch block comprising the "throws" typemap + content.
--/* Structure used to store module information - * Each module generates one structure like this, and the runtime collects - * all of these structures and stores them in a circularly linked list.*/ -typedef struct swig_module_info { - swig_type_info **types; /* Array of pointers to swig_type_info structs in this module */ - int size; /* Number of types in this module */ - struct swig_module_info *next; /* Pointer to next element in circularly linked list */ - swig_type_info **type_initial; /* Array of initially generated type structures */ - swig_cast_info **cast_initial; /* Array of initially generated casting structures */ - void *clientdata; /* Language specific module data */ -} swig_module_info; +... +try { + bar(); +} +catch(char const *_e) { + PyErr_SetString(PyExc_RuntimeError, _e); + SWIG_fail; + +} +...Each module stores an array of pointers to swig_type_info - structures and the number of types in this module. So when a second - module is loaded, it finds the swig_module_info structure for - the first module and searches the array of types. If any of its own - types are in the first module and have already been loaded, it uses - those swig_type_info structures rather than creating new ones. - These swig_module_info structures are chained together in a - circularly linked list.
-10.12.2 Usage
-This section covers how to use these functions from typemaps. To - learn how to call these functions from external files (not the - generated _wrap.c file), see the -External access to the run-time system section.
-When pointers are converted in a typemap, the typemap code often - looks similar to this:
+Note that if your methods do not have an exception specification yet + they do throw exceptions, SWIG cannot know how to deal with them. For a + neat way to handle these, see the +Exception handling with %exception section.
+11.6 Some typemap examples
+This section contains a few examples. Consult language module + documentation for more examples.
+11.6.1 Typemaps for arrays
+A common use of typemaps is to provide support for C arrays + appearing both as arguments to functions and as structure members.
+For example, suppose you had a function like this:
--%typemap(in) Foo * { - if ((SWIG_ConvertPtr($input, (void **) &$1, $1_descriptor)) == -1) return NULL; -} +void set_vector(int type, float value[4]);The most critical part is the typemap is the use of the -$1_descriptor special variable. When placed in a typemap, this is - expanded into the SWIGTYPE_* type descriptor object above. As - a general rule, you should always use $1_descriptor instead of - trying to hard-code the type descriptor name directly.
-There is another reason why you should always use the -$1_descriptor variable. When this special variable is expanded, - SWIG marks the corresponding type as "in use." When type-tables and - type information is emitted in the wrapper file, descriptor information - is only generated for those datatypes that were actually used in the - interface. This greatly reduces the size of the type tables and - improves efficiency.
-Occasionally, you might need to write a typemap that needs to - convert pointers of other types. To handle this, the special variable - macro $descriptor(type) covered earlier can be used to - generate the SWIG type descriptor name for any C datatype. For example:
+If you wanted to handle float value[4] as a list of floats, + you might write a typemap similar to this:
--%typemap(in) Foo * { - if ((SWIG_ConvertPtr($input, (void **) &$1, $1_descriptor)) == -1) { - Bar *temp; - if ((SWIG_ConvertPtr($input, (void **) &temp, $descriptor(Bar *)) == -1) { - return NULL; - } - $1 = (Foo *) temp; + +%typemap(in) float value[4] (float temp[4]) { + int i; + if (!PySequence_Check($input)) { + PyErr_SetString(PyExc_ValueError,"Expected a sequence"); + return NULL; + } + if (PySequence_Length($input) != 4) { + PyErr_SetString(PyExc_ValueError,"Size mismatch. Expected 4 elements"); + return NULL; + } + for (i = 0; i < 4; i++) { + PyObject *o = PySequence_GetItem($input,i); + if (PyNumber_Check(o)) { + temp[i] = (float) PyFloat_AsDouble(o); + } else { + PyErr_SetString(PyExc_ValueError,"Sequence elements must be numbers"); + return NULL; + } } + $1 = temp; }The primary use of $descriptor(type) is when writing - typemaps for container objects and other complex data structures. There - are some restrictions on the argument---namely it must be a fully - defined C datatype. It can not be any of the special typemap variables.
-In certain cases, SWIG may not generate type-descriptors like you - expect. For example, if you are converting pointers in some - non-standard way or working with an unusual combination of interface - files and modules, you may find that SWIG omits information for a - specific type descriptor. To fix this, you may need to use the -%types directive. For example:
-+In this example, the variable temp allocates a small array + on the C stack. The typemap then populates this array and passes it to + the underlying C function.
+When used from Python, the typemap allows the following type of + function call:
+--%types(int *, short *, long *, float *, double *); +>>> set_vector(type, [ 1, 2.5, 5, 20 ])When %types is used, SWIG generates type-descriptor - information even if those datatypes never appear elsewhere in the - interface file.
-Further details about the run-time type checking can be found in the - documentation for individual language modules. Reading the source code - may also help. The file Lib/swigrun.swg in the SWIG library - contains all of the source of the generated code for type-checking. - This code is also included in every generated wrapped file so you - probably just look at the output of SWIG to get a better sense for how - types are managed.
-10.13 Typemaps and overloading
-This section does not apply to the statically typed languages like - Java and C#, where overloading of the types is handled much like C++ by - generating overloaded methods in the target language. In many of the - other target languages, SWIG still fully supports C++ overloaded - methods and functions. For example, if you have a collection of - functions like this:
+If you wanted to generalize the typemap to apply to arrays of all + dimensions you might write this:
--int foo(int x); -int foo(double x); -int foo(char *s, int y); +%typemap(in) float value[ANY] (float temp[$1_dim0]) { + int i; + if (!PySequence_Check($input)) { + PyErr_SetString(PyExc_ValueError,"Expected a sequence"); + return NULL; + } + if (PySequence_Length($input) != $1_dim0) { + PyErr_SetString(PyExc_ValueError,"Size mismatch. Expected $1_dim0 elements"); + return NULL; + } + for (i = 0; i < $1_dim0; i++) { + PyObject *o = PySequence_GetItem($input,i); + if (PyNumber_Check(o)) { + temp[i] = (float) PyFloat_AsDouble(o); + } else { + PyErr_SetString(PyExc_ValueError,"Sequence elements must be numbers"); + return NULL; + } + } + $1 = temp; +}You can access the functions in a normal way from the scripting - interpreter:
-+In this example, the special variable $1_dim0 is expanded + with the actual array dimensions. Multidimensional arrays can be + matched in a similar manner. For example:
+--# Python -foo(3) # foo(int) -foo(3.5) # foo(double) -foo("hello",5) # foo(char *, int) - -# Tcl -foo 3 # foo(int) -foo 3.5 # foo(double) -foo hello 5 # foo(char *, int) +%typemap(in) float matrix[ANY][ANY] (float temp[$1_dim0][$1_dim1]) { + ... convert a 2d array ... +}To implement overloading, SWIG generates a separate wrapper function - for each overloaded method. For example, the above functions would - produce something roughly like this:
+For large arrays, it may be impractical to allocate storage on the + stack using a temporary variable as shown. To work with heap allocated + data, the following technique can be used.
--// wrapper pseudocode -_wrap_foo_0(argc, args[]) { // foo(int) - int arg1; - int result; - ... - arg1 = FromInteger(args[0]); - result = foo(arg1); - return ToInteger(result); -} - -_wrap_foo_1(argc, args[]) { // foo(double) - double arg1; - int result; - ... - arg1 = FromDouble(args[0]); - result = foo(arg1); - return ToInteger(result); +%typemap(in) float value[ANY] { + int i; + if (!PySequence_Check($input)) { + PyErr_SetString(PyExc_ValueError,"Expected a sequence"); + return NULL; + } + if (PySequence_Length($input) != $1_dim0) { + PyErr_SetString(PyExc_ValueError,"Size mismatch. Expected $1_dim0 elements"); + return NULL; + } + $1 = (float *) malloc($1_dim0*sizeof(float)); + for (i = 0; i < $1_dim0; i++) { + PyObject *o = PySequence_GetItem($input,i); + if (PyNumber_Check(o)) { + $1[i] = (float) PyFloat_AsDouble(o); + } else { + PyErr_SetString(PyExc_ValueError,"Sequence elements must be numbers"); + free($1); + return NULL; + } + } } - -_wrap_foo_2(argc, args[]) { // foo(char *, int) - char *arg1; - int arg2; - int result; - ... - arg1 = FromString(args[0]); - arg2 = FromInteger(args[1]); - result = foo(arg1,arg2); - return ToInteger(result); +%typemap(freearg) float value[ANY] { + if ($1) free($1); } -Next, a dynamic dispatch function is generated:
+In this case, an array is allocated using malloc. The +freearg typemap is then used to release the argument after the + function has been called.
+Another common use of array typemaps is to provide support for array + structure members. Due to subtle differences between pointers and + arrays in C, you can't just "assign" to a array structure member. + Instead, you have to explicitly copy elements into the array. For + example, suppose you had a structure like this:
--_wrap_foo(argc, args[]) { - if (argc == 1) { - if (IsInteger(args[0])) { - return _wrap_foo_0(argc,args); - } - if (IsDouble(args[0])) { - return _wrap_foo_1(argc,args); - } - } - if (argc == 2) { - if (IsString(args[0]) && IsInteger(args[1])) { - return _wrap_foo_2(argc,args); - } - } - error("No matching function!\n"); -} +struct SomeObject { + float value[4]; + ... +};The purpose of the dynamic dispatch function is to select the - appropriate C++ function based on argument types---a task that must be - performed at runtime in most of SWIG's target languages.
-The generation of the dynamic dispatch function is a relatively - tricky affair. Not only must input typemaps be taken into account - (these typemaps can radically change the types of arguments accepted), - but overloaded methods must also be sorted and checked in a very - specific order to resolve potential ambiguity. A high-level overview of - this ranking process is found in the "SWIG and C++ -" chapter. What isn't mentioned in that chapter is the mechanism by - which it is implemented---as a collection of typemaps.
-To support dynamic dispatch, SWIG first defines a general purpose - type hierarchy as follows:
-+-When SWIG runs, it won't produce any code to set the vec + member. You may even get a warning message like this:
+--Symbolic Name Precedence Value ------------------------------- ------------------ -SWIG_TYPECHECK_POINTER 0 -SWIG_TYPECHECK_VOIDPTR 10 -SWIG_TYPECHECK_BOOL 15 -SWIG_TYPECHECK_UINT8 20 -SWIG_TYPECHECK_INT8 25 -SWIG_TYPECHECK_UINT16 30 -SWIG_TYPECHECK_INT16 35 -SWIG_TYPECHECK_UINT32 40 -SWIG_TYPECHECK_INT32 45 -SWIG_TYPECHECK_UINT64 50 -SWIG_TYPECHECK_INT64 55 -SWIG_TYPECHECK_UINT128 60 -SWIG_TYPECHECK_INT128 65 -SWIG_TYPECHECK_INTEGER 70 -SWIG_TYPECHECK_FLOAT 80 -SWIG_TYPECHECK_DOUBLE 90 -SWIG_TYPECHECK_COMPLEX 100 -SWIG_TYPECHECK_UNICHAR 110 -SWIG_TYPECHECK_UNISTRING 120 -SWIG_TYPECHECK_CHAR 130 -SWIG_TYPECHECK_STRING 140 -SWIG_TYPECHECK_BOOL_ARRAY 1015 -SWIG_TYPECHECK_INT8_ARRAY 1025 -SWIG_TYPECHECK_INT16_ARRAY 1035 -SWIG_TYPECHECK_INT32_ARRAY 1045 -SWIG_TYPECHECK_INT64_ARRAY 1055 -SWIG_TYPECHECK_INT128_ARRAY 1065 -SWIG_TYPECHECK_FLOAT_ARRAY 1080 -SWIG_TYPECHECK_DOUBLE_ARRAY 1090 -SWIG_TYPECHECK_CHAR_ARRAY 1130 -SWIG_TYPECHECK_STRING_ARRAY 1140 +$ swig -python example.i +example.i:10: Warning 462: Unable to set variable of type float [4].(These precedence levels are defined in swig.swg, a library - file that's included by all target language modules.)
-In this table, the precedence-level determines the order in which - types are going to be checked. Low values are always checked before - higher values. For example, integers are checked before floats, single - values are checked before arrays, and so forth.
-Using the above table as a guide, each target language defines a - collection of "typecheck" typemaps. The follow excerpt from the Python - module illustrates this:
+These warning messages indicate that SWIG does not know how you want + to set the vec field.
+To fix this, you can supply a special "memberin" typemap like this:
--/* Python type checking rules */ -/* Note: %typecheck(X) is a macro for %typemap(typecheck,precedence=X) */ - -%typecheck(SWIG_TYPECHECK_INTEGER) - int, short, long, - unsigned int, unsigned short, unsigned long, - signed char, unsigned char, - long long, unsigned long long, - const int &, const short &, const long &, - const unsigned int &, const unsigned short &, const unsigned long &, - const long long &, const unsigned long long &, - enum SWIGTYPE, - bool, const bool & -{ - $1 = (PyInt_Check($input) || PyLong_Check($input)) ? 1 : 0; -} - -%typecheck(SWIG_TYPECHECK_DOUBLE) - float, double, - const float &, const double & -{ - $1 = (PyFloat_Check($input) || PyInt_Check($input) || PyLong_Check($input)) ? 1 : 0; -} - -%typecheck(SWIG_TYPECHECK_CHAR) char { - $1 = (PyString_Check($input) && (PyString_Size($input) == 1)) ? 1 : 0; -} - -%typecheck(SWIG_TYPECHECK_STRING) char * { - $1 = PyString_Check($input) ? 1 : 0; -} - -%typecheck(SWIG_TYPECHECK_POINTER) SWIGTYPE *, SWIGTYPE &, SWIGTYPE [] { - void *ptr; - if (SWIG_ConvertPtr($input, (void **) &ptr, $1_descriptor, 0) == -1) { - $1 = 0; - PyErr_Clear(); - } else { - $1 = 1; - } -} - -%typecheck(SWIG_TYPECHECK_POINTER) SWIGTYPE { - void *ptr; - if (SWIG_ConvertPtr($input, (void **) &ptr, $&1_descriptor, 0) == -1) { - $1 = 0; - PyErr_Clear(); - } else { - $1 = 1; - } -} - -%typecheck(SWIG_TYPECHECK_VOIDPTR) void * { - void *ptr; - if (SWIG_ConvertPtr($input, (void **) &ptr, 0, 0) == -1) { - $1 = 0; - PyErr_Clear(); - } else { - $1 = 1; +%typemap(memberin) float [ANY] { + int i; + for (i = 0; i < $1_dim0; i++) { + $1[i] = $input[i]; } } - -%typecheck(SWIG_TYPECHECK_POINTER) PyObject * -{ - $1 = ($input != 0); -}It might take a bit of contemplation, but this code has merely - organized all of the basic C++ types, provided some simple - type-checking code, and assigned each type a precedence value.
-Finally, to generate the dynamic dispatch function, SWIG uses the - following algorithm:
--
-- Overloaded methods are first sorted by the number of required - arguments.
-- Methods with the same number of arguments are then sorted by - precedence values of argument types.
-- Typecheck typemaps are then emitted to produce a dispatch function - that checks arguments in the correct order.
-If you haven't written any typemaps of your own, it is unnecessary - to worry about the typechecking rules. However, if you have written new - input typemaps, you might have to supply a typechecking rule as well. - An easy way to do this is to simply copy one of the existing - typechecking rules. Here is an example,
-+-The memberin typemap is used to set a structure member from data + that has already been converted from the target language to C. In this + case, $input is the local variable in which converted input + data is stored. This typemap then copies this data into the structure.
+When combined with the earlier typemaps for arrays, the combination + of the "in" and "memberin" typemap allows the following usage:
+--// Typemap for a C++ string -%typemap(in) std::string { - if (PyString_Check($input)) { - $1 = std::string(PyString_AsString($input)); - } else { - SWIG_exception(SWIG_TypeError, "string expected"); - } -} -// Copy the typecheck code for "char *". -%typemap(typecheck) std::string = char *; +>>> s = SomeObject() +>>> s.x = [1, 2.5, 5, 10]The bottom line: If you are writing new typemaps and you are using - overloaded methods, you will probably have to write typecheck code or - copy existing code. Since this is a relatively new SWIG feature, there - are few examples to work with. However, you might look at some of the - existing library files likes 'typemaps.i' for a guide.
-Notes:
--
-- Typecheck typemaps are not used for non-overloaded methods. Because - of this, it is still always necessary to check types in any "in" - typemaps.
-- The dynamic dispatch process is only meant to be a heuristic. There - are many corner cases where SWIG simply can't disambiguate types to the - same degree as C++. The only way to resolve this ambiguity is to use - the %rename directive to rename one of the overloaded methods - (effectively eliminating overloading).
-- Typechecking may be partial. For example, if working with arrays, - the typecheck code might simply check the type of the first array - element and use that to dispatch to the correct function. Subsequent - "in" typemaps would then perform more extensive type-checking.
-- Make sure you read the section on overloading in the " -SWIG and C++" chapter.
-10.14 More about %apply and -%clear
-In order to implement certain kinds of program behavior, it is - sometimes necessary to write sets of typemaps. For example, to support - output arguments, one often writes a set of typemaps like this:
+Related to structure member input, it may be desirable to return + structure members as a new kind of object. For example, in this + example, you will get very odd program behavior where the structure + member can be set nicely, but reading the member simply returns a + pointer:
++++>>> s = SomeObject() +>>> s.x = [1, 2.5, 5, 10] +>>> print s.x +_1008fea8_p_float +>>> ++To fix this, you can write an "out" typemap. For example:
--%typemap(in,numinputs=0) int *OUTPUT (int temp) { - $1 = &temp; -} -%typemap(argout) int *OUTPUT { - // return value somehow +%typemap(out) float [ANY] { + int i; + $result = PyList_New($1_dim0); + for (i = 0; i < $1_dim0; i++) { + PyObject *o = PyFloat_FromDouble((double) $1[i]); + PyList_SetItem($result,i,o); + } }To make it easier to apply the typemap to different argument types - and names, the %apply directive performs a copy of all - typemaps from one type to another. For example, if you specify this,
-+Now, you will find that member access is quite nice:
+--%apply int *OUTPUT { int *retvalue, int32 *output }; +>>> s = SomeObject() +>>> s.x = [1, 2.5, 5, 10] +>>> print s.x +[ 1, 2.5, 5, 10]then all of the int *OUTPUT typemaps are copied to int - *retvalue and int32 *output.
-However, there is a subtle aspect of %apply that needs more - description. Namely, %apply does not overwrite a typemap rule - if it is already defined for the target datatype. This behavior allows - you to do two things:
--
-- You can specialize parts of a complex typemap rule by first defining - a few typemaps and then using %apply to incorporate the - remaining pieces.
-- Sets of different typemaps can be applied to the same datatype using - repeated %apply directives.
-For example:
+Compatibility Note: SWIG1.1 used to provide a special + "memberout" typemap. However, it was mostly useless and has since been + eliminated. To return structure members, simply use the "out" typemap.
+11.6.2 Implementing constraints with + typemaps
+One particularly interesting application of typemaps is the + implementation of argument constraints. This can be done with the + "check" typemap. When used, this allows you to provide code for + checking the values of function arguments. For example:
--%typemap(in) int *INPUT (int temp) { - temp = ... get value from $input ...; - $1 = &temp; -} +%module math -%typemap(check) int *POSITIVE { - if (*$1 <= 0) { - SWIG_exception(SWIG_ValueError,"Expected a positive number!\n"); - return NULL; - } +%typemap(check) double posdouble { + if ($1 < 0) { + croak("Expecting a positive number"); + } } ... -%apply int *INPUT { int *invalue }; -%apply int *POSITIVE { int *invalue }; --Since %apply does not overwrite or replace any existing - rules, the only way to reset behavior is to use the %clear - directive. %clear removes all typemap rules defined for a - specific datatype. For example:
----%clear int *invalue; +double sqrt(double posdouble); +10.15 Passing data between typemaps
-It is also important to note that the primary use of local variables - is to create stack-allocated objects for temporary use inside a wrapper - function (this is faster and less-prone to error than allocating data - on the heap). In general, the variables are not intended to pass - information between different types of typemaps. However, this can be - done if you realize that local names have the argument number appended - to them. For example, you could do this:
+This provides a sanity check to your wrapper function. If a negative + number is passed to this function, a Perl exception will be raised and + your program terminated with an error message.
+This kind of checking can be particularly useful when working with + pointers. For example:
--%typemap(in) int *(int temp) { - temp = (int) PyInt_AsLong($input); - $1 = &temp; +%typemap(check) Vector * { + if ($1 == 0) { + PyErr_SetString(PyExc_TypeError,"NULL Pointer not allowed"); + return NULL; + } } -%typemap(argout) int * { - PyObject *o = PyInt_FromLong(temp$argnum); - ... -}In this case, the $argnum variable is expanded into the - argument number. Therefore, the code will reference the appropriate - local such as temp1 and temp2. It should be noted - that there are plenty of opportunities to break the universe here and - that accessing locals in this manner should probably be avoided. At the - very least, you should make sure that the typemaps sharing information - have exactly the same types and names.
-10.16 C++ "this" pointer
-All the rules discussed for typemaps apply to C++ as well as C. - However in addition C++ passes an extra parameter into every non-static - class method -- the this pointer. Occasionally it can be - useful to apply a typemap to this pointer (for example to check and - make sure this is non-null before deferencing). Actually, C - also has an the equivalent of the this pointer which is used - when accessing variables in a C struct.
-In order to customise the this pointer handling, target a - variable named self in your typemaps. self is the - name SWIG uses to refer to the extra parameter in wrapped functions.
-For example, if wrapping for Java generation:
+will prevent any function involving a Vector * from + accepting a NULL pointer. As a result, SWIG can often prevent a + potential segmentation faults or other run-time problems by raising an + exception rather than blindly passing values to the underlying C/C++ + program.
+11.7 Typemaps for multiple target languages +
+The code within typemaps is usually language dependent, however, + many target languages support the same typemaps. In order to + distinguish typemaps across different languages, the preprocessor + should be used. For example, the "in" typemap for Perl and Ruby could + be written as:
--%typemap(check) SWIGTYPE *self %{ -if (!$1) { - SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, - "invalid native object; delete() likely already called"); - return $null; -} -%} +#if defined(SWIGPERL) + %typemap(in) int "$1 = ($1_ltype) SvIV($input);" +#elif defined(SWIGRUBY) + %typemap(in) int "$1 = NUM2INT($input);" +#else + #warning no "in" typemap defined +#endifIn the above case, the $1 variable is expanded into the - argument name that SWIG is using as the this pointer. SWIG - will then insert the check code before the actual C++ class method is - called, and will raise an exception rather than crash the Java virtual - machine. The generated code will look something like:
+The full set of language specific macros is defined in the +Conditional Compilation section. The example above also shows a + common approach of issuing a warning for an as yet unsupported + language.
+Compatibility note: In SWIG-1.1 different languages could be + distinguished with the language name being put within the %typemap + directive, for example, +
+
%typemap(ruby,in) int "$1 = NUM2INT($input);".11.8 Optimal code generation when + returning by value
+The "out" typemap is the main typemap for return types. This typemap + supports an optional attribute flag called "optimal", which is for + reducing temporary variables and the amount of generated code, thereby + giving the compiler the opportunity to use return value optimization + for generating faster executing code. It only really makes a difference + when returning objects by value and has some limitations on usage, as + explained later on.
+When a function returns an object by value, SWIG generates code that + instantiates the default type on the stack then assigns the value + returned by the function call to it. A copy of this object is then made + on the heap and this is what is ultimately stored and used from the + target language. This will be clearer considering an example. Consider + running the following code through SWIG:
-- if (!arg1) { - SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, - "invalid native object; delete() likely already called"); - return ; +%typemap(out) SWIGTYPE %{ + $result = new $1_ltype((const $1_ltype &)$1); +%} + +%inline %{ +#include <iostream> +using namespace std; + +struct XX { + XX() { cout << "XX()" << endl; } + XX(int i) { cout << "XX(" << i << ")" << endl; } + XX(const XX &other) { cout << "XX(const XX &)" << endl; } + XX & operator =(const XX &other) { cout << "operator=(const XX &)" << endl; return *this; } + ~XX() { cout << "~XX()" << endl; } + static XX create() { + return XX(0); } - (arg1)->wrappedFunction(...); +}; +%}Note that if you have a parameter named self then it will - also match the typemap. One work around is to create an interface file - that wraps the method, but gives the argument a name other than -self.
-10.17 Where to go for more information?
-The best place to find out more information about writing typemaps - is to look in the SWIG library. Most language modules define all of - their default behavior using typemaps. These are found in files such as - python.swg, perl5.swg, tcl8.swg and so - forth. The typemaps.i file in the library also contains - numerous examples. You should look at these files to get a feel for how - to define typemaps of your own. Some of the language modules support - additional typemaps and further information is available in the - individual chapters for each target language. There you may also find - more hands-on practical examples.
-
-11 Customization Features
- - ----
+- Exception handling with - %exception - -
-- Object ownership and %newobject -
-- Features and the %feature - directive - -
-The "out" typemap shown is the default typemap for C# when returning + objects by value. When making a call to XX::create() from C#, + the output is as follows:
++- -+XX() +XX(0) +operator=(const XX &) +~XX() +XX(const XX &) +~XX() +~XX() +In many cases, it is desirable to change the default wrapping of - particular declarations in an interface. For example, you might want to - provide hooks for catching C++ exceptions, add assertions, or provide - hints to the underlying code generator. This chapter describes some of - these customization techniques. First, a discussion of exception - handling is presented. Then, a more general-purpose customization - mechanism known as "features" is described.
-11.1 Exception handling with - %exception
-The %exception directive allows you to define a general - purpose exception handler. For example, you can specify the following:
+Note that three objects are being created as well as an assignment. + Wouldn't it be great if the XX::create() method was the only + time a constructor was called? As the method returns by value, this is + asking a lot and the code that SWIG generates by default makes it + impossible for the compiler to use return value optimisation (RVO) +. However, this is where the "optimal" attribute in the "out" typemap + can help out. If the typemap code is kept the same and just the + "optimal" attribute specified like this:
--%exception { - try { - $action - } - catch (RangeError) { - ... handle error ... - } -} +%typemap(out, optimal="1") SWIGTYPE %{ + $result = new $1_ltype((const $1_ltype &)$1); +%}How the exception is handled depends on the target language, for - example, Python:
+then when the code is run again, the output is simply:
++++XX(0) +~XX() ++How the "optimal" attribute works is best explained using the + generated code. Without "optimal", the generated code is:
--%exception { - try { - $action - } - catch (RangeError) { - PyErr_SetString(PyExc_IndexError,"index out-of-bounds"); - SWIG_fail; - } +SWIGEXPORT void * SWIGSTDCALL CSharp_XX_create() { + void * jresult ; + XX result; + result = XX::create(); + jresult = new XX((const XX &)result); + return jresult; } +When defined, the code enclosed in braces is inserted directly into - the low-level wrapper functions. The special variable $action - is one of a few -%exception special variables supported and gets replaced with the - actual operation to be performed (a function call, method invocation, - attribute access, etc.). An exception handler remains in effect until - it is explicitly deleted. This is done by using either %exception - or %noexception with no code. For example:
+With the "optimal" attribute, the code is:
--%exception; // Deletes any previously defined handler +SWIGEXPORT void * SWIGSTDCALL CSharp_XX_create() { + void * jresult ; + jresult = new XX((const XX &)XX::create()); + return jresult; +}Compatibility note: Previous versions of SWIG used a special - directive %except for exception handling. That directive is - deprecated--%exception provides the same functionality, but is - substantially more flexible.
-11.1.1 Handling exceptions in C code
-C has no formal exception handling mechanism so there are several - approaches that might be used. A somewhat common technique is to simply - set a special error code. For example:
+The major difference is the result temporary variable + holding the value returned from XX::create() is no longer + generated and instead the copy constructor call is made directly from + the value returned by XX::create(). With modern compilers + implementing RVO, the copy is not actually done, in fact the object is + never created on the stack in XX::create() at all, it is + simply created directly on the heap. In the first instance, the $1 + special variable in the typemap is expanded into result. In + the second instance, $1 is expanded into XX::create() + and this is essentially what the "optimal" attribute is telling SWIG to + do.
+The "optimal" attribute optimisation is not turned on by default as + it has a number of restrictions. Firstly, some code cannot be condensed + into a simple call for passing into the copy constructor. One common + occurrence is when %exception is + used. Consider adding the following %exception to the example:
--/* File : except.c */ - -static char error_message[256]; -static int error_status = 0; - -void throw_exception(char *msg) { - strncpy(error_message,msg,256); - error_status = 1; -} - -void clear_exception() { - error_status = 0; -} -char *check_exception() { - if (error_status) return error_message; - else return NULL; +%exception XX::create() %{ +try { + $action +} catch(const std::exception &e) { + cout << e.what() << endl; } - +%}To use these functions, functions simply call throw_exception() - to indicate an error occurred. For example :
-+-SWIG can detect when the "optimal" attribute cannot be used and will + ignore it and in this case will issue the following warning:
+--double inv(double x) { - if (x != 0) return 1.0/x; - else { - throw_exception("Division by zero"); - return 0; - } +example.i:28: Warning 474: Method XX::create() usage of the optimal attribute ignored +example.i:14: Warning 474: in the out typemap as the following cannot be used to generate +optimal code: +try { + result = XX::create(); +} catch(const std::exception &e) { + cout << e.what() << endl; } -To catch the exception, you can write a simple exception handler - such as the following (shown for Perl5) :
+It should be clear that the above code cannot be used as the + argument to the copy constructor call, that is, for the $1 + substitution.
+Secondly, if the typemaps uses $1 more than once, then + multiple calls to the wrapped function will be made. Obviously that is + not very optimal. In fact SWIG attempts to detect this and will issue a + warning something like:
++++example.i:21: Warning 475: Multiple calls to XX::create() might be generated due to +example.i:7: Warning 475: optimal attribute usage in the out typemap. ++However, it doesn't always get it right, for example when $1 + is within some commented out code.
+11.9 Multi-argument + typemaps
+So far, the typemaps presented have focused on the problem of + dealing with single values. For example, converting a single input + object to a single argument in a function call. However, certain + conversion problems are difficult to handle in this manner. As an + example, consider the example at the very beginning of this chapter:
--%exception { - char *err; - clear_exception(); - $action - if ((err = check_exception())) { - croak(err); - } -} +int foo(int argc, char *argv[]);In this case, when an error occurs, it is translated into a Perl - error. Each target language has its own approach to creating a runtime - error/exception in and for Perl it is the croak method shown - above.
-11.1.2 Exception handling with - longjmp()
-Exception handling can also be added to C code using the -<setjmp.h> library. Here is a minimalistic implementation that - relies on the C preprocessor :
+Suppose that you wanted to wrap this function so that it accepted a + single list of strings like this:
++++>>> foo(["ale", "lager", "stout"]) ++To do this, you not only need to map a list of strings to char + *argv[], but the value of int argc is implicitly + determined by the length of the list. Using only simple typemaps, this + type of conversion is possible, but extremely painful. Multi-argument + typemaps help in this situation.
+A multi-argument typemap is a conversion rule that specifies how to + convert a single object in the target language to a set of + consecutive function arguments in C/C++. For example, the following + multi-argument maps perform the conversion described for the above + example:
--/* File : except.c - Just the declaration of a few global variables we're going to use */ - -#include <setjmp.h> -jmp_buf exception_buffer; -int exception_status; - -/* File : except.h */ -#include <setjmp.h> -extern jmp_buf exception_buffer; -extern int exception_status; - -#define try if ((exception_status = setjmp(exception_buffer)) == 0) -#define catch(val) else if (exception_status == val) -#define throw(val) longjmp(exception_buffer,val) -#define finally else - -/* Exception codes */ +%typemap(in) (int argc, char *argv[]) { + int i; + if (!PyList_Check($input)) { + PyErr_SetString(PyExc_ValueError, "Expecting a list"); + return NULL; + } + $1 = PyList_Size($input); + $2 = (char **) malloc(($1+1)*sizeof(char *)); + for (i = 0; i < $1; i++) { + PyObject *s = PyList_GetItem($input,i); + if (!PyString_Check(s)) { + free($2); + PyErr_SetString(PyExc_ValueError, "List items must be strings"); + return NULL; + } + $2[i] = PyString_AsString(s); + } + $2[i] = 0; +} -#define RangeError 1 -#define DivisionByZero 2 -#define OutOfMemory 3 +%typemap(freearg) (int argc, char *argv[]) { + if ($2) free($2); +} +/* Required for C++ method overloading */ +%typecheck(SWIG_TYPECHECK_STRING_ARRAY) (int argc, char *argv[]) { + $1 = PyList_Check($input) ? 1 : 0; +}Now, within a C program, you can do the following :
+A multi-argument map is always specified by surrounding the + arguments with parentheses as shown. For example:
--double inv(double x) { - if (x) return 1.0/x; - else throw(DivisionByZero); -} - +%typemap(in) (int argc, char *argv[]) { ... }Finally, to create a SWIG exception handler, write the following :
+Within the typemap code, the variables $1, $2, and + so forth refer to each type in the map. All of the usual substitutions + apply--just use the appropriate $1 or $2 prefix on + the variable name (e.g., $2_type, $1_ltype, etc.)
+Multi-argument typemaps always have precedence over simple typemaps + and SWIG always performs longest-match searching. Therefore, you will + get the following behavior:
--%{ -#include "except.h" -%} +%typemap(in) int argc { ... typemap 1 ... } +%typemap(in) (int argc, char *argv[]) { ... typemap 2 ... } +%typemap(in) (int argc, char *argv[], char *env[]) { ... typemap 3 ... } -%exception { - try { - $action - } catch(RangeError) { - croak("Range Error"); - } catch(DivisionByZero) { - croak("Division by zero"); - } catch(OutOfMemory) { - croak("Out of memory"); - } finally { - croak("Unknown exception"); - } -} +int foo(int argc, char *argv[]); // Uses typemap 2 +int bar(int argc, int x); // Uses typemap 1 +int spam(int argc, char *argv[], char *env[]); // Uses typemap 3Note: This implementation is only intended to illustrate the general - idea. To make it work better, you'll need to modify it to handle nested - try declarations.
-11.1.3 Handling C++ exceptions
-Handling C++ exceptions is also straightforward. For example:
+It should be stressed that multi-argument typemaps can appear + anywhere in a function declaration and can appear more than once. For + example, you could write this:
--%exception { - try { - $action - } catch(RangeError) { - croak("Range Error"); - } catch(DivisionByZero) { - croak("Division by zero"); - } catch(OutOfMemory) { - croak("Out of memory"); - } catch(...) { - croak("Unknown exception"); - } -} +%typemap(in) (int scount, char *swords[]) { ... } +%typemap(in) (int wcount, char *words[]) { ... } +void search_words(int scount, char *swords[], int wcount, char *words[], int maxcount);The exception types need to be declared as classes elsewhere, - possibly in a header file :
+Other directives such as %apply and %clear also + work with multi-argument maps. For example:
--class RangeError {}; -class DivisionByZero {}; -class OutOfMemory {}; +%apply (int argc, char *argv[]) { + (int scount, char *swords[]), + (int wcount, char *words[]) +}; +... +%clear (int scount, char *swords[]), (int wcount, char *words[]); +...11.1.4 Exception handlers - for variables
-By default all variables will ignore %exception, so it is - effectively turned off for all variables wrappers. This applies to - global variables, member variables and static member variables. The - approach is certainly a logical one when wrapping variables in C. - However, in C++, it is quite possible for an exception to be thrown - while the variable is being assigned. To ensure %exception is - used when wrapping variables, it needs to be 'turned on' using the -%allowexception feature. Note that %allowexception is just - a macro for %feature("allowexcept"), that is, it is a feature - called "allowexcept". Any variable which has this feature attached to - it, will then use the %exception feature, but of course, only - if there is a %exception attached to the variable in the first - place. The %allowexception feature works like any other - feature and so can be used globally or for selective variables.
+Don't forget to also provide a suitable +typemap for overloaded functions, such as %typecheck shown + for foo above. This is only required if the function is overloaded in + C++.
+Although multi-argument typemaps may seem like an exotic, little + used feature, there are several situations where they make sense. + First, suppose you wanted to wrap functions similar to the low-level +read() and write() system calls. For example:
--%allowexception; // turn on globally -%allowexception Klass::MyVar; // turn on for a specific variable +typedef unsigned int size_t; -%noallowexception Klass::MyVar; // turn off for a specific variable -%noallowexception; // turn off globally +int read(int fd, void *rbuffer, size_t len); +int write(int fd, void *wbuffer, size_t len);11.1.5 Defining different exception - handlers
-By default, the %exception directive creates an exception - handler that is used for all wrapper functions that follow it. Unless - there is a well-defined (and simple) error handling mechanism in place, - defining one universal exception handler may be unwieldy and result in - excessive code bloat since the handler is inlined into each wrapper - function.
-To fix this, you can be more selective about how you use the -%exception directive. One approach is to only place it around - critical pieces of code. For example:
+As is, the only way to use the functions would be to allocate memory + and pass some kind of pointer as the second argument---a process that + might require the use of a helper function. However, using + multi-argument maps, the functions can be transformed into something + more natural. For example, you might write typemaps like this:
--%exception { - ... your exception handler ... +// typemap for an outgoing buffer +%typemap(in) (void *wbuffer, size_t len) { + if (!PyString_Check($input)) { + PyErr_SetString(PyExc_ValueError, "Expecting a string"); + return NULL; + } + $1 = (void *) PyString_AsString($input); + $2 = PyString_Size($input); } -/* Define critical operations that can throw exceptions here */ -%exception; +// typemap for an incoming buffer +%typemap(in) (void *rbuffer, size_t len) { + if (!PyInt_Check($input)) { + PyErr_SetString(PyExc_ValueError, "Expecting an integer"); + return NULL; + } + $2 = PyInt_AsLong($input); + if ($2 < 0) { + PyErr_SetString(PyExc_ValueError, "Positive integer expected"); + return NULL; + } + $1 = (void *) malloc($2); +} -/* Define non-critical operations that don't throw exceptions */ +// Return the buffer. Discarding any previous return result +%typemap(argout) (void *rbuffer, size_t len) { + Py_XDECREF($result); /* Blow away any previous result */ + if (result < 0) { /* Check for I/O error */ + free($1); + PyErr_SetFromErrno(PyExc_IOError); + return NULL; + } + $result = PyString_FromStringAndSize($1,result); + free($1); +}More precise control over exception handling can be obtained by - attaching an exception handler to specific declaration name. For - example:
-+(note: In the above example, $result and result + are two different variables. result is the real C datatype + that was returned by the function. $result is the scripting + language object being returned to the interpreter.).
+Now, in a script, you can write code that simply passes buffers as + strings like this:
+--%exception allocate { - try { - $action - } - catch (MemoryError) { - croak("Out of memory"); - } -} +>>> f = example.open("Makefile") +>>> example.read(f,40) +'TOP = ../..\nSWIG = $(TOP)/.' +>>> example.read(f,40) +'./swig\nSRCS = example.c\nTARGET ' +>>> example.close(f) +0 +>>> g = example.open("foo", example.O_WRONLY | example.O_CREAT, 0644) +>>> example.write(g,"Hello world\n") +12 +>>> example.write(g,"This is a test\n") +15 +>>> example.close(g) +0 +>>>In this case, the exception handler is only attached to declarations - named "allocate". This would include both global and member functions. - The names supplied to %exception follow the same rules as for -%rename described in the section on -Ambiguity resolution and renaming. For example, if you wanted to - define an exception handler for a specific class, you might write this:
+A number of multi-argument typemap problems also arise in libraries + that perform matrix-calculations--especially if they are mapped onto + low-level Fortran or C code. For example, you might have a function + like this:
--%exception Object::allocate { - try { - $action - } - catch (MemoryError) { - croak("Out of memory"); - } -} +int is_symmetric(double *mat, int rows, int columns);When a class prefix is supplied, the exception handler is applied to - the corresponding declaration in the specified class as well as for - identically named functions appearing in derived classes.
-%exception can even be used to pinpoint a precise - declaration when overloading is used. For example:
+In this case, you might want to pass some kind of higher-level + object as an matrix. To do this, you could write a multi-argument + typemap like this:
--%exception Object::allocate(int) { - try { - $action - } - catch (MemoryError) { - croak("Out of memory"); - } +%typemap(in) (double *mat, int rows, int columns) { + MatrixObject *a; + a = GetMatrixFromObject($input); /* Get matrix somehow */ + + /* Get matrix properties */ + $1 = GetPointer(a); + $2 = GetRows(a); + $3 = GetColumns(a); }Attaching exceptions to specific declarations is a good way to - reduce code bloat. It can also be a useful way to attach exceptions to - specific parts of a header file. For example:
+This kind of technique can be used to hook into scripting-language + matrix packages such as Numeric Python. However, it should also be + stressed that some care is in order. For example, when crossing + languages you may need to worry about issues such as row-major vs. + column-major ordering (and perform conversions if needed). Note that + multi-argument typemaps cannot deal with non-consecutive C/C++ + arguments; a workaround such as a helper function re-ordering the + arguments to make them consecutive will need to be written.
+11.10 Typemap warnings
+Warnings can be added to typemaps so that SWIG generates a warning + message whenever the typemap is used. See the information in the +issuing warnings section.
+11.11 Typemap fragments
+The primary purpose of fragments is to reduce code bloat that + repeated use of typemap code can lead to. Fragments are snippets of + code that can be thought of as code dependencies of a typemap. If a + fragment is used by more than one typemap, then the snippet of code + within the fragment is only generated once. Code bloat is typically + reduced by moving typemap code into a support function and then placing + the support function into a fragment.
+For example, if you have a very long typemap
--%module example -%{ -#include "someheader.h" -%} +%typemap(in) MyClass * { + MyClass *value = 0; -// Define a few exception handlers for specific declarations -%exception Object::allocate(int) { - try { - $action - } - catch (MemoryError) { - croak("Out of memory"); - } -} + ... many lines of marshalling code ... -%exception Object::getitem { - try { - $action - } - catch (RangeError) { - croak("Index out of range"); - } + $result = value; } -... -// Read a raw header file -%include "someheader.h"Compatibility note: The %exception directive - replaces the functionality provided by the deprecated "except" typemap. - The typemap would allow exceptions to be thrown in the target language - based on the return type of a function and was intended to be a - mechanism for pinpointing specific declarations. However, it never - really worked that well and the new %exception directive is much - better.
-11.1.6 - Special variables for %exception
-The %exception directive supports a few special variables which are - placeholders for code substitution. The following table shows the - available special variables and details what the special variables are - replaced with.
--
-- $action The actual operation to be performed (a function - call, method invocation, variable access, etc.) - $name The C/C++ symbol name for the function. - $symname The symbol name used internally by SWIG - $overname The extra mangling used in the symbol name for - overloaded method. Expands to nothing if the wrapped method is not - overloaded. - $wrapname The language specific wrapper name (usually a - C function name exported from the shared object/dll) - $decl The fully qualified C/C++ declaration of the - method being wrapped without the return type - $fulldecl The fully qualified C/C++ declaration of the - method being wrapped including the return type - $parentname The parent class name (if any) for a method. -- $parentsymname The target language parent class name (if - any) for a method. The special variables are often used in situations where method - calls are logged. Exactly which form of the method call needs logging - is up to individual requirements, but the example code below shows all - the possible expansions, plus how an exception message could be - tailored to show the C++ method declaration:
+the same marshalling code is often repeated in several typemaps, + such as "in", "varin", "directorout", etc. SWIG copies the code for + each argument that requires the typemap code, easily leading to code + bloat in the generated code. To eliminate this, define a fragment that + includes the common marshalling code:
--%exception Special::something { - log("symname: $symname"); - log("overname: $overname"); - log("wrapname: $wrapname"); - log("decl: $decl"); - log("fulldecl: $fulldecl"); - try { - $action - } - catch (MemoryError) { - croak("Out of memory in $decl"); +%fragment("AsMyClass", "header") { + MyClass *AsMyClass(PyObject *obj) { + MyClass *value = 0; + + ... many lines of marshalling code ... + + return value; } } -void log(const char *message); -struct Special { - void something(const char *c); - void something(int i); -}; + +%typemap(in, fragment="AsMyClass") MyClass * { + $result = AsMyClass($input); +} + +%typemap(varin, fragment="AsMyClass") MyClass * { + $result = AsMyClass($input); +}Below shows the expansions for the 1st of the overloaded -something wrapper methods for Perl:
+When the "in" or "varin" typemaps for MyClass are required, the + contents of the fragment called "AsMyClass" is added to the "header" + section within the generated code, and then the typemap code is + emitted. Hence, the method AsMyClass will be generated into + the wrapper code before any typemap code that calls it.
+To define a fragment you need a fragment name, a section name for + generating the fragment code into, and the code itself. See +Code insertion blocks for a full list of section names. Usually the + section name used is "header". Different delimiters can be used:
-- log("symname: Special_something"); - log("overname: __SWIG_0"); - log("wrapname: _wrap_Special_something__SWIG_0"); - log("decl: Special::something(char const *)"); - log("fulldecl: void Special::something(char const *)"); - try { - (arg1)->something((char const *)arg2); - } - catch (MemoryError) { - croak("Out of memory in Special::something(char const *)"); - } +%fragment("my_name", "header") %{ ... %} +%fragment("my_name", "header") { ... } +%fragment("my_name", "header") " ... "11.1.7 Using The SWIG exception - library
-The exception.i library file provides support for creating - language independent exceptions in your interfaces. To use it, simply - put an "%include exception.i" in your interface file. This - creates a function SWIG_exception() that can be used to raise - common scripting language exceptions in a portable manner. For example - :
+and these follow the usual preprocessing rules mentioned in the +Preprocessing delimiters section. The following are some rules and + guidelines for using fragments:
++
- +
A fragment is added to the wrapping code only once. When using the +MyClass * typemaps above and wrapping the method:
--// Language independent exception handler -%include exception.i - -%exception { - try { - $action - } catch(RangeError) { - SWIG_exception(SWIG_ValueError, "Range Error"); - } catch(DivisionByZero) { - SWIG_exception(SWIG_DivisionByZero, "Division by zero"); - } catch(OutOfMemory) { - SWIG_exception(SWIG_MemoryError, "Out of memory"); - } catch(...) { - SWIG_exception(SWIG_RuntimeError,"Unknown exception"); - } -} - +void foo(MyClass *a, MyClass *b);As arguments, SWIG_exception() takes an error type code (an - integer) and an error message string. The currently supported error - types are :
-+the generated code will look something like:
+--SWIG_UnknownError -SWIG_IOError -SWIG_RuntimeError -SWIG_IndexError -SWIG_TypeError -SWIG_DivisionByZero -SWIG_OverflowError -SWIG_SyntaxError -SWIG_ValueError -SWIG_SystemError -SWIG_AttributeError -SWIG_MemoryError -SWIG_NullReferenceError +MyClass *AsMyClass(PyObject *obj) { + ... +} + +void _wrap_foo(...) { + .... + arg1 = AsMyClass(obj1); + arg2 = AsMyClass(obj2); + ... + foo(arg1, arg2); +}The SWIG_exception() function can also be used in typemaps.
-11.2 Object ownership and - %newobject
-A common problem in some applications is managing proper ownership - of objects. For example, consider a function like this:
+even as there is duplicated typemap code to process both a + and b, the AsMyClass method will be defined only + once.
+ +- +
+A fragment should only be defined once. If there is more than one + definition, the first definition is the one used. All other definitions + are silently ignored. For example, if you have
--Foo *blah() { - Foo *f = new Foo(); - return f; -} +%fragment("AsMyClass", "header") { ...definition 1... } +.... +%fragment("AsMyClass", "header") { ...definition 2... }If you wrap the function blah(), SWIG has no idea that the - return value is a newly allocated object. As a result, the resulting - extension module may produce a memory leak (SWIG is conservative and - will never delete objects unless it knows for certain that the returned - object was newly created).
-To fix this, you can provide an extra hint to the code generator - using the %newobject directive. For example:
+only the first definition is used. In this way you can override the + default fragments in a SWIG library by defining your fragment before + the library %include. Note that this behavior is the opposite + to typemaps, where the last typemap defined/applied prevails. Fragments + follow the first-in-first-out convention since they are intended to be + global, while typemaps are intended to be locally specialized.
+- +
+Fragment names cannot contain commas.
+- +
+A fragment can use one or more additional fragments, for example:
--%newobject blah; -Foo *blah(); +%fragment("<limits.h>", "header") { + %#include <limits.h> +} + + +%fragment("AsMyClass", "header", fragment="<limits.h>") { + MyClass *AsMyClass(PyObject *obj) { + MyClass *value = 0; + + ... some marshalling code ... + + if (ival < CHAR_MIN /*defined in <limits.h>*/) { + ... + } else { + ... + } + ... + return value; + } +}%newobject works exactly like %rename and -%exception. In other words, you can attach it to class members and - parameterized declarations as before. For example:
+in this case, when the "AsMyClass" fragment is emitted, it also + triggers the inclusion of the "<limits.h>" fragment.
+- +
+A fragment can have dependencies on a number of other fragments, for + example:
--%newobject ::blah(); // Only applies to global blah -%newobject Object::blah(int,double); // Only blah(int,double) in Object -%newobject *::copy; // Copy method in all classes -... +%fragment("bigfragment", "header", fragment="frag1", fragment="frag2", fragment="frag3") "";When %newobject is supplied, many language modules will - arrange to take ownership of the return value. This allows the value to - be automatically garbage-collected when it is no longer in use. - However, this depends entirely on the target language (a language - module may also choose to ignore the %newobject directive).
-Closely related to %newobject is a special typemap. The - "newfree" typemap can be used to deallocate a newly allocated return - value. It is only available on methods for which %newobject - has been applied and is commonly used to clean-up string results. For - example:
+When the "bigfragment" is used, the three dependent fragments + "frag1", "frag2" and "frag3" are also pulled in. Note that as + "bigframent" is empty (the empty string - ""), it does not add any code + itself, but merely triggers the inclusion of the other fragments.
+- +
+A typemap can also use more than one fragment, but since the syntax + is different, you need to specify the dependent fragments in a comma + separated list. Consider:
--%typemap(newfree) char * "free($1);"; -... -%newobject strdup; -... -char *strdup(const char *s); +%typemap(in, fragment="frag1,frag2,frag3") {...}In this case, the result of the function is a string in the target - language. Since this string is a copy of the original result, the data - returned by strdup() is no longer needed. The "newfree" - typemap in the example simply releases this memory.
-As a complement to the %newobject, from SWIG 1.3.28, you - can use the %delobject directive. For example, if you have two - methods, one to create objects and one to destroy them, you can use:
+which is equivalent to:
--%newobject create_foo; -%delobject destroy_foo; -... -Foo *create_foo(); -void destroy_foo(Foo *foo); +%typemap(in, fragment="bigfragment") {...}or in a member method as:
+when used with the "bigfragment" defined above.
+- +
+ +Finally, you can force the inclusion of a fragment at any point in + the generated code as follows:
--%delobject Foo::destroy; - -class Foo { -public: - void destroy() { delete this;} - -private: - ~Foo(); -}; +%fragment("bigfragment");%delobject instructs SWIG that the first argument passed to - the method will be destroyed, and therefore, the target language should - not attempt to deallocate it twice. This is similar to use the DISOWN - typemap in the first method argument, and in fact, it also depends on - the target language on implementing the 'disown' mechanism properly.
-The use of %newobject is also integrated with reference - counting and is covered in the C++ - reference counted objects section.
-Compatibility note: Previous versions of SWIG had a special -%new directive. However, unlike %newobject, it only - applied to the next declaration. For example:
+which is very useful inside a template class, for example.
+Most readers will probably want to skip the next two sub-sections on + advanced fragment usage unless a desire to really get to grips with + some powerful but tricky macro and fragment usage that is used in parts + of the SWIG typemap library.
+11.11.1 Fragment + type specialization
+Fragments can be type specialized. The syntax is as follows:
--%new char *strdup(const char *s); +%fragment("name", "header") { ...a type independent fragment... } +%fragment("name"{type}, "header") { ...a type dependent fragment... }For now this is still supported but is deprecated.
-How to shoot yourself in the foot: The %newobject - directive is not a declaration modifier like the old %new - directive. Don't write code like this:
+where type is a C/C++ type. Like typemaps, fragments can + also be used inside templates, for example:
--%newobject -char *strdup(const char *s); +template <class T> +struct A { + %fragment("incode"{A<T>}, "header") { + ... 'incode' specialized fragment ... + } + + %typemap(in, fragment="incode"{A<T>}) { + ... here we use the 'type specialized' fragment "incode"{A<T>} ... + } +};The results might not be what you expect.
-11.3 Features and the %feature - directive
-Both %exception and %newobject are examples of a - more general purpose customization mechanism known as "features." A - feature is simply a user-definable property that is attached to - specific declarations. Features are attached using the %feature - directive. For example:
+11.11.2 Fragments and + automatic typemap specialization
+Since fragments can be type specialized, they can be elegantly used + to specialize typemaps. For example, if you have something like:
--%feature("except") Object::allocate { - try { - $action - } - catch (MemoryError) { - croak("Out of memory"); - } +%fragment("incode"{float}, "header") { + float in_method_float(PyObject *obj) { + ... + } } -%feature("new","1") *::copy; +%fragment("incode"{long}, "header") { + float in_method_long(PyObject *obj) { + ... + } +} + +// %my_typemaps macro definition +%define %my_typemaps(Type) +%typemap(in, fragment="incode"{Type}) Type { + value = in_method_##Type(obj); +} +%enddef + +%my_typemaps(float); +%my_typemaps(long);In fact, the %exception and %newobject directives - are really nothing more than macros involving %feature:
-+then the proper "incode"{float} or "incode"{long} + fragment will be used, and the in_method_float and +in_method_long methods will be called whenever the float + or long types are used as input parameters.
+This feature is used a lot in the typemaps shipped in the SWIG + library for some scripting languages. The interested (or very brave) + reader can take a look at the fragments.swg file shipped with SWIG to + see this in action.
+11.12 The run-time type + checker
+Most scripting languages need type information at run-time. This + type information can include how to construct types, how to garbage + collect types, and the inheritance relationships between types. If the + language interface does not provide its own type information storage, + the generated SWIG code needs to provide it.
+Requirements for the type system:
++
+- Store inheritance and type equivalence information and be able to + correctly re-create the type pointer.
+- Share type information between modules.
+- Modules can be loaded in any order, regardless of actual type + dependency.
+- Avoid the use of dynamically allocated memory, and library/system + calls in general.
+- Provide a reasonably fast implementation, minimizing the lookup time + for all language modules.
+- Custom, language specific information can be attached to types.
+- Modules can be unloaded from the type system.
+11.12.1 Implementation
+The run-time type checker is used by many, but not all, of SWIG's + supported target languages. The run-time type checker features are not + required and are thus not used for statically typed languages such as + Java and C#. The scripting and scheme based languages rely on it and it + forms a critical part of SWIG's operation for these languages.
+When pointers, arrays, and objects are wrapped by SWIG, they are + normally converted into typed pointer objects. For example, an instance + of Foo * might be a string encoded like this:
+--#define %exception %feature("except") -#define %newobject %feature("new","1") +_108e688_p_FooThe name matching rules outlined in the -Ambiguity resolution and renaming section applies to all -%feature directives. In fact the %rename directive is just - a special form of %feature. The matching rules mean that - features are very flexible and can be applied with pinpoint accuracy to - specific declarations if needed. Additionally, if no declaration name - is given, a global feature is said to be defined. This feature is then - attached to every declaration that follows. This is how global - exception handlers are defined. For example:
+At a basic level, the type checker simply restores some type-safety + to extension modules. However, the type checker is also responsible for + making sure that wrapped C++ classes are handled correctly---especially + when inheritance is used. This is especially important when an + extension module makes use of multiple inheritance. For example:
--/* Define a global exception handler */ -%feature("except") { - try { - $action - } - ... -} +class Foo { + int x; +}; -... bunch of declarations ... +class Bar { + int y; +}; + +class FooBar : public Foo, public Bar { + int z; +};The %feature directive can be used with different syntax. - The following are all equivalent:
-+When the class FooBar is organized in memory, it contains + the contents of the classes Foo and Bar as well as + its own data members. For example:
+--%feature("except") Object::method { $action }; -%feature("except") Object::method %{ $action %}; -%feature("except") Object::method " $action "; -%feature("except","$action") Object::method; +FooBar --> | -----------| <-- Foo + | int x | + |------------| <-- Bar + | int y | + |------------| + | int z | + |------------|The syntax in the first variation will generate the { } - delimiters used whereas the other variations will not.
-11.3.1 Feature - attributes
-The %feature directive also accepts XML style attributes in - the same way that typemaps do. Any number of attributes can be - specified. The following is the generic syntax for features:
+Because of the way that base class data is stacked together, the + casting of a Foobar * to either of the base classes may change + the actual value of the pointer. This means that it is generally not + safe to represent pointers using a simple integer or a bare void * +---type tags are needed to implement correct handling of pointer values + (and to make adjustments when needed).
+In the wrapper code generated for each language, pointers are + handled through the use of special type descriptors and conversion + functions. For example, if you look at the wrapper code for Python, you + will see code like this:
--%feature("name","value", attribute1="AttributeValue1") symbol; -%feature("name", attribute1="AttributeValue1") symbol {value}; -%feature("name", attribute1="AttributeValue1") symbol %{value%}; -%feature("name", attribute1="AttributeValue1") symbol "value"; +if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_Foo,1)) == -1) return NULL;More than one attribute can be specified using a comma separated - list. The Java module is an example that uses attributes in -%feature("except"). The throws attribute specifies the - name of a Java class to add to a proxy method's throws clause. In the - following example, MyExceptionClass is the name of the Java - class for adding to the throws clause.
+In this code, SWIGTYPE_p_Foo is the type descriptor that + describes Foo *. The type descriptor is actually a pointer to + a structure that contains information about the type name to use in the + target language, a list of equivalent typenames (via typedef or + inheritance), and pointer value handling information (if applicable). + The SWIG_ConvertPtr() function is simply a utility function + that takes a pointer object in the target language and a + type-descriptor objects and uses this information to generate a C++ + pointer. However, the exact name and calling conventions of the + conversion function depends on the target language (see language + specific chapters for details).
+The actual type code is in swigrun.swg, and gets inserted near the + top of the generated swig wrapper file. The phrase "a type X that can + cast into a type Y" means that given a type X, it can be converted into + a type Y. In other words, X is a derived class of Y or X is a typedef + of Y. The structure to store type information looks like this:
--%feature("except", throws="MyExceptionClass") Object::method { - try { - $action - } catch (...) { - ... code to throw a MyExceptionClass Java exception ... - } -}; +/* Structure to store information on one type */ +typedef struct swig_type_info { + const char *name; /* mangled name of this type */ + const char *str; /* human readable name for this type */ + swig_dycast_func dcast; /* dynamic cast function down a hierarchy */ + struct swig_cast_info *cast; /* Linked list of types that can cast into this type */ + void *clientdata; /* Language specific type data */ +} swig_type_info; + +/* Structure to store a type and conversion function used for casting */ +typedef struct swig_cast_info { + swig_type_info *type; /* pointer to type that is equivalent to this type */ + swig_converter_func converter; /* function to cast the void pointers */ + struct swig_cast_info *next; /* pointer to next cast in linked list */ + struct swig_cast_info *prev; /* pointer to the previous cast */ +} swig_cast_info;Further details can be obtained from the -Java exception handling section.
-11.3.2 Feature flags
-Feature flags are used to enable or disable a particular feature. - Feature flags are a common but simple usage of %feature and - the feature value should be either 1 to enable or 0 - to disable the feature.
+Each swig_type_info stores a linked list of types that it + is equivalent to. Each entry in this doubly linked list stores a + pointer back to another swig_type_info structure, along with a pointer + to a conversion function. This conversion function is used to solve the + above problem of the FooBar class, correctly returning a pointer to the + type we want.
+The basic problem we need to solve is verifying and building + arguments passed to functions. So going back to the +SWIG_ConvertPtr() function example from above, we are expecting a +Foo * and need to check if obj0 is in fact a Foo * +. From before, SWIGTYPE_p_Foo is just a pointer to the +swig_type_info structure describing Foo *. So we loop + through the linked list of swig_cast_info structures attached + to SWIGTYPE_p_Foo. If we see that the type of obj0 is + in the linked list, we pass the object through the associated + conversion function and then return a positive. If we reach the end of + the linked list without a match, then obj0 can not be + converted to a Foo * and an error is generated.
+Another issue needing to be addressed is sharing type information + between multiple modules. More explicitly, we need to have ONE +swig_type_info for each type. If two modules both use the type, the + second module loaded must lookup and use the swig_type_info structure + from the module already loaded. Because no dynamic memory is used and + the circular dependencies of the casting information, loading the type + information is somewhat tricky, and not explained here. A complete + description is in the Lib/swiginit.swg file (and near the top + of any generated file).
+Each module has one swig_module_info structure which looks like + this:
--%feature("featurename") // enables feature -%feature("featurename", "1") // enables feature -%feature("featurename", "x") // enables feature -%feature("featurename", "0") // disables feature -%feature("featurename", "") // clears feature +/* Structure used to store module information + * Each module generates one structure like this, and the runtime collects + * all of these structures and stores them in a circularly linked list.*/ +typedef struct swig_module_info { + swig_type_info **types; /* Array of pointers to swig_type_info structs in this module */ + int size; /* Number of types in this module */ + struct swig_module_info *next; /* Pointer to next element in circularly linked list */ + swig_type_info **type_initial; /* Array of initially generated type structures */ + swig_cast_info **cast_initial; /* Array of initially generated casting structures */ + void *clientdata; /* Language specific module data */ +} swig_module_info;Actually any value other than zero will enable the feature. Note - that if the value is omitted completely, the default value becomes -1, thereby enabling the feature. A feature is cleared by specifying - no value, see Clearing - features. The %immutable directive described in the -Creating read-only variables section, is just a macro for -%feature("immutable"), and can be used to demonstrates feature - flags:
+Each module stores an array of pointers to swig_type_info + structures and the number of types in this module. So when a second + module is loaded, it finds the swig_module_info structure for + the first module and searches the array of types. If any of its own + types are in the first module and have already been loaded, it uses + those swig_type_info structures rather than creating new ones. + These swig_module_info structures are chained together in a + circularly linked list.
+11.12.2 Usage
+This section covers how to use these functions from typemaps. To + learn how to call these functions from external files (not the + generated _wrap.c file), see the +External access to the run-time system section.
+When pointers are converted in a typemap, the typemap code often + looks similar to this:
-- // features are disabled by default -int red; // mutable - -%feature("immutable"); // global enable -int orange; // immutable - -%feature("immutable","0"); // global disable -int yellow; // mutable - -%feature("immutable","1"); // another form of global enable -int green; // immutable - -%feature("immutable",""); // clears the global feature -int blue; // mutable +%typemap(in) Foo * { + if ((SWIG_ConvertPtr($input, (void **) &$1, $1_descriptor)) == -1) return NULL; +}Note that features are disabled by default and must be explicitly - enabled either globally or by specifying a targeted declaration. The - above intersperses SWIG directives with C code. Of course you can - target features explicitly, so the above could also be rewritten as:
+The most critical part is the typemap is the use of the +$1_descriptor special variable. When placed in a typemap, this is + expanded into the SWIGTYPE_* type descriptor object above. As + a general rule, you should always use $1_descriptor instead of + trying to hard-code the type descriptor name directly.
+There is another reason why you should always use the +$1_descriptor variable. When this special variable is expanded, + SWIG marks the corresponding type as "in use." When type-tables and + type information is emitted in the wrapper file, descriptor information + is only generated for those datatypes that were actually used in the + interface. This greatly reduces the size of the type tables and + improves efficiency.
+Occasionally, you might need to write a typemap that needs to + convert pointers of other types. To handle this, the special variable + macro $descriptor(type) covered earlier can be used to + generate the SWIG type descriptor name for any C datatype. For example:
--%feature("immutable","1") orange; -%feature("immutable","1") green; -int red; // mutable -int orange; // immutable -int yellow; // mutable -int green; // immutable -int blue; // mutable +%typemap(in) Foo * { + if ((SWIG_ConvertPtr($input, (void **) &$1, $1_descriptor)) == -1) { + Bar *temp; + if ((SWIG_ConvertPtr($input, (void **) &temp, $descriptor(Bar *)) == -1) { + return NULL; + } + $1 = (Foo *) temp; + } +}The above approach allows for the C declarations to be separated - from the SWIG directives for when the C declarations are parsed from a - C header file. The logic above can of course be inverted and rewritten - as:
+The primary use of $descriptor(type) is when writing + typemaps for container objects and other complex data structures. There + are some restrictions on the argument---namely it must be a fully + defined C datatype. It can not be any of the special typemap variables.
+In certain cases, SWIG may not generate type-descriptors like you + expect. For example, if you are converting pointers in some + non-standard way or working with an unusual combination of interface + files and modules, you may find that SWIG omits information for a + specific type descriptor. To fix this, you may need to use the +%types directive. For example:
--%feature("immutable","1"); -%feature("immutable","0") red; -%feature("immutable","0") yellow; -%feature("immutable","0") blue; -int red; // mutable -int orange; // immutable -int yellow; // mutable -int green; // immutable -int blue; // mutable +%types(int *, short *, long *, float *, double *);As hinted above for %immutable, most feature flags can also - be specified via alternative syntax. The alternative syntax is just a - macro in the swig.swg Library file. The following shows the - alternative syntax for the imaginary featurename feature:
+When %types is used, SWIG generates type-descriptor + information even if those datatypes never appear elsewhere in the + interface file.
+Further details about the run-time type checking can be found in the + documentation for individual language modules. Reading the source code + may also help. The file Lib/swigrun.swg in the SWIG library + contains all of the source of the generated code for type-checking. + This code is also included in every generated wrapped file so you + probably just look at the output of SWIG to get a better sense for how + types are managed.
+11.13 Typemaps and overloading
+This section does not apply to the statically typed languages like + Java and C#, where overloading of the types is handled much like C++ by + generating overloaded methods in the target language. In many of the + other target languages, SWIG still fully supports C++ overloaded + methods and functions. For example, if you have a collection of + functions like this:
--%featurename // equivalent to %feature("featurename", "1") ie enables feature -%nofeaturename // equivalent to %feature("featurename", "0") ie disables feature -%clearfeaturename // equivalent to %feature("featurename", "") ie clears feature +int foo(int x); +int foo(double x); +int foo(char *s, int y);The concept of clearing features is discussed next.
-11.3.3 Clearing - features
-A feature stays in effect until it is explicitly cleared. A feature - is cleared by supplying a %feature directive with no value. - For example %feature("name",""). A cleared feature means that - any feature exactly matching any previously defined feature is no - longer used in the name matching rules. So if a feature is cleared, it - might mean that another name matching rule will apply. To clarify, - let's consider the except feature again (%exception):
+You can access the functions in a normal way from the scripting + interpreter:
++++# Python +foo(3) # foo(int) +foo(3.5) # foo(double) +foo("hello",5) # foo(char *, int) + +# Tcl +foo 3 # foo(int) +foo 3.5 # foo(double) +foo hello 5 # foo(char *, int) ++To implement overloading, SWIG generates a separate wrapper function + for each overloaded method. For example, the above functions would + produce something roughly like this:
--// Define global exception handler -%feature("except") { - try { - $action - } catch (...) { - croak("Unknown C++ exception"); - } +// wrapper pseudocode +_wrap_foo_0(argc, args[]) { // foo(int) + int arg1; + int result; + ... + arg1 = FromInteger(args[0]); + result = foo(arg1); + return ToInteger(result); } -// Define exception handler for all clone methods to log the method calls -%feature("except") *::clone() { - try { - logger.info("$action"); - $action - } catch (...) { - croak("Unknown C++ exception"); - } +_wrap_foo_1(argc, args[]) { // foo(double) + double arg1; + int result; + ... + arg1 = FromDouble(args[0]); + result = foo(arg1); + return ToInteger(result); } -... initial set of class declarations with clone methods ... - -// clear the previously defined feature -%feature("except","") *::clone(); +_wrap_foo_2(argc, args[]) { // foo(char *, int) + char *arg1; + int arg2; + int result; + ... + arg1 = FromString(args[0]); + arg2 = FromInteger(args[1]); + result = foo(arg1,arg2); + return ToInteger(result); +} -... final set of class declarations with clone methods ...In the above scenario, the initial set of clone methods will log all - method invocations from the target language. This specific feature is - cleared for the final set of clone methods. However, these clone - methods will still have an exception handler (without logging) as the - next best feature match for them is the global exception handler.
-Note that clearing a feature is not always the same as disabling it. - Clearing the feature above with %feature("except","") *::clone() - is not the same as specifying %feature("except","0") *::clone() -. The former will disable the feature for clone methods - the feature is - still a better match than the global feature. If on the other hand, no - global exception handler had been defined at all, then clearing the - feature would be the same as disabling it as no other feature would - have matched.
-Note that the feature must match exactly for it to be cleared by any - previously defined feature. For example the following attempt to clear - the initial feature will not work:
+Next, a dynamic dispatch function is generated:
--%feature("except") clone() { logger.info("$action"); $action } -%feature("except","") *::clone(); +_wrap_foo(argc, args[]) { + if (argc == 1) { + if (IsInteger(args[0])) { + return _wrap_foo_0(argc,args); + } + if (IsDouble(args[0])) { + return _wrap_foo_1(argc,args); + } + } + if (argc == 2) { + if (IsString(args[0]) && IsInteger(args[1])) { + return _wrap_foo_2(argc,args); + } + } + error("No matching function!\n"); +}but this will:
-+@@ -21281,19 +22901,19 @@ void Shape::move(double dx, double dy) { int Shape::nshapes = 0; -double Circle::area(void) { +double Circle::area() { return M_PI*radius*radius; } -double Circle::perimeter(void) { +double Circle::perimeter() { return 2*M_PI*radius; } -double Square::area(void) { +double Square::area() { return width*width; } -double Square::perimeter(void) { +double Square::perimeter() { return 4*width; } @@ -21518,14 +23138,14 @@ $ adb install bin/SwigClass-debug.apkThe purpose of the dynamic dispatch function is to select the + appropriate C++ function based on argument types---a task that must be + performed at runtime in most of SWIG's target languages.
+The generation of the dynamic dispatch function is a relatively + tricky affair. Not only must input typemaps be taken into account + (these typemaps can radically change the types of arguments accepted), + but overloaded methods must also be sorted and checked in a very + specific order to resolve potential ambiguity. A high-level overview of + this ranking process is found in the "SWIG and C++ +" chapter. What isn't mentioned in that chapter is the mechanism by + which it is implemented---as a collection of typemaps.
+To support dynamic dispatch, SWIG first defines a general purpose + type hierarchy as follows:
+--%feature("except") clone() { logger.info("$action"); $action } -%feature("except","") clone(); +Symbolic Name Precedence Value +------------------------------ ------------------ +SWIG_TYPECHECK_POINTER 0 +SWIG_TYPECHECK_VOIDPTR 10 +SWIG_TYPECHECK_BOOL 15 +SWIG_TYPECHECK_UINT8 20 +SWIG_TYPECHECK_INT8 25 +SWIG_TYPECHECK_UINT16 30 +SWIG_TYPECHECK_INT16 35 +SWIG_TYPECHECK_UINT32 40 +SWIG_TYPECHECK_INT32 45 +SWIG_TYPECHECK_UINT64 50 +SWIG_TYPECHECK_INT64 55 +SWIG_TYPECHECK_UINT128 60 +SWIG_TYPECHECK_INT128 65 +SWIG_TYPECHECK_INTEGER 70 +SWIG_TYPECHECK_FLOAT 80 +SWIG_TYPECHECK_DOUBLE 90 +SWIG_TYPECHECK_COMPLEX 100 +SWIG_TYPECHECK_UNICHAR 110 +SWIG_TYPECHECK_UNISTRING 120 +SWIG_TYPECHECK_CHAR 130 +SWIG_TYPECHECK_STRING 140 +SWIG_TYPECHECK_BOOL_ARRAY 1015 +SWIG_TYPECHECK_INT8_ARRAY 1025 +SWIG_TYPECHECK_INT16_ARRAY 1035 +SWIG_TYPECHECK_INT32_ARRAY 1045 +SWIG_TYPECHECK_INT64_ARRAY 1055 +SWIG_TYPECHECK_INT128_ARRAY 1065 +SWIG_TYPECHECK_FLOAT_ARRAY 1080 +SWIG_TYPECHECK_DOUBLE_ARRAY 1090 +SWIG_TYPECHECK_CHAR_ARRAY 1130 +SWIG_TYPECHECK_STRING_ARRAY 1140SWIG provides macros for disabling and clearing features. Many of - these can be found in the swig.swg library file. The typical - pattern is to define three macros; one to define the feature itself, - one to disable the feature and one to clear the feature. The three - macros below show this for the "except" feature:
+(These precedence levels are defined in swig.swg, a library + file that's included by all target language modules.)
+In this table, the precedence-level determines the order in which + types are going to be checked. Low values are always checked before + higher values. For example, integers are checked before floats, single + values are checked before arrays, and so forth.
+Using the above table as a guide, each target language defines a + collection of "typecheck" typemaps. The following excerpt from the + Python module illustrates this:
--#define %exception %feature("except") -#define %noexception %feature("except","0") -#define %clearexception %feature("except","") +/* Python type checking rules */ +/* Note: %typecheck(X) is a macro for %typemap(typecheck,precedence=X) */ + +%typecheck(SWIG_TYPECHECK_INTEGER) + int, short, long, + unsigned int, unsigned short, unsigned long, + signed char, unsigned char, + long long, unsigned long long, + const int &, const short &, const long &, + const unsigned int &, const unsigned short &, const unsigned long &, + const long long &, const unsigned long long &, + enum SWIGTYPE, + bool, const bool & +{ + $1 = (PyInt_Check($input) || PyLong_Check($input)) ? 1 : 0; +} + +%typecheck(SWIG_TYPECHECK_DOUBLE) + float, double, + const float &, const double & +{ + $1 = (PyFloat_Check($input) || PyInt_Check($input) || PyLong_Check($input)) ? 1 : 0; +} + +%typecheck(SWIG_TYPECHECK_CHAR) char { + $1 = (PyString_Check($input) && (PyString_Size($input) == 1)) ? 1 : 0; +} + +%typecheck(SWIG_TYPECHECK_STRING) char * { + $1 = PyString_Check($input) ? 1 : 0; +} + +%typecheck(SWIG_TYPECHECK_POINTER) SWIGTYPE *, SWIGTYPE &, SWIGTYPE [] { + void *ptr; + if (SWIG_ConvertPtr($input, (void **) &ptr, $1_descriptor, 0) == -1) { + $1 = 0; + PyErr_Clear(); + } else { + $1 = 1; + } +} + +%typecheck(SWIG_TYPECHECK_POINTER) SWIGTYPE { + void *ptr; + if (SWIG_ConvertPtr($input, (void **) &ptr, $&1_descriptor, 0) == -1) { + $1 = 0; + PyErr_Clear(); + } else { + $1 = 1; + } +} + +%typecheck(SWIG_TYPECHECK_VOIDPTR) void * { + void *ptr; + if (SWIG_ConvertPtr($input, (void **) &ptr, 0, 0) == -1) { + $1 = 0; + PyErr_Clear(); + } else { + $1 = 1; + } +} + +%typecheck(SWIG_TYPECHECK_POINTER) PyObject * +{ + $1 = ($input != 0); +}11.3.4 Features - and default arguments
-SWIG treats methods with default arguments as separate overloaded - methods as detailed in the default - arguments section. Any %feature targeting a method with - default arguments will apply to all the extra overloaded methods that - SWIG generates if the default arguments are specified in the feature. - If the default arguments are not specified in the feature, then the - feature will match that exact wrapper method only and not the extra - overloaded methods that SWIG generates. For example:
+It might take a bit of contemplation, but this code has merely + organized all of the basic C++ types, provided some simple + type-checking code, and assigned each type a precedence value.
+Finally, to generate the dynamic dispatch function, SWIG uses the + following algorithm:
++
+- Overloaded methods are first sorted by the number of required + arguments.
+- Methods with the same number of arguments are then sorted by + precedence values of argument types.
+- Typecheck typemaps are then emitted to produce a dispatch function + that checks arguments in the correct order.
+If you haven't written any typemaps of your own, it is unnecessary + to worry about the typechecking rules. However, if you have written new + input typemaps, you might have to supply a typechecking rule as well. + An easy way to do this is to simply copy one of the existing + typechecking rules. Here is an example,
--%feature("except") void hello(int i=0, double d=0.0) { ... } -void hello(int i=0, double d=0.0); +// Typemap for a C++ string +%typemap(in) std::string { + if (PyString_Check($input)) { + $1 = std::string(PyString_AsString($input)); + } else { + SWIG_exception(SWIG_TypeError, "string expected"); + } +} +// Copy the typecheck code for "char *". +%typemap(typecheck) std::string = char *;will apply the feature to all three wrapper methods, that is:
+The bottom line: If you are writing new typemaps and you are using + overloaded methods, you will probably have to write new typecheck code + or copy and modify existing typecheck code.
+If you write a typecheck typemap and omit the precedence level, for + example commenting it out as shown below:
--void hello(int i, double d); -void hello(int i); -void hello(); +%typemap(typecheck /*,precedence=SWIG_TYPECHECK_INTEGER*/) int { + $1 = PyInt_Check($input) ? 1 : 0; +}If the default arguments are not specified in the feature:
-+@@ -21210,7 +22830,7 @@ $ adb install bin/SwigSimple-debug.apk below, showing the result of calls into the C code:then the type is given a precedence higher than any other known + precedence level and a warning is issued:
+--%feature("except") void hello(int i, double d) { ... } -void hello(int i=0, double d=0.0); +example.i:18: Warning 467: Overloaded method foo(int) not supported (incomplete type checking rule - no precedence level in typecheck typemap for 'int').then the feature will only apply to this wrapper method:
+Notes:
++
+- Typecheck typemaps are not used for non-overloaded methods. Because + of this, it is still always necessary to check types in any "in" + typemaps.
+- The dynamic dispatch process is only meant to be a heuristic. There + are many corner cases where SWIG simply can't disambiguate types to the + same degree as C++. The only way to resolve this ambiguity is to use + the %rename directive to rename one of the overloaded methods + (effectively eliminating overloading).
+- Typechecking may be partial. For example, if working with arrays, + the typecheck code might simply check the type of the first array + element and use that to dispatch to the correct function. Subsequent + "in" typemaps would then perform more extensive type-checking.
+- Make sure you read the section on overloading in the " +SWIG and C++" chapter.
+11.14 More about %apply and %clear
+In order to implement certain kinds of program behavior, it is + sometimes necessary to write sets of typemaps. For example, to support + output arguments, one often writes a set of typemaps like this:
--void hello(int i, double d); +%typemap(in,numinputs=0) int *OUTPUT (int temp) { + $1 = &temp; +} +%typemap(argout) int *OUTPUT { + // return value somehow +}and not these wrapper methods:
+To make it easier to apply the typemap to different argument types + and names, the %apply directive performs a copy of all + typemaps from one type to another. For example, if you specify this,
--void hello(int i); -void hello(); +%apply int *OUTPUT { int *retvalue, int32 *output };If compactdefaultargs are being - used, then the difference between specifying or not specifying default - arguments in a feature is not applicable as just one wrapper is - generated.
-Compatibility note: The different behaviour of features - specified with or without default arguments was introduced in - SWIG-1.3.23 when the approach to wrapping methods with default - arguments was changed.
-11.3.5 Feature example
-As has been shown earlier, the intended use for the %feature - directive is as a highly flexible customization mechanism that can be - used to annotate declarations with additional information for use by - specific target language modules. Another example is in the Python - module. You might use %feature to rewrite proxy/shadow class - code as follows:
+then all of the int *OUTPUT typemaps are copied to int + *retvalue and int32 *output.
+However, there is a subtle aspect of %apply that needs more + description. Namely, %apply does not overwrite a typemap rule + if it is already defined for the target datatype. This behavior allows + you to do two things:
++
+- You can specialize parts of a complex typemap rule by first defining + a few typemaps and then using %apply to incorporate the + remaining pieces.
+- Sets of different typemaps can be applied to the same datatype using + repeated %apply directives.
+For example:
+-%module example -%rename(bar_id) bar(int,double); +%typemap(in) int *INPUT (int temp) { + temp = ... get value from $input ...; + $1 = &temp; +} -// Rewrite bar() to allow some nice overloading +%typemap(check) int *POSITIVE { + if (*$1 <= 0) { + SWIG_exception(SWIG_ValueError,"Expected a positive number!\n"); + return NULL; + } +} -%feature("shadow") Foo::bar(int) %{ -def bar(*args): - if len(args) == 3: - return apply(examplec.Foo_bar_id,args) - return apply(examplec.Foo_bar,args) -%} - -class Foo { -public: - int bar(int x); - int bar(int x, double y); +... +%apply int *INPUT { int *invalue }; +%apply int *POSITIVE { int *invalue }; ++Since %apply does not overwrite or replace any existing + rules, the only way to reset behavior is to use the %clear + directive. %clear removes all typemap rules defined for a + specific datatype. For example:
++++%clear int *invalue; ++11.15 Passing data between typemaps
+It is also important to note that the primary use of local variables + is to create stack-allocated objects for temporary use inside a wrapper + function (this is faster and less-prone to error than allocating data + on the heap). In general, the variables are not intended to pass + information between different types of typemaps. However, this can be + done if you realize that local names have the argument number appended + to them. For example, you could do this:
++-+%typemap(in) int *(int temp) { + temp = (int) PyInt_AsLong($input); + $1 = &temp; +} + +%typemap(argout) int * { + PyObject *o = PyInt_FromLong(temp$argnum); + ... }Further details of %feature usage is described in the - documentation for specific language modules.
+In this case, the $argnum variable is expanded into the + argument number. Therefore, the code will reference the appropriate + local such as temp1 and temp2. It should be noted + that there are plenty of opportunities to break the universe here and + that accessing locals in this manner should probably be avoided. At the + very least, you should make sure that the typemaps sharing information + have exactly the same types and names.
+11.16 C++ "this" pointer
+All the rules discussed for typemaps apply to C++ as well as C. + However in addition C++ passes an extra parameter into every non-static + class method -- the this pointer. Occasionally it can be + useful to apply a typemap to this pointer (for example to check and + make sure this is non-null before deferencing). Actually, C + also has an the equivalent of the this pointer which is used + when accessing variables in a C struct.
+In order to customise the this pointer handling, target a + variable named self in your typemaps. self is the + name SWIG uses to refer to the extra parameter in wrapped functions.
+For example, if wrapping for Java generation:
++++%typemap(check) SWIGTYPE *self %{ +if (!$1) { + SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, + "invalid native object; delete() likely already called"); + return $null; +} +%} ++In the above case, the $1 variable is expanded into the + argument name that SWIG is using as the this pointer. SWIG + will then insert the check code before the actual C++ class method is + called, and will raise an exception rather than crash the Java virtual + machine. The generated code will look something like:
++++ if (!arg1) { + SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, + "invalid native object; delete() likely already called"); + return ; + } + (arg1)->wrappedFunction(...); ++Note that if you have a parameter named self then it will + also match the typemap. One work around is to create an interface file + that wraps the method, but gives the argument a name other than +self.
+11.17 Where to go for more information?
+The best place to find out more information about writing typemaps + is to look in the SWIG library. Most language modules define all of + their default behavior using typemaps. These are found in files such as + python.swg, perl5.swg, tcl8.swg and so + forth. The typemaps.i file in the library also contains + numerous examples. You should look at these files to get a feel for how + to define typemaps of your own. Some of the language modules support + additional typemaps and further information is available in the + individual chapters for each target language. There you may also find + more hands-on practical examples.
-12 Contracts
+12 Customization Features
-A common problem that arises when wrapping C libraries is that of - maintaining reliability and checking for errors. The fact of the matter - is that many C programs are notorious for not providing error checks. - Not only that, when you expose the internals of an application as a - library, it often becomes possible to crash it simply by providing bad - inputs or using it in a way that wasn't intended.
-This chapter describes SWIG's support for software contracts. In the - context of SWIG, a contract can be viewed as a runtime constraint that - is attached to a declaration. For example, you can easily attach - argument checking rules, check the output values of a function and - more. When one of the rules is violated by a script, a runtime - exception is generated rather than having the program continue to - execute.
-12.1 The %contract directive
-Contracts are added to a declaration using the %contract directive. - Here is a simple example:
+In many cases, it is desirable to change the default wrapping of + particular declarations in an interface. For example, you might want to + provide hooks for catching C++ exceptions, add assertions, or provide + hints to the underlying code generator. This chapter describes some of + these customization techniques. First, a discussion of exception + handling is presented. Then, a more general-purpose customization + mechanism known as "features" is described.
+12.1 Exception handling with + %exception
+The %exception directive allows you to define a general + purpose exception handler. For example, you can specify the following:
--%contract sqrt(double x) { -require: - x >= 0; -ensure: - sqrt >= 0; +%exception { + try { + $action + } + catch (RangeError) { + ... handle error ... + } } - -... -double sqrt(double); --In this case, a contract is being added to the sqrt() - function. The %contract directive must always appear before - the declaration in question. Within the contract there are two - sections, both of which are optional. The require: section - specifies conditions that must hold before the function is called. - Typically, this is used to check argument values. The ensure: - section specifies conditions that must hold after the function is - called. This is often used to check return values or the state of the - program. In both cases, the conditions that must hold must be specified - as boolean expressions.
-In the above example, we're simply making sure that sqrt() returns a - non-negative number (if it didn't, then it would be broken in some - way).
-Once a contract has been specified, it modifies the behavior of the - resulting module. For example:
---->>> example.sqrt(2) -1.4142135623730951 ->>> example.sqrt(-2) -Traceback (most recent call last): - File "<stdin>", line 1, in ? -RuntimeError: Contract violation: require: (arg1>=0) ->>>12.2 %contract and classes
-The %contract directive can also be applied to class - methods and constructors. For example:
+How the exception is handled depends on the target language, for + example, Python:
--%contract Foo::bar(int x, int y) { -require: - x > 0; -ensure: - bar > 0; -} - -%contract Foo::Foo(int a) { -require: - a > 0; +%exception { + try { + $action + } + catch (RangeError) { + PyErr_SetString(PyExc_IndexError,"index out-of-bounds"); + SWIG_fail; + } } - -class Foo { -public: - Foo(int); - int bar(int, int); -};The way in which %contract is applied is exactly the same - as the %feature directive. Thus, any contract that you - specified for a base class will also be attached to inherited methods. - For example:
+When defined, the code enclosed in braces is inserted directly into + the low-level wrapper functions. The special variable $action + is one of a few +%exception special variables supported and gets replaced with the + actual operation to be performed (a function call, method invocation, + attribute access, etc.). An exception handler remains in effect until + it is explicitly deleted. This is done by using either %exception + or %noexception with no code. For example:
--class Spam : public Foo { -public: - int bar(int,int); // Gets contract defined for Foo::bar(int,int) -}; +%exception; // Deletes any previously defined handlerIn addition to this, separate contracts can be applied to both the - base class and a derived class. For example:
+Compatibility note: Previous versions of SWIG used a special + directive %except for exception handling. That directive is + deprecated--%exception provides the same functionality, but is + substantially more flexible.
+12.1.1 Handling exceptions in C code
+C has no formal exception handling mechanism so there are several + approaches that might be used. A somewhat common technique is to simply + set a special error code. For example:
--%contract Foo::bar(int x, int) { -require: - x > 0; -} +/* File : except.c */ -%contract Spam::bar(int, int y) { -require: - y > 0; +static char error_message[256]; +static int error_status = 0; + +void throw_exception(char *msg) { + strncpy(error_message,msg,256); + error_status = 1; } -class Foo { -public: - int bar(int,int); // Gets Foo::bar contract. -}; +void clear_exception() { + error_status = 0; +} +char *check_exception() { + if (error_status) + return error_message; + else + return NULL; +} -class Spam : public Foo { -public: - int bar(int,int); // Gets Foo::bar and Spam::bar contract -};When more than one contract is applied, the conditions specified in - a "require:" section are combined together using a logical-AND - operation. In other words conditions specified for the base class and - conditions specified for the derived class all must hold. In the above - example, this means that both the arguments to Spam::bar must - be positive.
-12.3 Constant aggregation and - %aggregate_check
-Consider an interface file that contains the following code:
+To use these functions, functions simply call throw_exception() + to indicate an error occurred. For example :
--#define UP 1 -#define DOWN 2 -#define RIGHT 3 -#define LEFT 4 - -void move(SomeObject *, int direction, int distance); +double inv(double x) { + if (x != 0) + return 1.0/x; + else { + throw_exception("Division by zero"); + return 0; + } +}One thing you might want to do is impose a constraint on the - direction parameter to make sure it's one of a few accepted values. To - do that, SWIG provides an easy to use macro %aggregate_check() that - works like this:
+To catch the exception, you can write a simple exception handler + such as the following (shown for Perl5) :
--%aggregate_check(int, check_direction, UP, DOWN, LEFT, RIGHT); +%exception { + char *err; + clear_exception(); + $action + if ((err = check_exception())) { + croak(err); + } +}This merely defines a utility function of the form
+In this case, when an error occurs, it is translated into a Perl + error. Each target language has its own approach to creating a runtime + error/exception in and for Perl it is the croak method shown + above.
+12.1.2 Exception handling with longjmp() +
+Exception handling can also be added to C code using the +<setjmp.h> library. Here is a minimalistic implementation that + relies on the C preprocessor :
--int check_direction(int x); +/* File : except.c + Just the declaration of a few global variables we're going to use */ + +#include <setjmp.h> +jmp_buf exception_buffer; +int exception_status; + +/* File : except.h */ +#include <setjmp.h> +extern jmp_buf exception_buffer; +extern int exception_status; + +#define try if ((exception_status = setjmp(exception_buffer)) == 0) +#define catch(val) else if (exception_status == val) +#define throw(val) longjmp(exception_buffer,val) +#define finally else + +/* Exception codes */ + +#define RangeError 1 +#define DivisionByZero 2 +#define OutOfMemory 3 +That checks the argument x to see if it is one of the values listed. - This utility function can be used in contracts. For example:
+Now, within a C program, you can do the following :
--%aggregate_check(int, check_direction, UP, DOWN, RIGHT, LEFT); - -%contract move(SomeObject *, int direction, in) { -require: - check_direction(direction); +double inv(double x) { + if (x) + return 1.0/x; + else + throw(DivisionByZero); } -#define UP 1 -#define DOWN 2 -#define RIGHT 3 -#define LEFT 4 - -void move(SomeObject *, int direction, int distance);Alternatively, it can be used in typemaps and other directives. For - example:
+Finally, to create a SWIG exception handler, write the following :
--%aggregate_check(int, check_direction, UP, DOWN, RIGHT, LEFT); +%{ +#include "except.h" +%} -%typemap(check) int direction { - if (!check_direction($1)) SWIG_exception(SWIG_ValueError, "Bad direction"); +%exception { + try { + $action + } catch(RangeError) { + croak("Range Error"); + } catch(DivisionByZero) { + croak("Division by zero"); + } catch(OutOfMemory) { + croak("Out of memory"); + } finally { + croak("Unknown exception"); + } } - -#define UP 1 -#define DOWN 2 -#define RIGHT 3 -#define LEFT 4 - -void move(SomeObject *, int direction, int distance);Regrettably, there is no automatic way to perform similar checks - with enums values. Maybe in a future release.
-12.4 Notes
-Contract support was implemented by Songyan (Tiger) Feng and first - appeared in SWIG-1.3.20.
-
-13 Variable Length Arguments
- - -- -- -(a.k.a, "The horror. The horror.")
-This chapter describes the problem of wrapping functions that take a - variable number of arguments. For instance, generating wrappers for the - C printf() family of functions.
-This topic is sufficiently advanced to merit its own chapter. In - fact, support for varargs is an often requested feature that was first - added in SWIG-1.3.12. Most other wrapper generation tools have wisely - chosen to avoid this issue.
-13.1 Introduction
-Some C and C++ programs may include functions that accept a variable - number of arguments. For example, most programmers are familiar with - functions from the C library such as the following:
+Note: This implementation is only intended to illustrate the general + idea. To make it work better, you'll need to modify it to handle nested + try declarations.
+12.1.3 Handling C++ exceptions
+Handling C++ exceptions is also straightforward. For example:
--int printf(const char *fmt, ...) -int fprintf(FILE *, const char *fmt, ...); -int sprintf(char *s, const char *fmt, ...); +%exception { + try { + $action + } catch(RangeError) { + croak("Range Error"); + } catch(DivisionByZero) { + croak("Division by zero"); + } catch(OutOfMemory) { + croak("Out of memory"); + } catch(...) { + croak("Unknown exception"); + } +} +Although there is probably little practical purpose in wrapping - these specific C library functions in a scripting language (what would - be the point?), a library may include its own set of special functions - based on a similar API. For example:
+The exception types need to be declared as classes elsewhere, + possibly in a header file :
--int traceprintf(const char *fmt, ...); +class RangeError {}; +class DivisionByZero {}; +class OutOfMemory {};In this case, you may want to have some kind of access from the - target language.
-Before describing the SWIG implementation, it is important to - discuss the common uses of varargs that you are likely to encounter in - real programs. Obviously, there are the printf() style output - functions as shown. Closely related to this would be scanf() - style input functions that accept a format string and a list of - pointers into which return values are placed. However, variable length - arguments are also sometimes used to write functions that accept a - NULL-terminated list of pointers. A good example of this would be a - function like this:
+12.1.4 Exception handlers for + variables
+By default all variables will ignore %exception, so it is + effectively turned off for all variables wrappers. This applies to + global variables, member variables and static member variables. The + approach is certainly a logical one when wrapping variables in C. + However, in C++, it is quite possible for an exception to be thrown + while the variable is being assigned. To ensure %exception is + used when wrapping variables, it needs to be 'turned on' using the +%allowexception feature. Note that %allowexception is just + a macro for %feature("allowexcept"), that is, it is a feature + called "allowexcept". Any variable which has this feature attached to + it, will then use the %exception feature, but of course, only + if there is a %exception attached to the variable in the first + place. The %allowexception feature works like any other + feature and so can be used globally or for selective variables.
--int execlp(const char *path, const char *arg1, ...); -... +%allowexception; // turn on globally +%allowexception Klass::MyVar; // turn on for a specific variable -/* Example */ -execlp("ls","ls","-l",NULL); +%noallowexception Klass::MyVar; // turn off for a specific variable +%noallowexception; // turn off globallyIn addition, varargs is sometimes used to fake default arguments in - older C libraries. For instance, the low level open() system - call is often declared as a varargs function so that it will accept two - or three arguments:
+12.1.5 Defining different exception + handlers
+By default, the %exception directive creates an exception + handler that is used for all wrapper functions that follow it. Unless + there is a well-defined (and simple) error handling mechanism in place, + defining one universal exception handler may be unwieldy and result in + excessive code bloat since the handler is inlined into each wrapper + function.
+To fix this, you can be more selective about how you use the +%exception directive. One approach is to only place it around + critical pieces of code. For example:
--int open(const char *path, int oflag, ...); -... +%exception { + ... your exception handler ... +} +/* Define critical operations that can throw exceptions here */ -/* Examples */ -f = open("foo", O_RDONLY); -g = open("bar", O_WRONLY | O_CREAT, 0644); +%exception; + +/* Define non-critical operations that don't throw exceptions */Finally, to implement a varargs function, recall that you have to - use the C library functions defined in <stdarg.h>. For +
More precise control over exception handling can be obtained by + attaching an exception handler to specific declaration name. For example:
--List make_list(const char *s, ...) { - va_list ap; - List x; - ... - va_start(ap, s); - while (s) { - x.append(s); - s = va_arg(ap, const char *); +%exception allocate { + try { + $action + } + catch (MemoryError) { + croak("Out of memory"); } - va_end(ap); - return x; }13.2 The Problem
-Generating wrappers for a variable length argument function presents - a number of special challenges. Although C provides support for - implementing functions that receive variable length arguments, there - are no functions that can go in the other direction. Specifically, you - can't write a function that dynamically creates a list of arguments and - which invokes a varargs function on your behalf.
-Although it is possible to write functions that accept the special - type va_list, this is something entirely different. You can't - take a va_list structure and pass it in place of the variable - length arguments to another varargs function. It just doesn't work.
-The reason this doesn't work has to do with the way that function - calls get compiled. For example, suppose that your program has a - function call like this:
+In this case, the exception handler is only attached to declarations + named "allocate". This would include both global and member functions. + The names supplied to %exception follow the same rules as for +%rename described in the section on +Ambiguity resolution and renaming. For example, if you wanted to + define an exception handler for a specific class, you might write this:
--printf("Hello %s. Your number is %d\n", name, num); +%exception Object::allocate { + try { + $action + } + catch (MemoryError) { + croak("Out of memory"); + } +}When the compiler looks at this, it knows that you are calling -printf() with exactly three arguments. Furthermore, it knows that - the number of arguments as well are their types and sizes is never - going to change during program execution. Therefore, this gets turned - to machine code that sets up a three-argument stack frame followed by a - call to printf().
-In contrast, suppose you attempted to make some kind of wrapper - around printf() using code like this:
+When a class prefix is supplied, the exception handler is applied to + the corresponding declaration in the specified class as well as for + identically named functions appearing in derived classes.
+%exception can even be used to pinpoint a precise + declaration when overloading is used. For example:
--int wrap_printf(const char *fmt, ...) { - va_list ap; - va_start(ap,fmt); - ... - printf(fmt,ap); - ... - va_end(ap); -}; +%exception Object::allocate(int) { + try { + $action + } + catch (MemoryError) { + croak("Out of memory"); + } +}Although this code might compile, it won't do what you expect. This - is because the call to printf() is compiled as a procedure - call involving only two arguments. However, clearly a two-argument - configuration of the call stack is completely wrong if your intent is - to pass an arbitrary number of arguments to the real printf(). - Needless to say, it won't work.
-Unfortunately, the situation just described is exactly the problem - faced by wrapper generation tools. In general, the number of passed - arguments will not be known until run-time. To make matters even worse, - you won't know the types and sizes of arguments until run-time as well. - Needless to say, there is no obvious way to make the C compiler - generate code for a function call involving an unknown number of - arguments of unknown types.
-In theory, it is possible to write a wrapper that does the - right thing. However, this involves knowing the underlying ABI for the - target platform and language as well as writing special purpose code - that manually constructed the call stack before making a procedure - call. Unfortunately, both of these tasks require the use of inline - assembly code. Clearly, that's the kind of solution you would much - rather avoid.
-With this nastiness in mind, SWIG provides a number of solutions to - the varargs wrapping problem. Most of these solutions are compromises - that provide limited varargs support without having to resort to - assembly language. However, SWIG can also support real varargs wrapping - (with stack-frame manipulation) if you are willing to get hands dirty. - Keep reading.
-13.3 Default varargs support
-When variable length arguments appear in an interface, the default - behavior is to drop the variable argument list entirely, replacing them - with a single NULL pointer. For example, if you had this function,
+Attaching exceptions to specific declarations is a good way to + reduce code bloat. It can also be a useful way to attach exceptions to + specific parts of a header file. For example:
--void traceprintf(const char *fmt, ...); +%module example +%{ +#include "someheader.h" +%} + +// Define a few exception handlers for specific declarations +%exception Object::allocate(int) { + try { + $action + } + catch (MemoryError) { + croak("Out of memory"); + } +} + +%exception Object::getitem { + try { + $action + } + catch (RangeError) { + croak("Index out of range"); + } +} +... +// Read a raw header file +%include "someheader.h"it would be wrapped as if it had been declared as follows:
+Compatibility note: The %exception directive + replaces the functionality provided by the deprecated "except" typemap. + The typemap would allow exceptions to be thrown in the target language + based on the return type of a function and was intended to be a + mechanism for pinpointing specific declarations. However, it never + really worked that well and the new %exception directive is much + better.
+12.1.6 Special + variables for %exception
+The %exception directive supports a few special variables which are + placeholders for code substitution. The following table shows the + available special variables and details what the special variables are + replaced with.
++
++ $action The actual operation to be performed (a function + call, method invocation, variable access, etc.) + $name The C/C++ symbol name for the function. + $symname The symbol name used internally by SWIG + $overname The extra mangling used in the symbol name for + overloaded method. Expands to nothing if the wrapped method is not + overloaded. + $wrapname The language specific wrapper name (usually a + C function name exported from the shared object/dll) + $decl The fully qualified C/C++ declaration of the + method being wrapped without the return type + $fulldecl The fully qualified C/C++ declaration of the + method being wrapped including the return type + $parentclassname The parent class name (if any) for a + method. + $parentclasssymname The target language parent class + name (if any) for a method. The special variables are often used in situations where method + calls are logged. Exactly which form of the method call needs logging + is up to individual requirements, but the example code below shows all + the possible expansions, plus how an exception message could be + tailored to show the C++ method declaration:
--void traceprintf(const char *fmt); +%exception Special::something { + log("symname: $symname"); + log("overname: $overname"); + log("wrapname: $wrapname"); + log("decl: $decl"); + log("fulldecl: $fulldecl"); + try { + $action + } + catch (MemoryError) { + croak("Out of memory in $decl"); + } +} +void log(const char *message); +struct Special { + void something(const char *c); + void something(int i); +};When the function is called inside the wrappers, it is called as - follows:
+Below shows the expansions for the 1st of the overloaded +something wrapper methods for Perl:
--traceprintf(arg1, NULL); + log("symname: Special_something"); + log("overname: __SWIG_0"); + log("wrapname: _wrap_Special_something__SWIG_0"); + log("decl: Special::something(char const *)"); + log("fulldecl: void Special::something(char const *)"); + try { + (arg1)->something((char const *)arg2); + } + catch (MemoryError) { + croak("Out of memory in Special::something(char const *)"); + }Arguably, this approach seems to defeat the whole point of variable - length arguments. However, this actually provides enough support for - many simple kinds of varargs functions to still be useful, however it - does come with a caveat. For instance, you could make function calls - like this (in Python):
-+12.1.7 Using The SWIG exception library +
+The exception.i library file provides support for creating + language independent exceptions in your interfaces. To use it, simply + put an "%include exception.i" in your interface file. This + provides a function SWIG_exception() that can be used to raise + common scripting language exceptions in a portable manner. For example + :
+-->>> traceprintf("Hello World") ->>> traceprintf("Hello %s. Your number is %d\n" % (name, num)) ->>> traceprintf("Your result is 90%%.") +// Language independent exception handler +%include exception.i + +%exception { + try { + $action + } catch(RangeError) { + SWIG_exception(SWIG_ValueError, "Range Error"); + } catch(DivisionByZero) { + SWIG_exception(SWIG_DivisionByZero, "Division by zero"); + } catch(OutOfMemory) { + SWIG_exception(SWIG_MemoryError, "Out of memory"); + } catch(...) { + SWIG_exception(SWIG_RuntimeError,"Unknown exception"); + } +} +Notice how string formatting is being done in Python instead of C. - The caveat is the strings passed must be safe to use in C though. For - example if name was to contain a "%" it should be double escaped in - order to avoid unpredictable behaviour:
-+As arguments, SWIG_exception() takes an error type code (an + integer) and an error message string. The currently supported error + types are :
+-->>> traceprintf("Your result is 90%.\n") # unpredictable behaviour ->>> traceprintf("Your result is 90%%.\n") # good +SWIG_UnknownError +SWIG_IOError +SWIG_RuntimeError +SWIG_IndexError +SWIG_TypeError +SWIG_DivisionByZero +SWIG_OverflowError +SWIG_SyntaxError +SWIG_ValueError +SWIG_SystemError +SWIG_AttributeError +SWIG_MemoryError +SWIG_NullReferenceErrorRead on for further solutions.
-13.4 Argument replacement using %varargs
-Instead of dropping the variable length arguments, an alternative - approach is to replace (...) with a set of suitable arguments. - SWIG provides a special %varargs directive that can be used to - do this. For example,
+The SWIG_exception() function can also be used in typemaps.
+12.2 Object ownership and + %newobject
+A common problem in some applications is managing proper ownership + of objects. For example, consider a function like this:
--%varargs(int mode = 0) open; -... -int open(const char *path, int oflags, ...); +Foo *blah() { + Foo *f = new Foo(); + return f; +}is equivalent to this:
+If you wrap the function blah(), SWIG has no idea that the + return value is a newly allocated object. As a result, the resulting + extension module may produce a memory leak (SWIG is conservative and + will never delete objects unless it knows for certain that the returned + object was newly created).
+To fix this, you can provide an extra hint to the code generator + using the %newobject directive. For example:
--int open(const char *path, int oflags, int mode = 0); +%newobject blah; +Foo *blah();In this case, %varargs is simply providing more specific - information about the extra arguments that might be passed to a - function. If the arguments to a varargs function are of uniform type, -%varargs can also accept a numerical argument count as follows:
+%newobject works exactly like %rename and +%exception. In other words, you can attach it to class members and + parameterized declarations as before. For example:
--%varargs(3, char *str = NULL) execlp; +%newobject ::blah(); // Only applies to global blah +%newobject Object::blah(int,double); // Only blah(int,double) in Object +%newobject *::copy; // Copy method in all classes ... -int execlp(const char *path, const char *arg, ...);and is effectively seen as:
+When %newobject is supplied, many language modules will + arrange to take ownership of the return value. This allows the value to + be automatically garbage-collected when it is no longer in use. + However, this depends entirely on the target language (a language + module may also choose to ignore the %newobject directive).
+Closely related to %newobject is a special typemap. The + "newfree" typemap can be used to deallocate a newly allocated return + value. It is only available on methods for which %newobject + has been applied and is commonly used to clean-up string results. For + example:
--int execlp(const char *path, const char *arg, - char *str1 = NULL, - char *str2 = NULL, - char *str3 = NULL); +%typemap(newfree) char * "free($1);"; +... +%newobject strdup; +... +char *strdup(const char *s);This would wrap execlp() as a function that accepted up to - 3 optional arguments. Depending on the application, this may be more - than enough for practical purposes.
-The handling of default arguments - can be changed via the compactdefaultargs feature. If this - feature is used, for example
+In this case, the result of the function is a string in the target + language. Since this string is a copy of the original result, the data + returned by strdup() is no longer needed. The "newfree" + typemap in the example simply releases this memory.
+As a complement to the %newobject, from SWIG 1.3.28, you + can use the %delobject directive. For example, if you have two + methods, one to create objects and one to destroy them, you can use:
--%feature("compactdefaultargs") execlp; -%varargs(3, char *str = NULL) execlp; +%newobject create_foo; +%delobject destroy_foo; ... -int execlp(const char *path, const char *arg, ...); +Foo *create_foo(); +void destroy_foo(Foo *foo);a call from the target language which does not provide the maximum - number of arguments, such as, execlp("a", "b", "c") will - generate C code which includes the missing default values, that is, -execlp("a", "b", "c", NULL, NULL). If compactdefaultargs - is not used, then the generated code will be execlp("a", "b", "c") -. The former is useful for helping providing a sentinel to terminate the - argument list. However, this is not guaranteed, for example when a user - passes a non-NULL value for all the parameters. When using -compactdefaultargs it is possible to guarantee the NULL sentinel is - passed through the, numinputs=0 'in' - typemap attribute, naming the last parameter. For example,
+or in a member method as:
--%feature("compactdefaultargs") execlp; -%varargs(3, char *str = NULL) execlp; -%typemap(in, numinputs=0) char *str3 "" -... -int execlp(const char *path, const char *arg, ...); +%delobject Foo::destroy; + +class Foo { +public: + void destroy() { delete this;} + +private: + ~Foo(); +};Note that str3 is the name of the last argument, as we have - used %varargs with 3. Now execlp("a", "b", "c", "d", "e") - will result in an error as one too many arguments has been passed, as - now only 2 additional 'str' arguments can be passed with the 3rd one - always using the specified default NULL.
-Argument replacement is most appropriate in cases where the types of - the extra arguments are uniform and the maximum number of arguments are - known. Argument replacement is not as useful when working with - functions that accept mixed argument types such as printf(). - Providing general purpose wrappers to such functions presents special - problems (covered shortly).
-13.5 Varargs and typemaps
-Variable length arguments may be used in typemap specifications. For - example:
+%delobject instructs SWIG that the first argument passed to + the method will be destroyed, and therefore, the target language should + not attempt to deallocate it twice. This is similar to use the DISOWN + typemap in the first method argument, and in fact, it also depends on + the target language on implementing the 'disown' mechanism properly.
+The use of %newobject is also integrated with reference + counting and is covered in the C++ + reference counted objects section.
+Compatibility note: Previous versions of SWIG had a special +%new directive. However, unlike %newobject, it only + applied to the next declaration. For example:
+-%typemap(in) (...) { - // Get variable length arguments (somehow) - ... +%new char *strdup(const char *s); ++For now this is still supported but is deprecated.
+How to shoot yourself in the foot: The %newobject + directive is not a declaration modifier like the old %new + directive. Don't write code like this:
++++%newobject +char *strdup(const char *s); ++The results might not be what you expect.
+12.3 Features and the %feature + directive
+Both %exception and %newobject are examples of a + more general purpose customization mechanism known as "features." A + feature is simply a user-definable property that is attached to + specific declarations. Features are attached using the %feature + directive. For example:
++-+%feature("except") Object::allocate { + try { + $action + } + catch (MemoryError) { + croak("Out of memory"); + } } -%typemap(in) (const char *fmt, ...) { - // Multi-argument typemap -} +%feature("new","1") *::copy;However, this immediately raises the question of what "type" is - actually used to represent (...). For lack of a better - alternative, the type of (...) is set to void *. - Since there is no way to dynamically pass arguments to a varargs - function (as previously described), the void * argument value - is intended to serve as a place holder for storing some kind of - information about the extra arguments (if any). In addition, the - default behavior of SWIG is to pass the void * value as an - argument to the function. Therefore, you could use the pointer to hold - a valid argument value if you wanted.
-To illustrate, here is a safer version of wrapping printf() - in Python:
+In fact, the %exception and %newobject directives + are really nothing more than macros involving %feature:
--%typemap(in) (const char *fmt, ...) { - $1 = "%s"; /* Fix format string to %s */ - $2 = (void *) PyString_AsString($input); /* Get string argument */ -}; -... -int printf(const char *fmt, ...); +#define %exception %feature("except") +#define %newobject %feature("new","1")In this example, the format string is implicitly set to "%s" -. This prevents a program from passing a bogus format string to the - extension. Then, the passed input object is decoded and placed in the -void * argument defined for the (...) argument. When the - actual function call is made, the underlying wrapper code will look - roughly like this:
+The name matching rules outlined in the +Ambiguity resolution and renaming section applies to all +%feature directives. In fact the %rename directive is just + a special form of %feature. The matching rules mean that + features are very flexible and can be applied with pinpoint accuracy to + specific declarations if needed. Additionally, if no declaration name + is given, a global feature is said to be defined. This feature is then + attached to every declaration that follows. This is how global + exception handlers are defined. For example:
--wrap_printf() { - char *arg1; - void *arg2; - int result; - - arg1 = "%s"; - arg2 = (void *) PyString_AsString(arg2obj); - ... - result = printf(arg1,arg2); +/* Define a global exception handler */ +%feature("except") { + try { + $action + } ... } + +... bunch of declarations ...Notice how both arguments are passed to the function and it does - what you would expect.
-The next example illustrates a more advanced kind of varargs - typemap. Disclaimer: this requires special support in the target - language module and is not guaranteed to work with all SWIG modules at - this time. It also starts to illustrate some of the more fundamental - problems with supporting varargs in more generality.
-If a typemap is defined for any form of (...), many SWIG - modules will generate wrappers that accept a variable number of - arguments as input and will make these arguments available in some - form. The precise details of this depends on the language module being - used (consult the appropriate chapter for more details). However, - suppose that you wanted to create a Python wrapper for the execlp() - function shown earlier. To do this using a typemap instead of using -%varargs, you might first write a typemap like this:
+The %feature directive can be used with different syntax. + The following are all equivalent:
--%typemap(in) (...)(char *vargs[10]) { - int i; - int argc; - for (i = 0; i < 10; i++) vargs[i] = 0; - argc = PyTuple_Size(varargs); - if (argc > 10) { - PyErr_SetString(PyExc_ValueError, "Too many arguments"); - return NULL; - } - for (i = 0; i < argc; i++) { - PyObject *pyobj = PyTuple_GetItem(varargs, i); - char *str = 0; -%#if PY_VERSION_HEX>=0x03000000 - PyObject *pystr; - if (!PyUnicode_Check(pyobj)) { - PyErr_SetString(PyExc_ValueError, "Expected a string"); - return NULL; - } - pystr = PyUnicode_AsUTF8String(pyobj); - str = strdup(PyBytes_AsString(pystr)); - Py_XDECREF(pystr); -%#else - if (!PyString_Check(pyobj)) { - PyErr_SetString(PyExc_ValueError, "Expected a string"); - return NULL; - } - str = PyString_AsString(pyobj); -%#endif - vargs[i] = str; - } - $1 = (void *)vargs; -} - -%typemap(freearg) (...) { -%#if PY_VERSION_HEX>=0x03000000 - int i; - for (i = 0; i < 10; i++) { - free(vargs$argnum[i]); - } -%#endif -} +%feature("except") Object::method { $action }; +%feature("except") Object::method %{ $action %}; +%feature("except") Object::method " $action "; +%feature("except","$action") Object::method;In the 'in' typemap, the special variable varargs is a - tuple holding all of the extra arguments passed (this is specific to - the Python module). The typemap then pulls this apart and sticks the - values into the array of strings args. Then, the array is - assigned to $1 (recall that this is the void * - variable corresponding to (...)). However, this assignment is - only half of the picture----clearly this alone is not enough to make - the function work. The 'freearg' typemap cleans up memory allocated in - the 'in' typemap; this code is generated to be called after the -execlp function is called. To patch everything up, you have to - rewrite the underlying action code using the %feature - directive like this:
+The syntax in the first variation will generate the { } + delimiters used whereas the other variations will not.
+12.3.1 Feature attributes +
+The %feature directive also accepts XML style attributes in + the same way that typemaps do. Any number of attributes can be + specified. The following is the generic syntax for features:
--%feature("action") execlp { - char **vargs = (char **) arg3; - result = execlp(arg1, arg2, vargs[0], vargs[1], vargs[2], vargs[3], vargs[4], - vargs[5], vargs[6], vargs[7], vargs[8], vargs[9], NULL); -} - -int execlp(const char *path, const char *arg, ...); +%feature("name","value", attribute1="AttributeValue1") symbol; +%feature("name", attribute1="AttributeValue1") symbol {value}; +%feature("name", attribute1="AttributeValue1") symbol %{value%}; +%feature("name", attribute1="AttributeValue1") symbol "value";This patches everything up and creates a function that more or less - works. However, don't try explaining this to your coworkers unless you - know for certain that they've had several cups of coffee. If you really - want to elevate your guru status and increase your job security, - continue to the next section.
-13.6 Varargs wrapping with libffi
-All of the previous examples have relied on features of SWIG that - are portable and which don't rely upon any low-level machine-level - details. In many ways, they have all dodged the real issue of variable - length arguments by recasting a varargs function into some weaker - variation with a fixed number of arguments of known types. In many - cases, this works perfectly fine. However, if you want more generality - than this, you need to bring out some bigger guns.
-One way to do this is to use a special purpose library such as - libffi ( -http://sources.redhat.com/libffi). libffi is a library that allows - you to dynamically construct call-stacks and invoke procedures in a - relatively platform independent manner. Details about the library can - be found in the libffi distribution and are not repeated here.
-To illustrate the use of libffi, suppose that you really - wanted to create a wrapper for execlp() that accepted any - number of arguments. To do this, you might make a few adjustments to - the previous example. For example:
+More than one attribute can be specified using a comma separated + list. The Java module is an example that uses attributes in +%feature("except"). The throws attribute specifies the + name of a Java class to add to a proxy method's throws clause. In the + following example, MyExceptionClass is the name of the Java + class for adding to the throws clause.
--/* Take an arbitrary number of extra arguments and place into an array - of strings */ - -%typemap(in) (...) { - char **argv; - int argc; - int i; - - argc = PyTuple_Size(varargs); - argv = (char **) malloc(sizeof(char *)*(argc+1)); - for (i = 0; i < argc; i++) { - PyObject *o = PyTuple_GetItem(varargs,i); - if (!PyString_Check(o)) { - PyErr_SetString(PyExc_ValueError,"Expected a string"); - free(argv); - return NULL; - } - argv[i] = PyString_AsString(o); +%feature("except", throws="MyExceptionClass") Object::method { + try { + $action + } catch (...) { + ... code to throw a MyExceptionClass Java exception ... } - argv[i] = NULL; - $1 = (void *) argv; -} - -/* Rewrite the function call, using libffi */ - -%feature("action") execlp { - int i, vc; - ffi_cif cif; - ffi_type **types; - void **values; - char **args; - - vc = PyTuple_Size(varargs); - types = (ffi_type **) malloc((vc+3)*sizeof(ffi_type *)); - values = (void **) malloc((vc+3)*sizeof(void *)); - args = (char **) arg3; - - /* Set up path parameter */ - types[0] = &ffi_type_pointer; - values[0] = &arg1; - - /* Set up first argument */ - types[1] = &ffi_type_pointer; - values[1] = &arg2; - - /* Set up rest of parameters */ - for (i = 0; i <= vc; i++) { - types[2+i] = &ffi_type_pointer; - values[2+i] = &args[i]; - } - if (ffi_prep_cif(&cif, FFI_DEFAULT_ABI, vc+3, - &ffi_type_uint, types) == FFI_OK) { - ffi_call(&cif, (void (*)()) execlp, &result, values); - } else { - PyErr_SetString(PyExc_RuntimeError, "Whoa!!!!!"); - free(types); - free(values); - free(arg3); - return NULL; - } - free(types); - free(values); - free(arg3); -} - -/* Declare the function. Whew! */ -int execlp(const char *path, const char *arg1, ...); +};Looking at this example, you may start to wonder if SWIG is making - life any easier. Given the amount of code involved, you might also - wonder why you didn't just write a hand-crafted wrapper! Either that or - you're wondering "why in the hell am I trying to wrap this varargs - function in the first place?!?" Obviously, those are questions you'll - have to answer for yourself.
-As a more extreme example of libffi, here is some code that attempts - to wrap printf(),
+Further details can be obtained from the +Java exception handling section.
+12.3.2 Feature flags
+Feature flags are used to enable or disable a particular feature. + Feature flags are a common but simple usage of %feature and + the feature value should be either 1 to enable or 0 + to disable the feature.
+-/* A wrapper for printf() using libffi */ - -%{ -/* Structure for holding passed arguments after conversion */ - typedef struct { - int type; - union { - int ivalue; - double dvalue; - void *pvalue; - } val; - } vtype; - enum { VT_INT, VT_DOUBLE, VT_POINTER }; -%} - -%typemap(in) (const char *fmt, ...) { - vtype *argv; - int argc; - int i; - - /* Format string */ - $1 = PyString_AsString($input); - - /* Variable length arguments */ - argc = PyTuple_Size(varargs); - argv = (vtype *) malloc(argc*sizeof(vtype)); - for (i = 0; i < argc; i++) { - PyObject *o = PyTuple_GetItem(varargs,i); - if (PyInt_Check(o)) { - argv[i].type = VT_INT; - argv[i].val.ivalue = PyInt_AsLong(o); - } else if (PyFloat_Check(o)) { - argv[i].type = VT_DOUBLE; - argv[i].val.dvalue = PyFloat_AsDouble(o); - } else if (PyString_Check(o)) { - argv[i].type = VT_POINTER; - argv[i].val.pvalue = (void *) PyString_AsString(o); - } else { - PyErr_SetString(PyExc_ValueError,"Unsupported argument type"); - free(argv); - return NULL; - } - } - $2 = (void *) argv; -} - -/* Rewrite the function call using libffi */ -%feature("action") printf { - int i, vc; - ffi_cif cif; - ffi_type **types; - void **values; - vtype *args; +%feature("featurename") // enables feature +%feature("featurename", "1") // enables feature +%feature("featurename", "x") // enables feature +%feature("featurename", "0") // disables feature +%feature("featurename", "") // clears feature ++Actually any value other than zero will enable the feature. Note + that if the value is omitted completely, the default value becomes +1, thereby enabling the feature. A feature is cleared by specifying + no value, see Clearing + features. The %immutable directive described in the +Creating read-only variables section, is just a macro for +%feature("immutable"), and can be used to demonstrates feature + flags:
++-+ // features are disabled by default +int red; // mutable - vc = PyTuple_Size(varargs); - types = (ffi_type **) malloc((vc+1)*sizeof(ffi_type *)); - values = (void **) malloc((vc+1)*sizeof(void *)); - args = (vtype *) arg2; +%feature("immutable"); // global enable +int orange; // immutable - /* Set up fmt parameter */ - types[0] = &ffi_type_pointer; - values[0] = &arg1; +%feature("immutable","0"); // global disable +int yellow; // mutable - /* Set up rest of parameters */ - for (i = 0; i < vc; i++) { - switch(args[i].type) { - case VT_INT: - types[1+i] = &ffi_type_uint; - values[1+i] = &args[i].val.ivalue; - break; - case VT_DOUBLE: - types[1+i] = &ffi_type_double; - values[1+i] = &args[i].val.dvalue; - break; - case VT_POINTER: - types[1+i] = &ffi_type_pointer; - values[1+i] = &args[i].val.pvalue; - break; - default: - abort(); /* Whoa! We're seriously hosed */ - break; - } - } - if (ffi_prep_cif(&cif, FFI_DEFAULT_ABI, vc+1, - &ffi_type_uint, types) == FFI_OK) { - ffi_call(&cif, (void (*)()) printf, &result, values); - } else { - PyErr_SetString(PyExc_RuntimeError, "Whoa!!!!!"); - free(types); - free(values); - free(args); - return NULL; - } - free(types); - free(values); - free(args); -} +%feature("immutable","1"); // another form of global enable +int green; // immutable -/* The function */ -int printf(const char *fmt, ...); +%feature("immutable",""); // clears the global feature +int blue; // mutableMuch to your amazement, it even seems to work if you try it:
-+-Note that features are disabled by default and must be explicitly + enabled either globally or by specifying a targeted declaration. The + above intersperses SWIG directives with C code. Of course you can + target features explicitly, so the above could also be rewritten as:
+-->>> import example ->>> example.printf("Grade: %s %d/60 = %0.2f%%\n", "Dave", 47, 47.0*100/60) -Grade: Dave 47/60 = 78.33% ->>> +%feature("immutable","1") orange; +%feature("immutable","1") green; +int red; // mutable +int orange; // immutable +int yellow; // mutable +int green; // immutable +int blue; // mutableOf course, there are still some limitations to consider:
-+-The above approach allows for the C declarations to be separated + from the SWIG directives for when the C declarations are parsed from a + C header file. The logic above can of course be inverted and rewritten + as:
+-->>> example.printf("la de da de da %s", 42) -Segmentation fault (core dumped) +%feature("immutable","1"); +%feature("immutable","0") red; +%feature("immutable","0") yellow; +%feature("immutable","0") blue; +int red; // mutable +int orange; // immutable +int yellow; // mutable +int green; // immutable +int blue; // mutableAnd, on this note, we leave further exploration of libffi to the - reader as an exercise. Although Python has been used as an example, - most of the techniques in this section can be extrapolated to other - language modules with a bit of work. The only details you need to know - is how the extra arguments are accessed in each target language. For - example, in the Python module, we used the special varargs - variable to get these arguments. Modules such as Tcl8 and Perl5 simply - provide an argument number for the first extra argument. This can be - used to index into an array of passed arguments to get values. Please - consult the chapter on each language module for more details.
-13.7 Wrapping of va_list
-Closely related to variable length argument wrapping, you may - encounter functions that accept a parameter of type va_list. - For example:
+As hinted above for %immutable, most feature flags can also + be specified via alternative syntax. The alternative syntax is just a + macro in the swig.swg Library file. The following shows the + alternative syntax for the imaginary featurename feature:
--int vprintf(const char *fmt, va_list ap); +%featurename // equivalent to %feature("featurename", "1") ie enables feature +%nofeaturename // equivalent to %feature("featurename", "0") ie disables feature +%clearfeaturename // equivalent to %feature("featurename", "") ie clears featureAs far as we know, there is no obvious way to wrap these functions - with SWIG. This is because there is no documented way to assemble the - proper va_list structure (there are no C library functions to do it and - the contents of va_list are opaque). Not only that, the contents of a -va_list structure are closely tied to the underlying call-stack. - It's not clear that exporting a va_list would have any use or - that it would work at all.
-A workaround can be implemented by writing a simple varargs C - wrapper and then using the techniques discussed earlier in this chapter - for varargs. Below is a simple wrapper for vprintf renamed so - that it can still be called as vprintf from your target - language. The %varargs used in the example restricts the - function to taking one string argument.
+The concept of clearing features is discussed next.
+12.3.3 Clearing features +
+A feature stays in effect until it is explicitly cleared. A feature + is cleared by supplying a %feature directive with no value. + For example %feature("name",""). A cleared feature means that + any feature exactly matching any previously defined feature is no + longer used in the name matching rules. So if a feature is cleared, it + might mean that another name matching rule will apply. To clarify, + let's consider the except feature again (%exception):
--%{ -int vprintf(const char *fmt, va_list ap); -%} +// Define global exception handler +%feature("except") { + try { + $action + } catch (...) { + croak("Unknown C++ exception"); + } +} -%varargs(const char *) my_vprintf; -%rename(vprintf) my_vprintf; +// Define exception handler for all clone methods to log the method calls +%feature("except") *::clone() { + try { + logger.info("$action"); + $action + } catch (...) { + croak("Unknown C++ exception"); + } +} -%inline %{ -int my_vprintf(const char *fmt, ...) { - va_list ap; - int result; +... initial set of class declarations with clone methods ... - va_start(ap, fmt); - result = vprintf(fmt, ap); - va_end(ap); - return result; -} -%} +// clear the previously defined feature +%feature("except","") *::clone(); + +... final set of class declarations with clone methods ...13.8 C++ Issues
-Wrapping of C++ member functions that accept a variable number of - arguments presents a number of challenges. By far, the easiest way to - handle this is to use the %varargs directive. This is portable - and it fully supports classes much like the %rename directive. - For example:
+In the above scenario, the initial set of clone methods will log all + method invocations from the target language. This specific feature is + cleared for the final set of clone methods. However, these clone + methods will still have an exception handler (without logging) as the + next best feature match for them is the global exception handler.
+Note that clearing a feature is not always the same as disabling it. + Clearing the feature above with %feature("except","") *::clone() + is not the same as specifying %feature("except","0") *::clone() +. The former will disable the feature for clone methods - the feature is + still a better match than the global feature. If on the other hand, no + global exception handler had been defined at all, then clearing the + feature would be the same as disabling it as no other feature would + have matched.
+Note that the feature must match exactly for it to be cleared by any + previously defined feature. For example the following attempt to clear + the initial feature will not work:
--%varargs (10, char * = NULL) Foo::bar; - -class Foo { -public: - virtual void bar(char *arg, ...); // gets varargs above -}; - -class Spam: public Foo { -public: - virtual void bar(char *arg, ...); // gets varargs above -}; +%feature("except") clone() { logger.info("$action"); $action } +%feature("except","") *::clone();%varargs also works with constructors, operators, and any - other C++ programming construct that accepts variable arguments.
-Doing anything more advanced than this is likely to involve a - serious world of pain. In order to use a library like libffi, you will - need to know the underlying calling conventions and details of the C++ - ABI. For instance, the details of how this is passed to member - functions as well as any hidden arguments that might be used to pass - additional information. These details are implementation specific and - may differ between compilers and even different versions of the same - compiler. Also, be aware that invoking a member function is further - complicated if it is a virtual method. In this case, invocation might - require a table lookup to obtain the proper function address (although - you might be able to obtain an address by casting a bound pointer to a - pointer to function as described in the C++ ARM section 18.3.4).
-If you do decide to change the underlying action code, be aware that - SWIG always places the this pointer in arg1. Other - arguments are placed in arg2, arg3, and so forth. For - example:
+but this will:
--%feature("action") Foo::bar { - ... - result = arg1->bar(arg2, arg3, etc.); - ... -} +%feature("except") clone() { logger.info("$action"); $action } +%feature("except","") clone();Given the potential to shoot yourself in the foot, it is probably - easier to reconsider your design or to provide an alternative interface - using a helper function than it is to create a fully general wrapper to - a varargs C++ member function.
-13.9 Discussion
-This chapter has provided a number of techniques that can be used to - address the problem of variable length argument wrapping. If you care - about portability and ease of use, the %varargs directive is - probably the easiest way to tackle the problem. However, using - typemaps, it is possible to do some very advanced kinds of wrapping.
-One point of discussion concerns the structure of the libffi - examples in the previous section. Looking at that code, it is not at - all clear that this is the easiest way to solve the problem. However, - there are a number of subtle aspects of the solution to - consider--mostly concerning the way in which the problem has been - decomposed. First, the example is structured in a way that tries to - maintain separation between wrapper-specific information and the - declaration of the function itself. The idea here is that you might - structure your interface like this:
+SWIG provides macros for disabling and clearing features. Many of + these can be found in the swig.swg library file. The typical + pattern is to define three macros; one to define the feature itself, + one to disable the feature and one to clear the feature. The three + macros below show this for the "except" feature:
--%typemap(const char *fmt, ...) { - ... -} -%feature("action") traceprintf { - ... -} - -/* Include some header file with traceprintf in it */ -%include "someheader.h" +#define %exception %feature("except") +#define %noexception %feature("except","0") +#define %clearexception %feature("except","")Second, careful scrutiny will reveal that the typemaps involving -(...) have nothing whatsoever to do with the libffi library. In - fact, they are generic with respect to the way in which the function is - actually called. This decoupling means that it will be much easier to - consider other library alternatives for making the function call. For - instance, if libffi wasn't supported on a certain platform, you might - be able to use something else instead. You could use conditional - compilation to control this:
+12.3.4 Features and + default arguments
+SWIG treats methods with default arguments as separate overloaded + methods as detailed in the default + arguments section. Any %feature targeting a method with + default arguments will apply to all the extra overloaded methods that + SWIG generates if the default arguments are specified in the feature. + If the default arguments are not specified in the feature, then the + feature will match that exact wrapper method only and not the extra + overloaded methods that SWIG generates. For example:
+-#ifdef USE_LIBFFI -%feature("action") printf { - ... -} -#endif -#ifdef USE_OTHERFFI -%feature("action") printf { -... +%feature("except") hello(int i=0, double d=0.0) { ... } +void hello(int i=0, double d=0.0); ++will apply the feature to all three wrapper methods, that is:
++++void hello(int i, double d); +void hello(int i); +void hello(); ++If the default arguments are not specified in the feature:
++++%feature("except") hello(int i, double d) { ... } +void hello(int i=0, double d=0.0); ++then the feature will only apply to this wrapper method:
++++void hello(int i, double d); ++and not these wrapper methods:
++++void hello(int i); +void hello(); ++If compactdefaultargs are being + used, then the difference between specifying or not specifying default + arguments in a feature is not applicable as just one wrapper is + generated.
+Compatibility note: The different behaviour of features + specified with or without default arguments was introduced in + SWIG-1.3.23 when the approach to wrapping methods with default + arguments was changed.
+12.3.5 Feature example
+As has been shown earlier, the intended use for the %feature + directive is as a highly flexible customization mechanism that can be + used to annotate declarations with additional information for use by + specific target language modules. Another example is in the Python + module. You might use %feature to rewrite proxy/shadow class + code as follows:
++-+%module example +%rename(bar_id) bar(int,double); + +// Rewrite bar() to allow some nice overloading + +%feature("shadow") Foo::bar(int) %{ +def bar(*args): + if len(args) == 3: + return apply(examplec.Foo_bar_id,args) + return apply(examplec.Foo_bar,args) +%} + +class Foo { +public: + int bar(int x); + int bar(int x, double y); } -#endifFinally, even though you might be inclined to just write a - hand-written wrapper for varargs functions, the techniques used in the - previous section have the advantage of being compatible with all other - features of SWIG such as exception handling.
-As a final word, some C programmers seem to have the assumption that - the wrapping of variable length argument functions is an easily solved - problem. However, this section has hopefully dispelled some of these - myths. All things being equal, you are better off avoiding variable - length arguments if you can. If you can't avoid them, please consider - some of the simple solutions first. If you can't live with a simple - solution, proceed with caution. At the very least, make sure you - carefully read the section "A7.3.2 Function Calls" in Kernighan and - Ritchie and make sure you fully understand the parameter passing - conventions used for varargs. Also, be aware of the platform - dependencies and reliability issues that this will introduce. Good - luck.
+Further details of %feature usage is described in the + documentation for specific language modules.
-14 Warning Messages
+13 Contracts
--
- Introduction
-- Warning message suppression
-- Enabling extra warnings
-- Issuing a warning message
-- Symbolic symbols
-- Commentary
-- Warnings as errors
-- Message output format
-- Warning number reference - +
- The %contract directive
+- %contract and classes
+- Constant aggregation and %aggregate_check
-- History
+- Notes
14.1 Introduction
-During compilation, SWIG may generate a variety of warning messages. - For example:
-+-A common problem that arises when wrapping C libraries is that of + maintaining reliability and checking for errors. The fact of the matter + is that many C programs are notorious for not providing error checks. + Not only that, when you expose the internals of an application as a + library, it often becomes possible to crash it simply by providing bad + inputs or using it in a way that wasn't intended.
+This chapter describes SWIG's support for software contracts. In the + context of SWIG, a contract can be viewed as a runtime constraint that + is attached to a declaration. For example, you can easily attach + argument checking rules, check the output values of a function and + more. When one of the rules is violated by a script, a runtime + exception is generated rather than having the program continue to + execute.
+13.1 The %contract directive
+Contracts are added to a declaration using the %contract directive. + Here is a simple example:
+--example.i:16: Warning 501: Overloaded declaration ignored. bar(double) -example.i:15: Warning 501: Previous declaration is bar(int) +%contract sqrt(double x) { +require: + x >= 0; +ensure: + sqrt >= 0; +} + +... +double sqrt(double);Typically, warning messages indicate non-fatal problems with the - input where the generated wrapper code will probably compile, but it - may not work like you expect.
-14.2 Warning message suppression
-All warning messages have a numeric code that is shown in the - warning message itself. To suppress the printing of a warning message, - a number of techniques can be used. First, you can run SWIG with the --w command line option. For example:
+In this case, a contract is being added to the sqrt() + function. The %contract directive must always appear before + the declaration in question. Within the contract there are two + sections, both of which are optional. The require: section + specifies conditions that must hold before the function is called. + Typically, this is used to check argument values. The ensure: + section specifies conditions that must hold after the function is + called. This is often used to check return values or the state of the + program. In both cases, the conditions that must hold must be specified + as boolean expressions.
+In the above example, we're simply making sure that sqrt() returns a + non-negative number (if it didn't, then it would be broken in some + way).
+Once a contract has been specified, it modifies the behavior of the + resulting module. For example:
--% swig -python -w501 example.i -% swig -python -w501,505,401 example.i +>>> example.sqrt(2) +1.4142135623730951 +>>> example.sqrt(-2) +Traceback (most recent call last): + File "<stdin>", line 1, in ? +RuntimeError: Contract violation: require: (arg1>=0) +>>>Alternatively, warnings can be suppressed by inserting a special - preprocessor pragma into the input file:
+13.2 %contract and classes
+The %contract directive can also be applied to class + methods and constructors. For example:
--%module example -#pragma SWIG nowarn=501 -#pragma SWIG nowarn=501,505,401 +%contract Foo::bar(int x, int y) { +require: + x > 0; +ensure: + bar > 0; +} + +%contract Foo::Foo(int a) { +require: + a > 0; +} + +class Foo { +public: + Foo(int); + int bar(int, int); +};Finally, code-generation warnings can be disabled on a declaration - by declaration basis using the %warnfilter directive. For - example:
+The way in which %contract is applied is exactly the same + as the %feature directive. Thus, any contract that you + specified for a base class will also be attached to inherited methods. + For example:
--%module example -%warnfilter(501) foo; -... -int foo(int); -int foo(double); // Silently ignored. +class Spam : public Foo { +public: + int bar(int,int); // Gets contract defined for Foo::bar(int,int) +};The %warnfilter directive has the same semantics as other - declaration modifiers like %rename, %ignore and -%feature, see the %feature - directive section. For example, if you wanted to suppress a warning - for a method in a class hierarchy, you could do this:
+In addition to this, separate contracts can be applied to both the + base class and a derived class. For example:
--%warnfilter(501) Object::foo; -class Object { +%contract Foo::bar(int x, int) { +require: + x > 0; +} + +%contract Spam::bar(int, int y) { +require: + y > 0; +} + +class Foo { public: - int foo(int); - int foo(double); // Silently ignored - ... + int bar(int,int); // Gets Foo::bar contract. }; -class Derived : public Object { +class Spam : public Foo { public: - int foo(int); - int foo(double); // Silently ignored - ... + int bar(int,int); // Gets Foo::bar and Spam::bar contract };Warnings can be suppressed for an entire class by supplying a class - name. For example:
+When more than one contract is applied, the conditions specified in + a "require:" section are combined together using a logical-AND + operation. In other words conditions specified for the base class and + conditions specified for the derived class all must hold. In the above + example, this means that both the arguments to Spam::bar must + be positive.
+13.3 Constant aggregation and + %aggregate_check
+Consider an interface file that contains the following code:
--%warnfilter(501) Object; +#define UP 1 +#define DOWN 2 +#define RIGHT 3 +#define LEFT 4 -class Object { -public: - ... // All 501 warnings ignored in class -}; +void move(SomeObject *, int direction, int distance);There is no option to suppress all SWIG warning messages. The - warning messages are there for a reason---to tell you that something - may be broken in your interface. Ignore the warning messages - at your own peril.
-14.3 Enabling extra warnings
-Some warning messages are disabled by default and are generated only - to provide additional diagnostics. These warnings can be turned on - using the -Wextra option. For example:
-+-One thing you might want to do is impose a constraint on the + direction parameter to make sure it's one of a few accepted values. To + do that, SWIG provides an easy to use macro %aggregate_check() that + works like this:
+--% swig -Wextra -python example.i +%aggregate_check(int, check_direction, UP, DOWN, LEFT, RIGHT);To selectively turn on extra warning messages, you can use the - directives and options in the previous section--simply add a "+" to all - warning numbers. For example:
-+-This merely defines a utility function of the form
+--% swig -w+309,+452 example.i +int check_direction(int x);or in your interface file use either
+That checks the argument x to see if it is one of the values listed. + This utility function can be used in contracts. For example:
--#pragma SWIG nowarn=+309,+452 +%aggregate_check(int, check_direction, UP, DOWN, RIGHT, LEFT); + +%contract move(SomeObject *, int direction, in) { +require: + check_direction(direction); +} + +#define UP 1 +#define DOWN 2 +#define RIGHT 3 +#define LEFT 4 + +void move(SomeObject *, int direction, int distance);or
+Alternatively, it can be used in typemaps and other directives. For + example:
--%warnfilter(+309,+452) foo; +%aggregate_check(int, check_direction, UP, DOWN, RIGHT, LEFT); + +%typemap(check) int direction { + if (!check_direction($1)) SWIG_exception(SWIG_ValueError, "Bad direction"); +} + +#define UP 1 +#define DOWN 2 +#define RIGHT 3 +#define LEFT 4 + +void move(SomeObject *, int direction, int distance);Note: selective enabling of warnings with %warnfilter - overrides any global settings you might have made using -w or -#pragma.
-You can of course also enable all warnings and suppress a select - few, for example:
----% swig -Wextra -w309,452 example.i -+Regrettably, there is no automatic way to perform similar checks + with enums values. Maybe in a future release.
+13.4 Notes
+Contract support was implemented by Songyan (Tiger) Feng and first + appeared in SWIG-1.3.20.
+
+14 Variable Length Arguments
+ + ++-The warnings on the right take precedence over the warnings on the - left, so in the above example -Wextra adds numerous warnings - including 452, but then -w309,452 overrides this and so 452 is - suppressesed.
-If you would like all warnings to appear, regardless of the warning - filters used, then use the -Wall option. The -Wall - option also turns on the extra warnings that -Wextra adds, - however, it is subtely different. When -Wall is used, it also - disables all other warning filters, that is, any warnings suppressed or - added in %warnfilter, #pragma SWIG nowarn or the --w option.
-14.4 Issuing a warning message
-Warning messages can be issued from an interface file using a number - of directives. The %warn directive is the most simple:
+ +(a.k.a, "The horror. The horror.")
+This chapter describes the problem of wrapping functions that take a + variable number of arguments. For instance, generating wrappers for the + C printf() family of functions.
+This topic is sufficiently advanced to merit its own chapter. In + fact, support for varargs is an often requested feature that was first + added in SWIG-1.3.12. Most other wrapper generation tools have wisely + chosen to avoid this issue.
+14.1 Introduction
+Some C and C++ programs may include functions that accept a variable + number of arguments. For example, most programmers are familiar with + functions from the C library such as the following:
--%warn "900:This is your last warning!" +int printf(const char *fmt, ...) +int fprintf(FILE *, const char *fmt, ...); +int sprintf(char *s, const char *fmt, ...);All warning messages are optionally prefixed by the warning number - to use. If you are generating your own warnings, make sure you don't - use numbers defined in the table at the end of this section.
-The %ignorewarn directive is the same as %ignore - except that it issues a warning message whenever a matching declaration - is found. For example:
+Although there is probably little practical purpose in wrapping + these specific C library functions in a scripting language (what would + be the point?), a library may include its own set of special functions + based on a similar API. For example:
--%ignorewarn("362:operator= ignored") operator=; +int traceprintf(const char *fmt, ...);Warning messages can be associated with typemaps using the -warning attribute of a typemap declaration. For example:
+In this case, you may want to have some kind of access from the + target language.
+Before describing the SWIG implementation, it is important to + discuss the common uses of varargs that you are likely to encounter in + real programs. Obviously, there are the printf() style output + functions as shown. Closely related to this would be scanf() + style input functions that accept a format string and a list of + pointers into which return values are placed. However, variable length + arguments are also sometimes used to write functions that accept a + NULL-terminated list of pointers. A good example of this would be a + function like this:
--%typemap(in, warning="901:You are really going to regret this usage of $1_type $1_name") blah * { - ... -} +int execlp(const char *path, const char *arg1, ...); +... + +/* Example */ +execlp("ls","ls","-l",NULL);In this case, the warning message will be printed whenever the - typemap is actually used and the -special variables will be expanded as appropriate, for example:
-+-In addition, varargs is sometimes used to fake default arguments in + older C libraries. For instance, the low level open() system + call is often declared as a varargs function so that it will accept two + or three arguments:
+--example.i:23: Warning 901: You are really going to regret this usage of blah * self -example.i:24: Warning 901: You are really going to regret this usage of blah * stuff +int open(const char *path, int oflag, ...); +... + +/* Examples */ +f = open("foo", O_RDONLY); +g = open("bar", O_WRONLY | O_CREAT, 0644);14.5 Symbolic symbols
-The swigwarn.swg file that is installed with SWIG contains - symbol constants that could also be used in %warnfilter and -#pragma SWIG nowarn. For example this file contains the following - line:
+Finally, to implement a varargs function, recall that you have to + use the C library functions defined in <stdarg.h>. For + example:
--%define SWIGWARN_TYPE_UNDEFINED_CLASS 401 %enddef +List make_list(const char *s, ...) { + va_list ap; + List x; + ... + va_start(ap, s); + while (s) { + x.append(s); + s = va_arg(ap, const char *); + } + va_end(ap); + return x; +}so SWIGWARN_TYPE_UNDEFINED_CLASS could be used instead of - 401, for example:
+14.2 The Problem
+Generating wrappers for a variable length argument function presents + a number of special challenges. Although C provides support for + implementing functions that receive variable length arguments, there + are no functions that can go in the other direction. Specifically, you + can't write a function that dynamically creates a list of arguments and + which invokes a varargs function on your behalf.
+Although it is possible to write functions that accept the special + type va_list, this is something entirely different. You can't + take a va_list structure and pass it in place of the variable + length arguments to another varargs function. It just doesn't work.
+The reason this doesn't work has to do with the way that function + calls get compiled. For example, suppose that your program has a + function call like this:
--#pragma SWIG nowarn=SWIGWARN_TYPE_UNDEFINED_CLASS +printf("Hello %s. Your number is %d\n", name, num);or
+When the compiler looks at this, it knows that you are calling +printf() with exactly three arguments. Furthermore, it knows that + the number of arguments as well are their types and sizes is never + going to change during program execution. Therefore, this gets turned + to machine code that sets up a three-argument stack frame followed by a + call to printf().
+In contrast, suppose you attempted to make some kind of wrapper + around printf() using code like this:
--%warnfilter(SWIGWARN_TYPE_UNDEFINED_CLASS) Foo; +int wrap_printf(const char *fmt, ...) { + va_list ap; + va_start(ap,fmt); + ... + printf(fmt,ap); + ... + va_end(ap); +};14.6 Commentary
-The ability to suppress warning messages is really only provided for - advanced users and is not recommended in normal use. You are advised to - modify your interface to fix the problems highlighted by the warnings - wherever possible instead of suppressing warnings.
-Certain types of SWIG problems are errors. These usually arise due - to parsing errors (bad syntax) or semantic problems for which there is - no obvious recovery. There is no mechanism for suppressing error - messages.
-14.7 Warnings as errors
-Warnings can be handled as errors by using the -Werror - command line option. This will cause SWIG to exit with a non successful - exit code if a warning is encountered.
-14.8 Message output format
-The output format for both warnings and errors can be selected for - integration with your favourite IDE/editor. Editors and IDEs can - usually parse error messages and if in the appropriate format will - easily take you directly to the source of the error. The standard - format is used by default except on Windows where the Microsoft format - is used by default. These can be overridden using command line options, - for example:
----$ swig -python -Fstandard example.i -example.i:4: Syntax error in input. -$ swig -python -Fmicrosoft example.i -example.i(4) : Syntax error in input. +Although this code might compile, it won't do what you expect. This + is because the call to printf() is compiled as a procedure + call involving only two arguments. However, clearly a two-argument + configuration of the call stack is completely wrong if your intent is + to pass an arbitrary number of arguments to the real printf(). + Needless to say, it won't work.
+Unfortunately, the situation just described is exactly the problem + faced by wrapper generation tools. In general, the number of passed + arguments will not be known until run-time. To make matters even worse, + you won't know the types and sizes of arguments until run-time as well. + Needless to say, there is no obvious way to make the C compiler + generate code for a function call involving an unknown number of + arguments of unknown types.
+In theory, it is possible to write a wrapper that does the + right thing. However, this involves knowing the underlying ABI for the + target platform and language as well as writing special purpose code + that manually constructed the call stack before making a procedure + call. Unfortunately, both of these tasks require the use of inline + assembly code. Clearly, that's the kind of solution you would much + rather avoid.
+With this nastiness in mind, SWIG provides a number of solutions to + the varargs wrapping problem. Most of these solutions are compromises + that provide limited varargs support without having to resort to + assembly language. However, SWIG can also support real varargs wrapping + (with stack-frame manipulation) if you are willing to get hands dirty. + Keep reading.
+14.3 Default varargs support
+When variable length arguments appear in an interface, the default + behavior is to drop the variable argument list entirely, replacing them + with a single NULL pointer. For example, if you had this function,
++-+void traceprintf(const char *fmt, ...);14.9 Warning number reference
-14.9.1 Deprecated features (100-199)
--
-- 101. Deprecated %extern directive.
-- 102. Deprecated %val directive.
-- 103. Deprecated %out directive.
-- 104. Deprecated %disabledoc directive.
-- 105. Deprecated %enabledoc directive.
-- 106. Deprecated %doconly directive.
-- 107. Deprecated %style directive.
-- 108. Deprecated %localstyle directive.
-- 109. Deprecated %title directive.
-- 110. Deprecated %section directive.
-- 111. Deprecated %subsection directive.
-- 112. Deprecated %subsubsection directive.
-- 113. Deprecated %addmethods directive.
-- 114. Deprecated %readonly directive.
-- 115. Deprecated %readwrite directive.
-- 116. Deprecated %except directive.
-- 117. Deprecated %new directive.
-- 118. Deprecated %typemap(except).
-- 119. Deprecated %typemap(ignore).
-- 120. Deprecated command line option (-runtime, -noruntime).
-- 121. Deprecated %name directive.
-14.9.2 Preprocessor (200-299)
--
-- 201. Unable to find filename.
-- 202. Could not evaluate expression expr.
-- 203. Both includeall and importall are defined: using includeall.
-- 204. CPP #warning, "warning".
-- 205. CPP #error, "error".
-- 206. Unexpected tokens after #directive directive.
-14.9.3 C/C++ Parser (300-399)
--
-- 301. class keyword used, but not in C++ mode.
-- 302. Identifier 'name' redefined (ignored).
-- 303. %extend defined for an undeclared class 'name -'.
-- 304. Unsupported constant value (ignored).
-- 305. Bad constant value (ignored).
-- 306. 'identifier' is private in this context.
-- 307. Can't set default argument value (ignored)
-- 308. Namespace alias 'name' not allowed here. Assuming ' -name'
-- 309. [private | protected] inheritance ignored.
-- 310. Template 'name' was already wrapped as 'name' - (ignored)
-- 312. Unnamed nested class not currently supported (ignored).
-- 313. Unrecognized extern type "name" (ignored).
-- 314. 'identifier' is a lang keyword.
-- 315. Nothing known about 'identifier'.
-- 316. Repeated %module directive.
-- 317. Specialization of non-template 'name'.
-- 318. Instantiation of template 'name' is ambiguous, - instantiation templ used, instantiation templ - ignored.
-- 319. No access specifier given for base class name - (ignored).
-- 320. Explicit template instantiation ignored.
-- 321. identifier conflicts with a built-in name.
-- 322. Redundant redeclaration of 'name'.
-- 323. Recursive scope inheritance of 'name'.
-- 324. Named nested template instantiations not supported. Processing - as if no name was given to %template().
-- 325. Nested kind not currently supported (name - ignored).
-- 326. Deprecated %extend name used - the kind name 'name -' should be used instead of the typedef name 'name'.
-- 350. operator new ignored.
-- 351. operator delete ignored.
-- 352. operator+ ignored.
-- 353. operator- ignored.
-- 354. operator* ignored.
-- 355. operator/ ignored.
-- 356. operator% ignored.
-- 357. operator^ ignored.
-- 358. operator& ignored.
-- 359. operator| ignored.
-- 360. operator~ ignored.
-- 361. operator! ignored.
-- 362. operator= ignored.
-- 363. operator< ignored.
-- 364. operator> ignored.
-- 365. operator+= ignored.
-- 366. operator-= ignored.
-- 367. operator*= ignored.
-- 368. operator/= ignored.
-- 369. operator%= ignored.
-- 370. operator^= ignored.
-- 371. operator&= ignored.
-- 372. operator|= ignored.
-- 373. operator<< ignored.
-- 374. operator>>ignored.
-- 375. operator<<= ignored.
-- 376. operator>>= ignored.
-- 377. operator== ignored.
-- 378. operator!= ignored.
-- 379. operator<= ignored.
-- 380. operator>= ignored.
-- 381. operator&& ignored.
-- 382. operator|| ignored.
-- 383. operator++ ignored.
-- 384. operator-- ignored.
-- 385. operator, ignored.
-- 386. operator-<* ignored.
-- 387. operator-< ignored.
-- 388. operator() ignored.
-- 389. operator[] ignored.
-- 390. operator+ ignored (unary).
-- 391. operator- ignored (unary).
-- 392. operator* ignored (unary).
-- 393. operator& ignored (unary).
-- 394. operator new[] ignored.
-- 395. operator delete[] ignored.
-14.9.4 Types and typemaps (400-499)
--
-- 401. Nothing known about class 'name'. Ignored.
-- 402. Base class 'name' is incomplete.
-- 403. Class 'name' might be abstract.
-- 450. Deprecated typemap feature ($source/$target).
-- 451. Setting const char * variable may leak memory.
-- 452. Reserved
-- 453. Can't apply (pattern). No typemaps are defined.
-- 460. Unable to use type type as a function argument.
-- 461. Unable to use return type type in function name -.
-- 462. Unable to set variable of type type.
-- 463. Unable to read variable of type type.
-- 464. Unsupported constant value.
-- 465. Unable to handle type type.
-- 466. Unsupported variable type type.
-- 467. Overloaded declaration not supported (no type checking - rule for 'type')
-- 468. No 'throw' typemap defined for exception type type
-- 469. No or improper directorin typemap defined for type
-- 470. Thread/reentrant unsafe wrapping, consider returning by value - instead.
-- 471. Unable to use return type type in director method
-- 474. Method method usage of the optimal attribute ignored - in the out typemap as the following cannot be used to generate optimal - code: code
-- 475. Multiple calls to method might be generated due to - optimal attribute usage in the out typemap.
-14.9.5 Code generation (500-599)
--
-- 501. Overloaded declaration ignored. decl. Previous - declaration is decl.
-- 502. Overloaded constructor ignored. decl. Previous - declaration is decl.
-- 503. Can't wrap 'identifier' unless renamed to a valid - identifier.
-- 504. Function name must have a return type. Ignored.
-- 505. Variable length arguments discarded.
-- 506. Can't wrap varargs with keyword arguments enabled.
-- 507. Adding native function name not supported (ignored).
-- 508. Declaration of 'name' shadows declaration accessible - via operator->(), previous declaration of'declaration'.
-- 509. Overloaded method declaration effectively ignored, as - it is shadowed by declaration.
-- 510. Friend function 'name' ignored.
-- 511. Can't use keyword arguments with overloaded functions.
-- 512. Overloaded method declaration ignored, using non-const - method declaration instead.
-- 513. Can't generate wrappers for unnamed struct/class.
-- 514.
-- 515.
-- 516. Overloaded method declaration ignored, using - declaration instead.
-- 517.
-- 518. Portability warning: File file1 will be overwritten by - file2 on case insensitive filesystems such as Windows' FAT32 and - NTFS unless the class/module name is renamed.
-- 519. %template() contains no name. Template method ignored: - declaration
-- 520. Base/Derived class 'classname1' of ' -classname2' is not similarly marked as a smart pointer.
-- 521. Illegal destructor name name. Ignored.
-- 522. Use of an illegal constructor name 'name' in %extend - is deprecated, the constructor name should be 'name'.
-- 523. Use of an illegal destructor name 'name' in %extend is - deprecated, the destructor name should be 'name'.
-14.9.6 Language module specific - (700-899)
--
-- 801. Wrong name (corrected to 'name'). (Ruby).
--
-- 810. No jni typemap defined for type (Java).
-- 811. No jtype typemap defined for type (Java).
-- 812. No jstype typemap defined for type (Java).
-- 813. Warning for classname: Base baseclass - ignored. Multiple inheritance is not supported in Java. (Java).
-- 814.
-- 815. No javafinalize typemap defined for type (Java).
-- 816. No javabody typemap defined for type (Java).
-- 817. No javaout typemap defined for type (Java).
-- 818. No javain typemap defined for type (Java).
-- 819. No javadirectorin typemap defined for type (Java).
-- 820. No javadirectorout typemap defined for type (Java).
-- 821.
-- 822. Covariant return types not supported in Java. Proxy method will - return basetype (Java).
-- 823. No javaconstruct typemap defined for type (Java).
-- 824. Missing JNI descriptor in directorin typemap defined for - type (Java).
-- 825. "directorconnect" attribute missing in type - "javaconstruct" typemap. (Java).
-- 826. The nspace feature is used on 'type' without -package. - The generated code may not compile as Java does not support types - declared in a named package accessing types declared in an unnamed - package. (Java).
--
-- 830. No ctype typemap defined for type (C#).
-- 831. No cstype typemap defined for type (C#).
-- 832. No cswtype typemap defined for type (C#).
-- 833. Warning for classname: Base baseclass - ignored. Multiple inheritance is not supported in C#. (C#).
-- 834.
-- 835. No csfinalize typemap defined for type (C#).
-- 836. No csbody typemap defined for type (C#).
-- 837. No csout typemap defined for type (C#).
-- 838. No csin typemap defined for type (C#).
-- 839.
-- 840.
-- 841.
-- 842. Covariant return types not supported in C#. Proxy method will - return basetype (C#).
-- 843. No csconstruct typemap defined for type (C#).
-- 844. C# exception may not be thrown - no $excode or excode attribute - in typemap typemap. (C#).
-- 845. Unmanaged code contains a call to a - SWIG_CSharpSetPendingException method and C# code does not handle - pending exceptions via the canthrow attribute. (C#).
--
-- 870. Warning for classname: Base baseclass - ignored. Multiple inheritance is not supported in PHP.
-- 871. Unrecognized pragma pragma. (Php).
-14.9.7 User defined (900-999)
-These numbers can be used by your own application.
-14.10 History
-The ability to control warning messages was first added to - SWIG-1.3.12.
-
-15 Working with Modules
- - ----
+- Modules Introduction
-- Basics
-- The SWIG runtime code
-- External access to the runtime -
-- A word of caution about static libraries
-- References
-- Reducing the wrapper file size
-it would be wrapped as if it had been declared as follows:
++- -+void traceprintf(const char *fmt); +15.1 Modules Introduction
-Each invocation of SWIG requires a module name to be specified. The - module name is used to name the resulting target language extension - module. Exactly what this means and what the name is used for depends - on the target language, for example the name can define a target - language namespace or merely be a useful name for naming files or - helper classes. Essentially, a module comprises target language - wrappers for a chosen collection of global variables/functions, - structs/classes and other C/C++ types.
-The module name can be supplied in one of two ways. The first is to - specify it with the special %module directive. This directive - must appear at the beginning of the interface file. The general form of - this directive is:
+When the function is called inside the wrappers, it is called as + follows:
--%module(option1="value1",option2="value2",...) modulename +traceprintf(arg1, NULL);where the modulename is mandatory and the options add one or more - optional additional features. Typically no options are specified, for - example:
+Arguably, this approach seems to defeat the whole point of variable + length arguments. However, this actually provides enough support for + many simple kinds of varargs functions to still be useful, however it + does come with a caveat. For instance, you could make function calls + like this (in Python):
++++>>> traceprintf("Hello World") +>>> traceprintf("Hello %s. Your number is %d\n" % (name, num)) +>>> traceprintf("Your result is 90%%.") ++Notice how string formatting is being done in Python instead of C. + The caveat is the strings passed must be safe to use in C though. For + example if name was to contain a "%" it should be double escaped in + order to avoid unpredictable behaviour:
++++>>> traceprintf("Your result is 90%.\n") # unpredictable behaviour +>>> traceprintf("Your result is 90%%.\n") # good ++Read on for further solutions.
+14.4 Argument replacement using %varargs
+Instead of dropping the variable length arguments, an alternative + approach is to replace (...) with a set of suitable arguments. + SWIG provides a special %varargs directive that can be used to + do this. For example,
--%module mymodule +%varargs(int mode = 0) open; +... +int open(const char *path, int oflags, ...);The second way to specify the module name is with the -module - command line option, for example -module mymodule. If the - module name is supplied on the command line, it overrides the name - specified by the %module directive.
-When first working with SWIG, users commonly start by creating a - single module. That is, you might define a single SWIG interface that - wraps some set of C/C++ code. You then compile all of the generated - wrapper code together and use it. For large applications, however, this - approach is problematic---the size of the generated wrapper code can be - rather large. Moreover, it is probably easier to manage the target - language interface when it is broken up into smaller pieces.
-This chapter describes the problem of using SWIG in programs where - you want to create a collection of modules. Each module in the - collection is created via separate invocations of SWIG.
-15.2 Basics
-The basic usage case with multiple modules is when modules do not - have cross-references (ie. when wrapping multiple independent C APIs). - In that case, swig input files should just work out of the box - you - simply create multiple wrapper .cxx files, link them into your - application, and insert/load each in the scripting language runtime as - you would do for the single module case.
-A bit more complex is the case in which modules need to share - information. For example, when one module extends the class of another - by deriving from it:
+is equivalent to this:
-// File: base.h -class base { -public: - int foo(); -}; +int open(const char *path, int oflags, int mode = 0);-++In this case, %varargs is simply providing more specific + information about the extra arguments that might be passed to a + function. If the arguments to a varargs function are of uniform type, +%varargs can also accept a numerical argument count as follows:
+-// File: base_module.i -%module base_module - -%{ -#include "base.h" -%} -%include "base.h" +%varargs(3, char *str = NULL) execlp; +... +int execlp(const char *path, const char *arg, ...);-++and is effectively seen as:
+--// File: derived_module.i -%module derived_module - -%import "base_module.i" - -%inline %{ -class derived : public base { -public: - int bar(); -}; -%} +int execlp(const char *path, const char *arg, + char *str1 = NULL, + char *str2 = NULL, + char *str3 = NULL);To create the wrapper properly, module derived_module needs - to know about the base class and that its interface is covered - in another module. The line %import "base_module.i" lets SWIG - know exactly that. Oftentimes the .h file is passed to -%import instead of the .i, which unfortunately doesn't - work for all language modules. For example, Python requires the name of - module that the base class exists in so that the proxy classes can - fully inherit the base class's methods. Typically you will get a - warning when the module name is missing, eg:
-+-This would wrap execlp() as a function that accepted up to + 3 optional arguments. Depending on the application, this may be more + than enough for practical purposes.
+The handling of default arguments + can be changed via the compactdefaultargs feature. If this + feature is used, for example
+--derived_module.i:8: Warning 401: Base class 'base' ignored - unknown module name for base. Either -import -the appropriate module interface file or specify the name of the module in the %import directive. +%feature("compactdefaultargs") execlp; +%varargs(3, char *str = NULL) execlp; +... +int execlp(const char *path, const char *arg, ...);It is sometimes desirable to import the header file rather than the - interface file and overcome the above warning. For example in the case - of the imported interface being quite large, it may be desirable to - simplify matters and just import a small header file of dependent - types. This can be done by specifying the optional module - attribute in the %import directive. The derived_module.i - file shown above could be replaced with the following:
++a call from the target language which does not provide the maximum + number of arguments, such as, execlp("a", "b", "c") will + generate C code which includes the missing default values, that is, +execlp("a", "b", "c", NULL, NULL). If compactdefaultargs + is not used, then the generated code will be execlp("a", "b", "c") +. The former is useful for helping providing a sentinel to terminate the + argument list. However, this is not guaranteed, for example when a user + passes a non-NULL value for all the parameters. When using +compactdefaultargs it is possible to guarantee the NULL sentinel is + passed through the, numinputs=0 'in' + typemap attribute, naming the last parameter. For example,
++-// File: derived_module.i -%module derived_module - -%import(module="base_module") "base.h" +%feature("compactdefaultargs") execlp; +%varargs(3, char *str = NULL) execlp; +%typemap(in, numinputs=0) char *str3 "" +... +int execlp(const char *path, const char *arg, ...); ++Note that str3 is the name of the last argument, as we have + used %varargs with 3. Now execlp("a", "b", "c", "d", "e") + will result in an error as one too many arguments has been passed, as + now only 2 additional 'str' arguments can be passed with the 3rd one + always using the specified default NULL.
+Argument replacement is most appropriate in cases where the types of + the extra arguments are uniform and the maximum number of arguments are + known. Argument replacement is not as useful when working with + functions that accept mixed argument types such as printf(). + Providing general purpose wrappers to such functions presents special + problems (covered shortly).
+14.5 Varargs and typemaps
+Variable length arguments may be used in typemap specifications. For + example:
++++%typemap(in) (...) { + // Get variable length arguments (somehow) + ... +} -%inline %{ -class derived : public base { -public: - int bar(); +%typemap(in) (const char *fmt, ...) { + // Multi-argument typemap +} ++However, this immediately raises the question of what "type" is + actually used to represent (...). For lack of a better + alternative, the type of (...) is set to void *. + Since there is no way to dynamically pass arguments to a varargs + function (as previously described), the void * argument value + is intended to serve as a place holder for storing some kind of + information about the extra arguments (if any). In addition, the + default behavior of SWIG is to pass the void * value as an + argument to the function. Therefore, you could use the pointer to hold + a valid argument value if you wanted.
+To illustrate, here is a safer version of wrapping printf() + in Python:
++-+%typemap(in) (const char *fmt, ...) { + $1 = "%s"; /* Fix format string to %s */ + $2 = (void *) PyString_AsString($input); /* Get string argument */ }; +... +int printf(const char *fmt, ...);-Note that "base_module" is the module name and is the same as that - specified in %module in base_module.i as well as the -%import in derived_module.i.
-Another issue to beware of is that multiple dependent wrappers - should not be linked/loaded in parallel from multiple threads as SWIG - provides no locking - for more on that issue, read on.
-15.3 The SWIG runtime code
-Many of SWIG's target languages generate a set of functions commonly - known as the "SWIG runtime." These functions are primarily related to - the runtime type system which checks pointer types and performs other - tasks such as proper casting of pointer values in C++. As a general - rule, the statically typed target languages, such as Java, use the - language's built in static type checking and have no need for a SWIG - runtime. All the dynamically typed / interpreted languages rely on the - SWIG runtime.
-The runtime functions are private to each SWIG-generated module. - That is, the runtime functions are declared with "static" linkage and - are visible only to the wrapper functions defined in that module. The - only problem with this approach is that when more than one SWIG module - is used in the same application, those modules often need to share type - information. This is especially true for C++ programs where SWIG must - collect and share information about inheritance relationships that - cross module boundaries.
-To solve the problem of sharing information across modules, a - pointer to the type information is stored in a global variable in the - target language namespace. During module initialization, type - information is loaded into the global data structure of type - information from all modules.
-There are a few trade offs with this approach. This type information - is global across all SWIG modules loaded, and can cause type conflicts - between modules that were not designed to work together. To solve this - approach, the SWIG runtime code uses a define SWIG_TYPE_TABLE to - provide a unique type table. This behavior can be enabled when - compiling the generated _wrap.cxx or _wrap.c file by adding - -DSWIG_TYPE_TABLE=myprojectname to the command line argument.
-Then, only modules compiled with SWIG_TYPE_TABLE set to - myprojectname will share type information. So if your project has three - modules, all three should be compiled with - -DSWIG_TYPE_TABLE=myprojectname, and then these three modules will - share type information. But any other project's types will not - interfere or clash with the types in your module.
-Another issue relating to the global type table is thread safety. If - two modules try and load at the same time, the type information can - become corrupt. SWIG currently does not provide any locking, and if you - use threads, you must make sure that modules are loaded serially. Be - careful if you use threads and the automatic module loading that some - scripting languages provide. One solution is to load all modules before - spawning any threads, or use SWIG_TYPE_TABLE to separate type tables so - they do not clash with each other.
-Lastly, SWIG uses a #define SWIG_RUNTIME_VERSION, located in - Lib/swigrun.swg and near the top of every generated module. This number - gets incremented when the data structures change, so that SWIG modules - generated with different versions can peacefully coexist. So the type - structures are separated by the (SWIG_TYPE_TABLE, SWIG_RUNTIME_VERSION) - pair, where by default SWIG_TYPE_TABLE is empty. Only modules compiled - with the same pair will share type information.
-15.4 External access to the - runtime
-As described in The run-time - type checker, the functions SWIG_TypeQuery, -SWIG_NewPointerObj, and others sometimes need to be called. Calling - these functions from a typemap is supported, since the typemap code is - embedded into the _wrap.c file, which has those declarations - available. If you need to call the SWIG run-time functions from another - C file, there is one header you need to include. To generate the header - that needs to be included, run the following command:
++In this example, the format string is implicitly set to "%s" +. This prevents a program from passing a bogus format string to the + extension. Then, the passed input object is decoded and placed in the +void * argument defined for the (...) argument. When the + actual function call is made, the underlying wrapper code will look + roughly like this:
+--$ swig -python -external-runtime <filename> +wrap_printf() { + char *arg1; + void *arg2; + int result; + + arg1 = "%s"; + arg2 = (void *) PyString_AsString(arg2obj); + ... + result = printf(arg1,arg2); + ... +}-The filename argument is optional and if it is not passed, then the - default filename will be something like swigpyrun.h, depending - on the language. This header file should be treated like any of the - other _wrap.c output files, and should be regenerated when the _wrap - files are. After including this header, your code will be able to call -SWIG_TypeQuery, SWIG_NewPointerObj, SWIG_ConvertPtr - and others. The exact argument parameters for these functions might - differ between language modules; please check the language module - chapters for more information.
-Inside this header the functions are declared static and are included - inline into the file, and thus the file does not need to be linked - against any SWIG libraries or code (you might still need to link - against the language libraries like libpython-2.3). Data is shared - between this file and the _wrap.c files through a global variable in - the scripting language. It is also possible to copy this header file - along with the generated wrapper files into your own package, so that - you can distribute a package that can be compiled without SWIG - installed (this works because the header file is self-contained, and - does not need to link with anything).
-This header will also use the -DSWIG_TYPE_TABLE described above, so - when compiling any code which includes the generated header file should - define the SWIG_TYPE_TABLE to be the same as the module whose types you - are trying to access.
-15.5 A word of caution about static - libraries
-When working with multiple SWIG modules, you should take care not to - use static libraries. For example, if you have a static library -libfoo.a and you link a collection of SWIG modules with that - library, each module will get its own private copy of the library code - inserted into it. This is very often NOT what you want and it - can lead to unexpected or bizarre program behavior. When working with - dynamically loadable modules, you should try to work exclusively with - shared libraries.
-15.6 References
-Due to the complexity of working with shared libraries and multiple - modules, it might be a good idea to consult an outside reference. John - Levine's "Linkers and Loaders" is highly recommended.
-15.7 Reducing the wrapper file size
-Using multiple modules with the %import directive is the - most common approach to modularising large projects. In this way a - number of different wrapper files can be generated, thereby avoiding - the generation of a single large wrapper file. There are a couple of - alternative solutions for reducing the size of a wrapper file through - the use of command line options and features.
--fcompact -
-
This command line option will compact the size of the wrapper file - without changing the code generated into the wrapper file. It simply - removes blank lines and joins lines of code together. This is useful - for compilers that have a maximum file size that can be handled.-fvirtual -
+
This command line option will remove the generation of superfluous - virtual method wrappers. Consider the following inheritance hierarchy:Notice how both arguments are passed to the function and it does + what you would expect.
+The next example illustrates a more advanced kind of varargs + typemap. Disclaimer: this requires special support in the target + language module and is not guaranteed to work with all SWIG modules at + this time. It also starts to illustrate some of the more fundamental + problems with supporting varargs in more generality.
+If a typemap is defined for any form of (...), many SWIG + modules will generate wrappers that accept a variable number of + arguments as input and will make these arguments available in some + form. The precise details of this depends on the language module being + used (consult the appropriate chapter for more details). However, + suppose that you wanted to create a Python wrapper for the execlp() + function shown earlier. To do this using a typemap instead of using +%varargs, you might first write a typemap like this:
--struct Base { - virtual void method(); - ... -}; +%typemap(in) (...)(char *vargs[10]) { + int i; + int argc; + for (i = 0; i < 10; i++) vargs[i] = 0; + argc = PyTuple_Size(varargs); + if (argc > 10) { + PyErr_SetString(PyExc_ValueError, "Too many arguments"); + return NULL; + } + for (i = 0; i < argc; i++) { + PyObject *pyobj = PyTuple_GetItem(varargs, i); + char *str = 0; +%#if PY_VERSION_HEX>=0x03000000 + PyObject *pystr; + if (!PyUnicode_Check(pyobj)) { + PyErr_SetString(PyExc_ValueError, "Expected a string"); + return NULL; + } + pystr = PyUnicode_AsUTF8String(pyobj); + str = strdup(PyBytes_AsString(pystr)); + Py_XDECREF(pystr); +%#else + if (!PyString_Check(pyobj)) { + PyErr_SetString(PyExc_ValueError, "Expected a string"); + return NULL; + } + str = PyString_AsString(pyobj); +%#endif + vargs[i] = str; + } + $1 = (void *)vargs; +} -struct Derived : Base { - virtual void method(); - ... -}; +%typemap(freearg) (...) { +%#if PY_VERSION_HEX>=0x03000000 + int i; + for (i = 0; i < 10; i++) { + free(vargs$argnum[i]); + } +%#endif +}Normally wrappers are generated for both methods, whereas this - command line option will suppress the generation of a wrapper for -Derived::method. Normal polymorphic behaviour remains as -Derived::method will still be called should you have a Derived - instance and call the wrapper for Base::method.
-%feature("compactdefaultargs") -
-
This feature can reduce the number of wrapper methods when wrapping - methods with default arguments. The section on -default arguments discusses the feature and its limitations.
-16 Using SWIG with ccache - ccache-swig(1) - manpage
+In the 'in' typemap, the special variable varargs is a + tuple holding all of the extra arguments passed (this is specific to + the Python module). The typemap then pulls this apart and sticks the + values into the array of strings args. Then, the array is + assigned to $1 (recall that this is the void * + variable corresponding to (...)). However, this assignment is + only half of the picture----clearly this alone is not enough to make + the function work. The 'freearg' typemap cleans up memory allocated in + the 'in' typemap; this code is generated to be called after the +execlp function is called. To patch everything up, you have to + rewrite the underlying action code using the %feature + directive like this:
+++%feature("action") execlp { + char **vargs = (char **) arg3; + result = execlp(arg1, arg2, vargs[0], vargs[1], vargs[2], vargs[3], vargs[4], + vargs[5], vargs[6], vargs[7], vargs[8], vargs[9], NULL); +} - -- +int execlp(const char *path, const char *arg, ...); +- - -16.1 NAME
-ccache-swig - a fast compiler cache
- -16.2 SYNOPSIS
-ccache-swig [OPTION]
-ccache-swig <compiler> [COMPILER OPTIONS]
-<compiler> [COMPILER OPTIONS]
- -16.3 DESCRIPTION
-ccache-swig is a compiler cache. It speeds up re-compilation of - C/C++/SWIG code by caching previous compiles and detecting when the - same compile is being done again. ccache-swig is ccache plus support - for SWIG. ccache and ccache-swig are used interchangeably in this - document.
- -16.4 OPTIONS SUMMARY
-Here is a summary of the options to ccache-swig.
- +This patches everything up and creates a function that more or less + works. However, don't try explaining this to your coworkers unless you + know for certain that they've had several cups of coffee. If you really + want to elevate your guru status and increase your job security, + continue to the next section.
+14.6 Varargs wrapping with libffi
+All of the previous examples have relied on features of SWIG that + are portable and which don't rely upon any low-level machine-level + details. In many ways, they have all dodged the real issue of variable + length arguments by recasting a varargs function into some weaker + variation with a fixed number of arguments of known types. In many + cases, this works perfectly fine. However, if you want more generality + than this, you need to bring out some bigger guns.
+One way to do this is to use a special purpose library such as + libffi ( +http://www.sourceware.org/libffi/). libffi is a library that allows + you to dynamically construct call-stacks and invoke procedures in a + relatively platform independent manner. Details about the library can + be found in the libffi distribution and are not repeated here.
+To illustrate the use of libffi, suppose that you really + wanted to create a wrapper for execlp() that accepted any + number of arguments. To do this, you might make a few adjustments to + the previous example. For example:
+++/* Take an arbitrary number of extra arguments and place into an array + of strings */ --s show statistics summary --z zero statistics --c run a cache cleanup --C clear the cache completely --F <n> set maximum files in cache --M <n> set maximum size of cache (use G, M or K) --h this help page --V print version number +%typemap(in) (...) { + char **argv; + int argc; + int i; + + argc = PyTuple_Size(varargs); + argv = (char **) malloc(sizeof(char *)*(argc+1)); + for (i = 0; i < argc; i++) { + PyObject *o = PyTuple_GetItem(varargs,i); + if (!PyString_Check(o)) { + PyErr_SetString(PyExc_ValueError,"Expected a string"); + free(argv); + return NULL; + } + argv[i] = PyString_AsString(o); + } + argv[i] = NULL; + $1 = (void *) argv; +} + +/* Rewrite the function call, using libffi */ + +%feature("action") execlp { + int i, vc; + ffi_cif cif; + ffi_type **types; + void **values; + char **args; + + vc = PyTuple_Size(varargs); + types = (ffi_type **) malloc((vc+3)*sizeof(ffi_type *)); + values = (void **) malloc((vc+3)*sizeof(void *)); + args = (char **) arg3; + + /* Set up path parameter */ + types[0] = &ffi_type_pointer; + values[0] = &arg1; + + /* Set up first argument */ + types[1] = &ffi_type_pointer; + values[1] = &arg2; + + /* Set up rest of parameters */ + for (i = 0; i <= vc; i++) { + types[2+i] = &ffi_type_pointer; + values[2+i] = &args[i]; + } + if (ffi_prep_cif(&cif, FFI_DEFAULT_ABI, vc+3, + &ffi_type_uint, types) == FFI_OK) { + ffi_call(&cif, (void (*)()) execlp, &result, values); + } else { + PyErr_SetString(PyExc_RuntimeError, "Whoa!!!!!"); + free(types); + free(values); + free(arg3); + return NULL; + } + free(types); + free(values); + free(arg3); +} +/* Declare the function. Whew! */ +int execlp(const char *path, const char *arg1, ...);- -16.5 OPTIONS
-These options only apply when you invoke ccache as "ccache-swig". - When invoked as a compiler none of these options apply. In that case - your normal compiler options apply and you should refer to your - compilers documentation.
- --
- --
- -h
-- Print a options summary page - - -
-- -s
-- Print the current statistics summary for the cache. The statistics - are stored spread across the subdirectories of the cache. Using - "ccache-swig -s" adds up the statistics across all subdirectories and - prints the totals. - - -
-- -z
-- Zero the cache statistics. - - -
-- -V
-- Print the ccache version number - - -
-- -c
-- Clean the cache and re-calculate the cache file count and size - totals. Normally the -c option should not be necessary as ccache keeps - the cache below the specified limits at runtime and keeps statistics up - to date on each compile. This option is mostly useful if you manually - modify the cache contents or believe that the cache size statistics may - be inaccurate. - - -
-- -C
-- Clear the entire cache, removing all cached files. - - -
-- -F <maxfiles>
-- This sets the maximum number of files allowed in the cache. The - value is stored inside the cache directory and applies to all future - compiles. Due to the way the value is stored the actual value used is - always rounded down to the nearest multiple of 16. - - -
-- -M <maxsize>
-- This sets the maximum cache size. You can specify a value in - gigabytes, megabytes or kilobytes by appending a G, M or K to the - value. The default is gigabytes. The actual value stored is rounded - down to the nearest multiple of 16 kilobytes. - -
- -16.6 INSTALLATION
-There are two ways to use ccache. You can either prefix your compile - commands with "ccache-swig" or you can create a symbolic link between - ccache-swig and the names of your compilers. The first method is most - convenient if you just want to try out ccache or wish to use it for - some specific projects. The second method is most useful for when you - wish to use ccache for all your compiles.
-To install for usage by the first method just copy ccache-swig to - somewhere in your path.
-To install for the second method do something like this:
+Looking at this example, you may start to wonder if SWIG is making + life any easier. Given the amount of code involved, you might also + wonder why you didn't just write a hand-crafted wrapper! Either that or + you're wondering "why in the hell am I trying to wrap this varargs + function in the first place?!?" Obviously, those are questions you'll + have to answer for yourself.
+As a more extreme example of libffi, here is some code that attempts + to wrap printf(),
+++/* A wrapper for printf() using libffi */ - cp ccache-swig /usr/local/bin/ - ln -s /usr/local/bin/ccache-swig /usr/local/bin/gcc - ln -s /usr/local/bin/ccache-swig /usr/local/bin/g++ - ln -s /usr/local/bin/ccache-swig /usr/local/bin/cc - ln -s /usr/local/bin/ccache-swig /usr/local/bin/swig +%{ +/* Structure for holding passed arguments after conversion */ + typedef struct { + int type; + union { + int ivalue; + double dvalue; + void *pvalue; + } val; + } vtype; + enum { VT_INT, VT_DOUBLE, VT_POINTER }; +%} -- This will work as long as /usr/local/bin comes before the path to gcc - (which is usually in /usr/bin). After installing you may wish to run - "which gcc" to make sure that the correct link is being used. -Note! Do not use a hard link, use a symbolic link. A hardlink will - cause "interesting" problems.
- -16.7 EXTRA OPTIONS
-When run as a compiler front end ccache usually just takes the same - command line options as the compiler you are using. The only exception - to this is the option '--ccache-skip'. That option can be used to tell - ccache that the next option is definitely not a input filename, and - should be passed along to the compiler as-is.
-The reason this can be important is that ccache does need to parse - the command line and determine what is an input filename and what is a - compiler option, as it needs the input filename to determine the name - of the resulting object file (among other things). The heuristic ccache - uses in this parse is that any string on the command line that exists - as a file is treated as an input file name (usually a C file). By using - --ccache-skip you can force an option to not be treated as an input - file name and instead be passed along to the compiler as a command line - option.
- -16.8 ENVIRONMENT VARIABLES
-ccache uses a number of environment variables to control operation. - In most cases you won't need any of these as the defaults will be fine.
- -- -
-
- CCACHE_DIR
-- the CCACHE_DIR environment variable specifies where ccache will - keep its cached compiler output. The default is "$HOME/.ccache". - - -
-- CCACHE_TEMPDIR
-- the CCACHE_TEMPDIR environment variable specifies where ccache will - put temporary files. The default is the same as CCACHE_DIR. Note that - the CCACHE_TEMPDIR path must be on the same filesystem as the - CCACHE_DIR path, so that renames of files between the two directories - can work. - - -
-- CCACHE_LOGFILE
-- If you set the CCACHE_LOGFILE environment variable then ccache will - write some log information on cache hits and misses in that file. This - is useful for tracking down problems. - - -
-- CCACHE_VERBOSE
-- If you set the CCACHE_VERBOSE environment variable then ccache will - display on stdout all the compiler invocations that it makes. This can - useful for debugging unexpected problems. - - -
-- CCACHE_PATH
-- You can optionally set CCACHE_PATH to a colon separated path where - ccache will look for the real compilers. If you don't do this then - ccache will look for the first executable matching the compiler name in - the normal PATH that isn't a symbolic link to ccache itself. - - -
-- CCACHE_CC
+%typemap(in) (const char *fmt, ...) { + vtype *argv; + int argc; + int i; + + /* Format string */ + $1 = PyString_AsString($input); + + /* Variable length arguments */ + argc = PyTuple_Size(varargs); + argv = (vtype *) malloc(argc*sizeof(vtype)); + for (i = 0; i < argc; i++) { + PyObject *o = PyTuple_GetItem(varargs,i); + if (PyInt_Check(o)) { + argv[i].type = VT_INT; + argv[i].val.ivalue = PyInt_AsLong(o); + } else if (PyFloat_Check(o)) { + argv[i].type = VT_DOUBLE; + argv[i].val.dvalue = PyFloat_AsDouble(o); + } else if (PyString_Check(o)) { + argv[i].type = VT_POINTER; + argv[i].val.pvalue = (void *) PyString_AsString(o); + } else { + PyErr_SetString(PyExc_ValueError,"Unsupported argument type"); + free(argv); + return NULL; + } + } + $2 = (void *) argv; +} + +/* Rewrite the function call using libffi */ +%feature("action") printf { + int i, vc; + ffi_cif cif; + ffi_type **types; + void **values; + vtype *args; + + vc = PyTuple_Size(varargs); + types = (ffi_type **) malloc((vc+1)*sizeof(ffi_type *)); + values = (void **) malloc((vc+1)*sizeof(void *)); + args = (vtype *) arg2; + + /* Set up fmt parameter */ + types[0] = &ffi_type_pointer; + values[0] = &arg1; + + /* Set up rest of parameters */ + for (i = 0; i < vc; i++) { + switch(args[i].type) { + case VT_INT: + types[1+i] = &ffi_type_uint; + values[1+i] = &args[i].val.ivalue; + break; + case VT_DOUBLE: + types[1+i] = &ffi_type_double; + values[1+i] = &args[i].val.dvalue; + break; + case VT_POINTER: + types[1+i] = &ffi_type_pointer; + values[1+i] = &args[i].val.pvalue; + break; + default: + abort(); /* Whoa! We're seriously hosed */ + break; + } + } + if (ffi_prep_cif(&cif, FFI_DEFAULT_ABI, vc+1, + &ffi_type_uint, types) == FFI_OK) { + ffi_call(&cif, (void (*)()) printf, &result, values); + } else { + PyErr_SetString(PyExc_RuntimeError, "Whoa!!!!!"); + free(types); + free(values); + free(args); + return NULL; + } + free(types); + free(values); + free(args); +} + +/* The function */ +int printf(const char *fmt, ...); + +Much to your amazement, it even seems to work if you try it:
++++>>> import example +>>> example.printf("Grade: %s %d/60 = %0.2f%%\n", "Dave", 47, 47.0*100/60) +Grade: Dave 47/60 = 78.33% +>>> ++Of course, there are still some limitations to consider:
++++>>> example.printf("la de da de da %s", 42) +Segmentation fault (core dumped) ++And, on this note, we leave further exploration of libffi to the + reader as an exercise. Although Python has been used as an example, + most of the techniques in this section can be extrapolated to other + language modules with a bit of work. The only details you need to know + is how the extra arguments are accessed in each target language. For + example, in the Python module, we used the special varargs + variable to get these arguments. Modules such as Tcl8 and Perl5 simply + provide an argument number for the first extra argument. This can be + used to index into an array of passed arguments to get values. Please + consult the chapter on each language module for more details.
+14.7 Wrapping of va_list
+Closely related to variable length argument wrapping, you may + encounter functions that accept a parameter of type va_list. + For example:
++++int vprintf(const char *fmt, va_list ap); ++As far as we know, there is no obvious way to wrap these functions + with SWIG. This is because there is no documented way to assemble the + proper va_list structure (there are no C library functions to do it and + the contents of va_list are opaque). Not only that, the contents of a +va_list structure are closely tied to the underlying call-stack. + It's not clear that exporting a va_list would have any use or + that it would work at all.
+A workaround can be implemented by writing a simple varargs C + wrapper and then using the techniques discussed earlier in this chapter + for varargs. Below is a simple wrapper for vprintf renamed so + that it can still be called as vprintf from your target + language. The %varargs used in the example restricts the + function to taking one string argument.
++++%{ +int vprintf(const char *fmt, va_list ap); +%} + +%varargs(const char *) my_vprintf; +%rename(vprintf) my_vprintf; + +%inline %{ +int my_vprintf(const char *fmt, ...) { + va_list ap; + int result; + + va_start(ap, fmt); + result = vprintf(fmt, ap); + va_end(ap); + return result; +} +%} ++14.8 C++ Issues
+Wrapping of C++ member functions that accept a variable number of + arguments presents a number of challenges. By far, the easiest way to + handle this is to use the %varargs directive. This is portable + and it fully supports classes much like the %rename directive. + For example:
++++%varargs (10, char * = NULL) Foo::bar; + +class Foo { +public: + virtual void bar(char *arg, ...); // gets varargs above +}; + +class Spam: public Foo { +public: + virtual void bar(char *arg, ...); // gets varargs above +}; ++%varargs also works with constructors, operators, and any + other C++ programming construct that accepts variable arguments.
+Doing anything more advanced than this is likely to involve a + serious world of pain. In order to use a library like libffi, you will + need to know the underlying calling conventions and details of the C++ + ABI. For instance, the details of how this is passed to member + functions as well as any hidden arguments that might be used to pass + additional information. These details are implementation specific and + may differ between compilers and even different versions of the same + compiler. Also, be aware that invoking a member function is further + complicated if it is a virtual method. In this case, invocation might + require a table lookup to obtain the proper function address (although + you might be able to obtain an address by casting a bound pointer to a + pointer to function as described in the C++ ARM section 18.3.4).
+If you do decide to change the underlying action code, be aware that + SWIG always places the this pointer in arg1. Other + arguments are placed in arg2, arg3, and so forth. For + example:
++++%feature("action") Foo::bar { + ... + result = arg1->bar(arg2, arg3, etc.); + ... +} ++Given the potential to shoot yourself in the foot, it is probably + easier to reconsider your design or to provide an alternative interface + using a helper function than it is to create a fully general wrapper to + a varargs C++ member function.
+14.9 Discussion
+This chapter has provided a number of techniques that can be used to + address the problem of variable length argument wrapping. If you care + about portability and ease of use, the %varargs directive is + probably the easiest way to tackle the problem. However, using + typemaps, it is possible to do some very advanced kinds of wrapping.
+One point of discussion concerns the structure of the libffi + examples in the previous section. Looking at that code, it is not at + all clear that this is the easiest way to solve the problem. However, + there are a number of subtle aspects of the solution to + consider--mostly concerning the way in which the problem has been + decomposed. First, the example is structured in a way that tries to + maintain separation between wrapper-specific information and the + declaration of the function itself. The idea here is that you might + structure your interface like this:
++++%typemap(const char *fmt, ...) { + ... +} +%feature("action") traceprintf { + ... +} + +/* Include some header file with traceprintf in it */ +%include "someheader.h" ++Second, careful scrutiny will reveal that the typemaps involving +(...) have nothing whatsoever to do with the libffi library. In + fact, they are generic with respect to the way in which the function is + actually called. This decoupling means that it will be much easier to + consider other library alternatives for making the function call. For + instance, if libffi wasn't supported on a certain platform, you might + be able to use something else instead. You could use conditional + compilation to control this:
++++#ifdef USE_LIBFFI +%feature("action") printf { + ... +} +#endif +#ifdef USE_OTHERFFI +%feature("action") printf { +... +} +#endif ++Finally, even though you might be inclined to just write a + hand-written wrapper for varargs functions, the techniques used in the + previous section have the advantage of being compatible with all other + features of SWIG such as exception handling.
+As a final word, some C programmers seem to have the assumption that + the wrapping of variable length argument functions is an easily solved + problem. However, this section has hopefully dispelled some of these + myths. All things being equal, you are better off avoiding variable + length arguments if you can. If you can't avoid them, please consider + some of the simple solutions first. If you can't live with a simple + solution, proceed with caution. At the very least, make sure you + carefully read the section "A7.3.2 Function Calls" in Kernighan and + Ritchie and make sure you fully understand the parameter passing + conventions used for varargs. Also, be aware of the platform + dependencies and reliability issues that this will introduce. Good + luck.
+
+15 Warning Messages
+ + ++ ++ +15.1 Introduction
+During compilation, SWIG may generate a variety of warning messages. + For example:
++++example.i:16: Warning 501: Overloaded declaration ignored. bar(double) +example.i:15: Warning 501: Previous declaration is bar(int) ++Typically, warning messages indicate non-fatal problems with the + input where the generated wrapper code will probably compile, but it + may not work like you expect.
+15.2 Warning message suppression
+All warning messages have a numeric code that is shown in the + warning message itself. To suppress the printing of a warning message, + a number of techniques can be used. First, you can run SWIG with the +-w command line option. For example:
++++% swig -python -w501 example.i +% swig -python -w501,505,401 example.i ++Alternatively, warnings can be suppressed by inserting a special + preprocessor pragma into the input file:
++++%module example +#pragma SWIG nowarn=501 +#pragma SWIG nowarn=501,505,401 ++Finally, code-generation warnings can be disabled on a declaration + by declaration basis using the %warnfilter directive. For + example:
++++%module example +%warnfilter(501) foo; +... +int foo(int); +int foo(double); // Silently ignored. ++The %warnfilter directive has the same semantics as other + declaration modifiers like %rename, %ignore and +%feature, see the %feature + directive section. For example, if you wanted to suppress a warning + for a method in a class hierarchy, you could do this:
++++%warnfilter(501) Object::foo; +class Object { +public: + int foo(int); + int foo(double); // Silently ignored + ... +}; + +class Derived : public Object { +public: + int foo(int); + int foo(double); // Silently ignored + ... +}; ++Warnings can be suppressed for an entire class by supplying a class + name. For example:
++++%warnfilter(501) Object; + +class Object { +public: + ... // All 501 warnings ignored in class +}; ++There is no option to suppress all SWIG warning messages. The + warning messages are there for a reason---to tell you that something + may be broken in your interface. Ignore the warning messages + at your own peril.
+15.3 Enabling extra warnings
+Some warning messages are disabled by default and are generated only + to provide additional diagnostics. These warnings can be turned on + using the -Wextra option. For example:
++++% swig -Wextra -python example.i ++To selectively turn on extra warning messages, you can use the + directives and options in the previous section--simply add a "+" to all + warning numbers. For example:
++++% swig -w+309,+452 example.i ++or in your interface file use either
++++#pragma SWIG nowarn=+309,+452 ++or
++++%warnfilter(+309,+452) foo; ++Note: selective enabling of warnings with %warnfilter + overrides any global settings you might have made using -w or +#pragma.
+You can of course also enable all warnings and suppress a select + few, for example:
++++% swig -Wextra -w309,452 example.i ++The warnings on the right take precedence over the warnings on the + left, so in the above example -Wextra adds numerous warnings + including 452, but then -w309,452 overrides this and so 452 is + suppressesed.
+If you would like all warnings to appear, regardless of the warning + filters used, then use the -Wall option. The -Wall + option also turns on the extra warnings that -Wextra adds, + however, it is subtely different. When -Wall is used, it also + disables all other warning filters, that is, any warnings suppressed or + added in %warnfilter, #pragma SWIG nowarn or the +-w option.
+15.4 Issuing a warning message
+Warning messages can be issued from an interface file using a number + of directives. The %warn directive is the most simple:
++++%warn "900:This is your last warning!" ++All warning messages are optionally prefixed by the warning number + to use. If you are generating your own warnings, make sure you don't + use numbers defined in the table at the end of this section.
+The %ignorewarn directive is the same as %ignore + except that it issues a warning message whenever a matching declaration + is found. For example:
++++%ignorewarn("362:operator= ignored") operator=; ++Warning messages can be associated with typemaps using the +warning attribute of a typemap declaration. For example:
++++%typemap(in, warning="901:You are really going to regret this usage of $1_type $1_name") blah * { + ... +} ++In this case, the warning message will be printed whenever the + typemap is actually used and the +special variables will be expanded as appropriate, for example:
++++example.i:23: Warning 901: You are really going to regret this usage of blah * self +example.i:24: Warning 901: You are really going to regret this usage of blah * stuff ++15.5 Symbolic symbols
+The swigwarn.swg file that is installed with SWIG contains + symbol constants that could also be used in %warnfilter and +#pragma SWIG nowarn. For example this file contains the following + line:
++++%define SWIGWARN_TYPE_UNDEFINED_CLASS 401 %enddef ++so SWIGWARN_TYPE_UNDEFINED_CLASS could be used instead of + 401, for example:
++++#pragma SWIG nowarn=SWIGWARN_TYPE_UNDEFINED_CLASS ++or
++++%warnfilter(SWIGWARN_TYPE_UNDEFINED_CLASS) Foo; ++15.6 Commentary
+The ability to suppress warning messages is really only provided for + advanced users and is not recommended in normal use. You are advised to + modify your interface to fix the problems highlighted by the warnings + wherever possible instead of suppressing warnings.
+Certain types of SWIG problems are errors. These usually arise due + to parsing errors (bad syntax) or semantic problems for which there is + no obvious recovery. There is no mechanism for suppressing error + messages.
+15.7 Warnings as errors
+Warnings can be handled as errors by using the -Werror + command line option. This will cause SWIG to exit with a non successful + exit code if a warning is encountered.
+15.8 Message output format
+The output format for both warnings and errors can be selected for + integration with your favourite IDE/editor. Editors and IDEs can + usually parse error messages and if in the appropriate format will + easily take you directly to the source of the error. The standard + format is used by default except on Windows where the Microsoft format + is used by default. These can be overridden using command line options, + for example:
++++$ swig -python -Fstandard example.i +example.i:4: Syntax error in input(1). +$ swig -python -Fmicrosoft example.i +example.i(4) : Syntax error in input(1). ++15.9 Warning number reference
+15.9.1 Deprecated features (100-199)
++
+- 101. Deprecated %extern directive.
+- 102. Deprecated %val directive.
+- 103. Deprecated %out directive.
+- 104. Deprecated %disabledoc directive.
+- 105. Deprecated %enabledoc directive.
+- 106. Deprecated %doconly directive.
+- 107. Deprecated %style directive.
+- 108. Deprecated %localstyle directive.
+- 109. Deprecated %title directive.
+- 110. Deprecated %section directive.
+- 111. Deprecated %subsection directive.
+- 112. Deprecated %subsubsection directive.
+- 113. Deprecated %addmethods directive.
+- 114. Deprecated %readonly directive.
+- 115. Deprecated %readwrite directive.
+- 116. Deprecated %except directive.
+- 117. Deprecated %new directive.
+- 118. Deprecated %typemap(except).
+- 119. Deprecated %typemap(ignore).
+- 120. Deprecated command line option (-runtime, -noruntime).
+- 121. Deprecated %name directive.
+- 126. The 'nestedworkaround' feature is deprecated.
+15.9.2 Preprocessor (200-299)
++
+- 201. Unable to find filename.
+- 202. Could not evaluate expression expr.
+- 203. Both includeall and importall are defined: using includeall.
+- 204. CPP #warning, "warning".
+- 205. CPP #error, "error".
+- 206. Unexpected tokens after #directive directive.
+15.9.3 C/C++ Parser (300-399)
++
+- 301. class keyword used, but not in C++ mode.
+- 302. Identifier 'name' redefined (ignored).
+- 303. %extend defined for an undeclared class 'name +'.
+- 304. Unsupported constant value (ignored).
+- 305. Bad constant value (ignored).
+- 306. 'identifier' is private in this context.
+- 307. Can't set default argument value (ignored)
+- 308. Namespace alias 'name' not allowed here. Assuming ' +name'
+- 309. [private | protected] inheritance ignored.
+- 310. Template 'name' was already wrapped as 'name' + (ignored)
+- 312. Unnamed nested class not currently supported (ignored).
+- 313. Unrecognized extern type "name" (ignored).
+- 314. 'identifier' is a lang keyword.
+- 315. Nothing known about 'identifier'.
+- 316. Repeated %module directive.
+- 317. Specialization of non-template 'name'.
+- 318. Instantiation of template 'name' is ambiguous, + instantiation templ used, instantiation templ + ignored.
+- 319. No access specifier given for base class name + (ignored).
+- 320. Explicit template instantiation ignored.
+- 321. identifier conflicts with a built-in name.
+- 322. Redundant redeclaration of 'name'.
+- 323. Recursive scope inheritance of 'name'.
+- 324. Named nested template instantiations not supported. Processing + as if no name was given to %template().
+- 325. Nested kind not currently supported (name + ignored).
+- 326. Deprecated %extend name used - the kind name 'name +' should be used instead of the typedef name 'name'.
+- 350. operator new ignored.
+- 351. operator delete ignored.
+- 352. operator+ ignored.
+- 353. operator- ignored.
+- 354. operator* ignored.
+- 355. operator/ ignored.
+- 356. operator% ignored.
+- 357. operator^ ignored.
+- 358. operator& ignored.
+- 359. operator| ignored.
+- 360. operator~ ignored.
+- 361. operator! ignored.
+- 362. operator= ignored.
+- 363. operator< ignored.
+- 364. operator> ignored.
+- 365. operator+= ignored.
+- 366. operator-= ignored.
+- 367. operator*= ignored.
+- 368. operator/= ignored.
+- 369. operator%= ignored.
+- 370. operator^= ignored.
+- 371. operator&= ignored.
+- 372. operator|= ignored.
+- 373. operator<< ignored.
+- 374. operator>>ignored.
+- 375. operator<<= ignored.
+- 376. operator>>= ignored.
+- 377. operator== ignored.
+- 378. operator!= ignored.
+- 379. operator<= ignored.
+- 380. operator>= ignored.
+- 381. operator&& ignored.
+- 382. operator|| ignored.
+- 383. operator++ ignored.
+- 384. operator-- ignored.
+- 385. operator, ignored.
+- 386. operator-<* ignored.
+- 387. operator-< ignored.
+- 388. operator() ignored.
+- 389. operator[] ignored.
+- 390. operator+ ignored (unary).
+- 391. operator- ignored (unary).
+- 392. operator* ignored (unary).
+- 393. operator& ignored (unary).
+- 394. operator new[] ignored.
+- 395. operator delete[] ignored.
+15.9.4 Types and typemaps (400-499)
++
+- 401. Nothing known about class 'name'. Ignored.
+- 402. Base class 'name' is incomplete.
+- 403. Class 'name' might be abstract.
+- 450. Deprecated typemap feature ($source/$target).
+- 451. Setting const char * variable may leak memory.
+- 452. Reserved
+- 453. Can't apply (pattern). No typemaps are defined.
+- 460. Unable to use type type as a function argument.
+- 461. Unable to use return type type in function name +.
+- 462. Unable to set variable of type type.
+- 463. Unable to read variable of type type.
+- 464. Unsupported constant value.
+- 465. Unable to handle type type.
+- 466. Unsupported variable type type.
+- 467. Overloaded declaration not supported (incomplete type + checking rule - no precedence level in typecheck typemap for 'type +')
+- 468. No 'throw' typemap defined for exception type type
+- 469. No or improper directorin typemap defined for type
+- 470. Thread/reentrant unsafe wrapping, consider returning by value + instead.
+- 471. Unable to use return type type in director method
+- 474. Method method usage of the optimal attribute ignored + in the out typemap as the following cannot be used to generate optimal + code: code
+- 475. Multiple calls to method might be generated due to + optimal attribute usage in the out typemap.
+- 476. Initialization using std::initializer_list.
+- 477. No directorthrows typemap defined for type
+15.9.5 Code generation (500-599)
++
+- 501. Overloaded declaration ignored. decl. Previous + declaration is decl.
+- 502. Overloaded constructor ignored. decl. Previous + declaration is decl.
+- 503. Can't wrap 'identifier' unless renamed to a valid + identifier.
+- 504. Function name must have a return type. Ignored.
+- 505. Variable length arguments discarded.
+- 506. Can't wrap varargs with keyword arguments enabled.
+- 507. Adding native function name not supported (ignored).
+- 508. Declaration of 'name' shadows declaration accessible + via operator->(), previous declaration of'declaration'.
+- 509. Overloaded method declaration effectively ignored, as + it is shadowed by declaration.
+- 510. Friend function 'name' ignored.
+- 511. Can't use keyword arguments with overloaded functions.
+- 512. Overloaded method declaration ignored, using non-const + method declaration instead.
+- 513. Can't generate wrappers for unnamed struct/class.
+- 514.
+- 515.
+- 516. Overloaded method declaration ignored, using + declaration instead.
+- 517.
+- 518. Portability warning: File file1 will be overwritten by + file2 on case insensitive filesystems such as Windows' FAT32 and + NTFS unless the class/module name is renamed.
+- 519. %template() contains no name. Template method ignored: + declaration
+- 520. Base/Derived class 'classname1' of ' +classname2' is not similarly marked as a smart pointer.
+- 521. Illegal destructor name name. Ignored.
+- 522. Use of an illegal constructor name 'name' in %extend + is deprecated, the constructor name should be 'name'.
+- 523. Use of an illegal destructor name 'name' in %extend is + deprecated, the destructor name should be 'name'.
+15.9.6 Language module specific (700-899) +
++
+- 801. Wrong name (corrected to 'name'). (Ruby).
++
+- 810. No jni typemap defined for type (Java).
+- 811. No jtype typemap defined for type (Java).
+- 812. No jstype typemap defined for type (Java).
+- 813. Warning for classname, base baseclass + ignored. Multiple inheritance is not supported in Java. (Java).
+- 814.
+- 815. No javafinalize typemap defined for type (Java).
+- 816. No javabody typemap defined for type (Java).
+- 817. No javaout typemap defined for type (Java).
+- 818. No javain typemap defined for type (Java).
+- 819. No javadirectorin typemap defined for type (Java).
+- 820. No javadirectorout typemap defined for type (Java).
+- 821.
+- 822. Covariant return types not supported in Java. Proxy method will + return basetype (Java).
+- 823. No javaconstruct typemap defined for type (Java).
+- 824. Missing JNI descriptor in directorin typemap defined for + type (Java).
+- 825. "directorconnect" attribute missing in type + "javaconstruct" typemap. (Java).
+- 826. The nspace feature is used on 'type' without -package. + The generated code may not compile as Java does not support types + declared in a named package accessing types declared in an unnamed + package. (Java).
++
+- 830. No ctype typemap defined for type (C#).
+- 831. No cstype typemap defined for type (C#).
+- 832. No cswtype typemap defined for type (C#).
+- 833. Warning for classname, base baseclass + ignored. Multiple inheritance is not supported in C#. (C#).
+- 834.
+- 835. No csfinalize typemap defined for type (C#).
+- 836. No csbody typemap defined for type (C#).
+- 837. No csout typemap defined for type (C#).
+- 838. No csin typemap defined for type (C#).
+- 839.
+- 840.
+- 841.
+- 842. Covariant return types not supported in C#. Proxy method will + return basetype (C#).
+- 843. No csconstruct typemap defined for type (C#).
+- 844. C# exception may not be thrown - no $excode or excode attribute + in typemap typemap. (C#).
+- 845. Unmanaged code contains a call to a + SWIG_CSharpSetPendingException method and C# code does not handle + pending exceptions via the canthrow attribute. (C#).
++
+- 870. Warning for classname: Base baseclass + ignored. Multiple inheritance is not supported in PHP. (Php).
+- 871. Unrecognized pragma pragma. (Php).
+15.9.7 User defined (900-999)
+These numbers can be used by your own application.
+15.10 History
+The ability to control warning messages was first added to + SWIG-1.3.12.
+
+16 Working with Modules
+ + ++ ++ +16.1 Modules Introduction
+Each invocation of SWIG requires a module name to be specified. The + module name is used to name the resulting target language extension + module. Exactly what this means and what the name is used for depends + on the target language, for example the name can define a target + language namespace or merely be a useful name for naming files or + helper classes. Essentially, a module comprises target language + wrappers for a chosen collection of global variables/functions, + structs/classes and other C/C++ types.
+The module name can be supplied in one of two ways. The first is to + specify it with the special %module directive. This directive + must appear at the beginning of the interface file. The general form of + this directive is:
++++%module(option1="value1",option2="value2",...) modulename ++where the modulename is mandatory and the options add one or more + optional additional features. Typically no options are specified, for + example:
++++%module mymodule ++The second way to specify the module name is with the -module + command line option, for example -module mymodule. If the + module name is supplied on the command line, it overrides the name + specified by the %module directive.
+When first working with SWIG, users commonly start by creating a + single module. That is, you might define a single SWIG interface that + wraps some set of C/C++ code. You then compile all of the generated + wrapper code together and use it. For large applications, however, this + approach is problematic---the size of the generated wrapper code can be + rather large. Moreover, it is probably easier to manage the target + language interface when it is broken up into smaller pieces.
+This chapter describes the problem of using SWIG in programs where + you want to create a collection of modules. Each module in the + collection is created via separate invocations of SWIG.
+16.2 Basics
+The basic usage case with multiple modules is when modules do not + have cross-references (ie. when wrapping multiple independent C APIs). + In that case, swig input files should just work out of the box - you + simply create multiple wrapper .cxx files, link them into your + application, and insert/load each in the scripting language runtime as + you would do for the single module case.
+A bit more complex is the case in which modules need to share + information. For example, when one module extends the class of another + by deriving from it:
+++// File: base.h +class base { +public: + int foo(); +}; ++++// File: base_module.i +%module base_module + +%{ +#include "base.h" +%} +%include "base.h" +++++// File: derived_module.i +%module derived_module + +%import "base_module.i" + +%inline %{ +class derived : public base { +public: + int bar(); +}; +%} ++To create the wrapper properly, module derived_module needs + to know about the base class and that its interface is covered + in another module. The line %import "base_module.i" lets SWIG + know exactly that. Often the .h file is passed to %import + instead of the .i, which unfortunately doesn't work for all + language modules. For example, Python requires the name of module that + the base class exists in so that the proxy classes can fully inherit + the base class's methods. Typically you will get a warning when the + module name is missing, eg:
++++derived_module.i:8: Warning 401: Base class 'base' ignored - unknown module name for base. Either +import +the appropriate module interface file or specify the name of the module in the %import directive. ++It is sometimes desirable to import the header file rather than the + interface file and overcome the above warning. For example in the case + of the imported interface being quite large, it may be desirable to + simplify matters and just import a small header file of dependent + types. This can be done by specifying the optional module + attribute in the %import directive. The derived_module.i + file shown above could be replaced with the following:
+++// File: derived_module.i +%module derived_module + +%import(module="base_module") "base.h" + +%inline %{ +class derived : public base { +public: + int bar(); +}; ++Note that "base_module" is the module name and is the same as that + specified in %module in base_module.i as well as the +%import in derived_module.i.
+Another issue to beware of is that multiple dependent wrappers + should not be linked/loaded in parallel from multiple threads as SWIG + provides no locking - for more on that issue, read on.
+16.3 The SWIG runtime code
+Many of SWIG's target languages generate a set of functions commonly + known as the "SWIG runtime." These functions are primarily related to + the runtime type system which checks pointer types and performs other + tasks such as proper casting of pointer values in C++. As a general + rule, the statically typed target languages, such as Java, use the + language's built in static type checking and have no need for a SWIG + runtime. All the dynamically typed / interpreted languages rely on the + SWIG runtime.
+The runtime functions are private to each SWIG-generated module. + That is, the runtime functions are declared with "static" linkage and + are visible only to the wrapper functions defined in that module. The + only problem with this approach is that when more than one SWIG module + is used in the same application, those modules often need to share type + information. This is especially true for C++ programs where SWIG must + collect and share information about inheritance relationships that + cross module boundaries.
+To solve the problem of sharing information across modules, a + pointer to the type information is stored in a global variable in the + target language namespace. During module initialization, type + information is loaded into the global data structure of type + information from all modules.
+There are a few trade offs with this approach. This type information + is global across all SWIG modules loaded, and can cause type conflicts + between modules that were not designed to work together. To solve this + approach, the SWIG runtime code uses a define SWIG_TYPE_TABLE to + provide a unique type table. This behavior can be enabled when + compiling the generated _wrap.cxx or _wrap.c file by adding + -DSWIG_TYPE_TABLE=myprojectname to the command line argument.
+Then, only modules compiled with SWIG_TYPE_TABLE set to + myprojectname will share type information. So if your project has three + modules, all three should be compiled with + -DSWIG_TYPE_TABLE=myprojectname, and then these three modules will + share type information. But any other project's types will not + interfere or clash with the types in your module.
+Another issue relating to the global type table is thread safety. If + two modules try and load at the same time, the type information can + become corrupt. SWIG currently does not provide any locking, and if you + use threads, you must make sure that modules are loaded serially. Be + careful if you use threads and the automatic module loading that some + scripting languages provide. One solution is to load all modules before + spawning any threads, or use SWIG_TYPE_TABLE to separate type tables so + they do not clash with each other.
+Lastly, SWIG uses a #define SWIG_RUNTIME_VERSION, located in + Lib/swigrun.swg and near the top of every generated module. This number + gets incremented when the data structures change, so that SWIG modules + generated with different versions can peacefully coexist. So the type + structures are separated by the (SWIG_TYPE_TABLE, SWIG_RUNTIME_VERSION) + pair, where by default SWIG_TYPE_TABLE is empty. Only modules compiled + with the same pair will share type information.
+16.4 External access to the + runtime
+As described in The run-time + type checker, the functions SWIG_TypeQuery, +SWIG_NewPointerObj, and others sometimes need to be called. Calling + these functions from a typemap is supported, since the typemap code is + embedded into the _wrap.c file, which has those declarations + available. If you need to call the SWIG run-time functions from another + C file, there is one header you need to include. To generate the header + that needs to be included, SWIG can be run in a different mode via +-external-runtime to generate the run-time instead of the normal + mode of processing an input interface file. For example:
+++$ swig -python -external-runtime <filename> ++The filename argument is optional and if it is not passed, then the + default filename will be something like swigpyrun.h, depending + on the language. This header file should be treated like any of the + other _wrap.c output files, and should be regenerated when the _wrap + files are. After including this header, your code will be able to call +SWIG_TypeQuery, SWIG_NewPointerObj, SWIG_ConvertPtr + and others. The exact argument parameters for these functions might + differ between language modules; please check the language module + chapters for more information.
+Inside this header the functions are declared static and are included + inline into the file, and thus the file does not need to be linked + against any SWIG libraries or code (you might still need to link + against the language libraries like libpython-2.3). Data is shared + between this file and the _wrap.c files through a global variable in + the scripting language. It is also possible to copy this header file + along with the generated wrapper files into your own package, so that + you can distribute a package that can be compiled without SWIG + installed (this works because the header file is self-contained, and + does not need to link with anything).
+This header will also use the -DSWIG_TYPE_TABLE described above, so + when compiling any code which includes the generated header file should + define the SWIG_TYPE_TABLE to be the same as the module whose types you + are trying to access.
+16.5 A word of caution about static libraries +
+When working with multiple SWIG modules, you should take care not to + use static libraries. For example, if you have a static library +libfoo.a and you link a collection of SWIG modules with that + library, each module will get its own private copy of the library code + inserted into it. This is very often NOT what you want and it + can lead to unexpected or bizarre program behavior. When working with + dynamically loadable modules, you should try to work exclusively with + shared libraries.
+16.6 References
+Due to the complexity of working with shared libraries and multiple + modules, it might be a good idea to consult an outside reference. John + Levine's "Linkers and Loaders" is highly recommended.
+16.7 Reducing the wrapper file size
+Using multiple modules with the %import directive is the + most common approach to modularising large projects. In this way a + number of different wrapper files can be generated, thereby avoiding + the generation of a single large wrapper file. There are a couple of + alternative solutions for reducing the size of a wrapper file through + the use of command line options and features.
+-fcompact +
+
This command line option will compact the size of the wrapper file + without changing the code generated into the wrapper file. It simply + removes blank lines and joins lines of code together. This is useful + for compilers that have a maximum file size that can be handled.-fvirtual +
+
This command line option will remove the generation of superfluous + virtual method wrappers. Consider the following inheritance hierarchy:+++struct Base { + virtual void method(); + ... +}; + +struct Derived : Base { + virtual void method(); + ... +}; ++Normally wrappers are generated for both methods, whereas this + command line option will suppress the generation of a wrapper for +Derived::method. Normal polymorphic behaviour remains as +Derived::method will still be called should you have a Derived + instance and call the wrapper for Base::method.
+%feature("compactdefaultargs") +
+
This feature can reduce the number of wrapper methods when wrapping + methods with default arguments. The section on +default arguments discusses the feature and its limitations.
+17 Using SWIG with ccache - ccache-swig(1) manpage +
+ + ++ ++ + +17.1 NAME
+ccache-swig - a fast compiler cache
+ +17.2 SYNOPSIS
+ccache-swig [OPTION]
+ccache-swig <compiler> [COMPILER OPTIONS]
+<compiler> [COMPILER OPTIONS]
+ +17.3 DESCRIPTION
+ccache-swig is a compiler cache. It speeds up re-compilation of + C/C++/SWIG code by caching previous compiles and detecting when the + same compile is being done again. ccache-swig is ccache plus support + for SWIG. ccache and ccache-swig are used interchangeably in this + document.
+ +17.4 OPTIONS SUMMARY
+Here is a summary of the options to ccache-swig.
+ ++ +-s show statistics summary +-z zero statistics +-c run a cache cleanup +-C clear the cache completely +-F <n> set maximum files in cache +-M <n> set maximum size of cache (use G, M or K) +-h this help page +-V print version number + ++ +17.5 OPTIONS
+These options only apply when you invoke ccache as "ccache-swig". + When invoked as a compiler none of these options apply. In that case + your normal compiler options apply and you should refer to your + compilers documentation.
+ ++
+ ++
- -h
+- Print a options summary page + + +
+- -s
+- Print the current statistics summary for the cache. The statistics + are stored spread across the subdirectories of the cache. Using + "ccache-swig -s" adds up the statistics across all subdirectories and + prints the totals. + + +
+- -z
+- Zero the cache statistics. + + +
+- -V
+- Print the ccache version number + + +
+- -c
+- Clean the cache and re-calculate the cache file count and size + totals. Normally the -c option should not be necessary as ccache keeps + the cache below the specified limits at runtime and keeps statistics up + to date on each compile. This option is mostly useful if you manually + modify the cache contents or believe that the cache size statistics may + be inaccurate. + + +
+- -C
+- Clear the entire cache, removing all cached files. + + +
+- -F <maxfiles>
+- This sets the maximum number of files allowed in the cache. The + value is stored inside the cache directory and applies to all future + compiles. Due to the way the value is stored the actual value used is + always rounded down to the nearest multiple of 16. + + +
+- -M <maxsize>
+- This sets the maximum cache size. You can specify a value in + gigabytes, megabytes or kilobytes by appending a G, M or K to the + value. The default is gigabytes. The actual value stored is rounded + down to the nearest multiple of 16 kilobytes. + +
+ +17.6 INSTALLATION
+There are two ways to use ccache. You can either prefix your compile + commands with "ccache-swig" or you can create a symbolic link between + ccache-swig and the names of your compilers. The first method is most + convenient if you just want to try out ccache or wish to use it for + some specific projects. The second method is most useful for when you + wish to use ccache for all your compiles.
+To install for usage by the first method just copy ccache-swig to + somewhere in your path.
+To install for the second method do something like this:
++ + cp ccache-swig /usr/local/bin/ + ln -s /usr/local/bin/ccache-swig /usr/local/bin/gcc + ln -s /usr/local/bin/ccache-swig /usr/local/bin/g++ + ln -s /usr/local/bin/ccache-swig /usr/local/bin/cc + ln -s /usr/local/bin/ccache-swig /usr/local/bin/swig + ++ This will work as long as /usr/local/bin comes before the path to gcc + (which is usually in /usr/bin). After installing you may wish to run + "which gcc" to make sure that the correct link is being used. +Note! Do not use a hard link, use a symbolic link. A hardlink will + cause "interesting" problems.
+ +17.7 EXTRA OPTIONS
+When run as a compiler front end ccache usually just takes the same + command line options as the compiler you are using. The only exception + to this is the option '--ccache-skip'. That option can be used to tell + ccache that the next option is definitely not a input filename, and + should be passed along to the compiler as-is.
+The reason this can be important is that ccache does need to parse + the command line and determine what is an input filename and what is a + compiler option, as it needs the input filename to determine the name + of the resulting object file (among other things). The heuristic ccache + uses in this parse is that any string on the command line that exists + as a file is treated as an input file name (usually a C file). By using + --ccache-skip you can force an option to not be treated as an input + file name and instead be passed along to the compiler as a command line + option.
+ +17.8 ENVIRONMENT VARIABLES
+ccache uses a number of environment variables to control operation. + In most cases you won't need any of these as the defaults will be fine.
+ ++ +
-+
- CCACHE_DIR
+- the CCACHE_DIR environment variable specifies where ccache will + keep its cached compiler output. The default is "$HOME/.ccache". + + +
+- CCACHE_TEMPDIR
+- the CCACHE_TEMPDIR environment variable specifies where ccache will + put temporary files. The default is the same as CCACHE_DIR. Note that + the CCACHE_TEMPDIR path must be on the same filesystem as the + CCACHE_DIR path, so that renames of files between the two directories + can work. + + +
+- CCACHE_LOGFILE
+- If you set the CCACHE_LOGFILE environment variable then ccache will + write some log information on cache hits and misses in that file. This + is useful for tracking down problems. + + +
+- CCACHE_VERBOSE
+- If you set the CCACHE_VERBOSE environment variable then ccache will + display on stdout all the compiler invocations that it makes. This can + useful for debugging unexpected problems. + + +
+- CCACHE_PATH
+- You can optionally set CCACHE_PATH to a colon separated path where + ccache will look for the real compilers. If you don't do this then + ccache will look for the first executable matching the compiler name in + the normal PATH that isn't a symbolic link to ccache itself. + + +
+- CCACHE_CC
- You can optionally set CCACHE_CC to force the name of the compiler to use. If you don't do this then ccache works it out from the command line. @@ -19081,7 +20703,7 @@ default arguments discusses the feature and its limitations.
16.9 CACHE SIZE MANAGEMENT
+17.9 CACHE SIZE MANAGEMENT
By default ccache has a one gigabyte limit on the cache size and no maximum number of files. You can set a different limit using the "ccache -M" and "ccache -F" options, which set the size and number of @@ -19090,14 +20712,14 @@ default arguments discusses the feature and its limitations.
below the numbers you specified in order to avoid doing the cache clean operation too often. -16.10 CACHE COMPRESSION
+17.10 CACHE COMPRESSION
By default on most platforms ccache will compress all files it puts into the cache using the zlib compression. While this involves a negligible performance slowdown, it significantly increases the number of files that fit in the cache. You can turn off compression setting the CCACHE_NOCOMPRESS environment variable.
-16.11 HOW IT WORKS
+17.11 HOW IT WORKS
The basic idea is to detect when you are compiling exactly the same code a 2nd time and use the previously compiled output. You detect that it is the same code by forming a hash of:
@@ -19117,7 +20739,7 @@ default arguments discusses the feature and its limitations. discover a case where ccache changes the output of your compiler then please let me know. -16.12 USING CCACHE WITH DISTCC
+17.12 USING CCACHE WITH DISTCC
distcc is a very useful program for distributing compilation across a range of compiler servers. It is often useful to combine distcc with ccache, so that compiles that are done are sped up by distcc, but that @@ -19127,7 +20749,7 @@ default arguments discusses the feature and its limitations.
'distcc' and ccache will prefix the command line used with the compiler with the command 'distcc'. -16.13 SHARING A CACHE
+17.13 SHARING A CACHE
A group of developers can increase the cache hit rate by sharing a cache directory. The hard links however cause unwanted side effects, as all links to a cached file share the file's modification timestamp. @@ -19154,7 +20776,7 @@ default arguments discusses the feature and its limitations.
users with versions of ccache that do not support compression. -16.14 HISTORY
+17.14 HISTORY
ccache was inspired by the compilercache shell script script written by Erik Thiele and I would like to thank him for an excellent piece of work. See @@ -19165,7 +20787,7 @@ http://www.erikyyy.de/compilercache/ for the Erik's scripts. compiler cache and I wanted to remove some of the limitations of the shell-script version.
-16.15 DIFFERENCES FROM COMPILERCACHE
+17.15 DIFFERENCES FROM COMPILERCACHE
The biggest differences between Erik's compilercache script and ccache are:
@@ -19180,7 +20802,7 @@ http://www.erikyyy.de/compilercache/ for the Erik's scripts.
-- ccache avoids a double call to cpp on a cache miss
16.16 CREDITS
+17.16 CREDITS
Thanks to the following people for their contributions to ccache
-
- Erik Thiele for the original compilercache script
@@ -19189,7 +20811,7 @@ http://www.erikyyy.de/compilercache/ for the Erik's scripts.- Paul Russell for many suggestions and the debian packaging
16.17 AUTHOR
+17.17 AUTHOR
ccache was written by Andrew Tridgell http://samba.org/~tridge/. ccache was adapted to create ccache-swig for use with SWIG by William Fulton.
@@ -19200,9 +20822,7 @@ http://www.swig.org/mail.html later. Please see the file COPYING for license details.
- - -17 SWIG and Allegro Common Lisp
+18 SWIG and Allegro Common Lisp
@@ -19332,8 +20952,8 @@ http://www.swig.org/mail.html interfaces (UFFI or CFFI, for example). Such work can only benefit the lisp community, and we would not be unhappy to see some enterprising folk use this work to add to it. --17.1 Basics
-17.1.1 Running SWIG
+18.1 Basics
+18.1.1 Running SWIG
If you're reading this, you must have some library you need to generate an interface for. In order for SWIG to do this work, however, it needs a bit of information about how it should go about creating @@ -19513,7 +21133,7 @@ EXPORT int ACL___fact__SWIG_1 (int larg1) { lisp, you will also need to link in the Allegro shared library. The library you create from the C++ wrapper will be what you then load into Allegro CL.
-17.1.2 Command Line Options
+18.1.2 Command Line Options
There are three Allegro CL specific command-line option:
@@ -19521,27 +21141,27 @@ swig -allegrocl [ options ] filename -identifier-converter [name] - Binds the variable swig:*swig-identifier-convert* in the generated .cl file to name. - This function is used to generate symbols - for the lisp side of the interface. + This function is used to generate symbols + for the lisp side of the interface. -cwrap - [default] Generate a .cxx file containing C wrapper function when wrapping C code. The interface generated is similar to what is - done for C++ code. + done for C++ code. -nocwrap - Explicitly turn off generation of .cxx wrappers for C code. Reasonable for modules with simple interfaces. Can not handle all legal enum - and constant constructs, or take advantage of SWIG customization features. + and constant constructs, or take advantage of SWIG customization features. -isolate - With this command-line argument, all lisp helper functions are defined in a unique package named swig.<module-name> rather than - swig. This prevents conflicts when the module is - intended to be used with other swig generated interfaces that may, - for instance, make use of different identifier converters. + swig. This prevents conflicts when the module is + intended to be used with other swig generated interfaces that may, + for instance, make use of different identifier converters.See Section 17.5 Identifier converter functions for more details.
-17.1.3 Inserting user code into - generated files
+18.1.3 Inserting user code into generated + files
It is often necessary to include user-defined code into the automatically generated interface files. For example, when building a C++ interface, example_wrap.cxx will likely not compile unless you add @@ -19569,11 +21189,11 @@ int fact(int n);
Note that the block %{ ... %} is effectively a shortcut for %insert("header") %{ ... %}.
-17.2 Wrapping Overview
+18.2 Wrapping Overview
New users to SWIG are encouraged to read SWIG Basics , and SWIG and C++, for those interested in generating an interface to C++.
-17.2.1 Function Wrapping
+18.2.1 Function Wrapping
Writing lisp code that directly invokes functions at the foreign function interface level can be cumbersome. Data must often be translated between lisp and foreign types, data extracted from objects, @@ -19591,7 +21211,7 @@ int fact(int n); | Foreign Code | What we're generating an interface to. |______________| | - | + | _______v______ | | (foreign side) | Wrapper code | extern "C" wrappers calling C++ @@ -19603,28 +21223,28 @@ int fact(int n); | FFI Layer | Low level lisp interface. ff:def-foreign-call, |______________| ff:def-foreign-variable | - +---------------------------- + +---------------------------- _______v______ _______v______ | | | | (lisp side) | Defuns | | Defmethods | wrapper for overloaded |______________| |______________| functions or those with (lisp side) | defaulted arguments - Wrapper for non-overloaded | - functions and methods _______v______ - | | (lisp side) - | Defuns | dispatch function - |______________| to overloads based - on arity + Wrapper for non-overloaded | + functions and methods _______v______ + | | (lisp side) + | Defuns | dispatch function + |______________| to overloads based + on arity
17.2.2 Foreign Wrappers
+18.2.2 Foreign Wrappers
These wrappers are as generated by SWIG default. The types of function parameters can be transformed in place using the CTYPE typemap. This is use for converting pass-by-value parameters to pass-by-reference where necessary. All wrapper parameters are then bound to local variables for possible transformation of values (see LIN typemap). Return values can be transformed via the OUT typemap.
-17.2.3 FFI Wrappers
+18.2.3 FFI Wrappers
These are the generated ff:def-foreign-call forms. No typemaps are applicable to this layer, but the %ffargs directive is available for use in .i files, to specify which keyword arguments @@ -19692,7 +21312,7 @@ char *xxx();
Is the only default value specified in allegrocl.swg to force the muffling of warnings about automatic string conversion when defining ff:def-foreign-call's.
-17.2.4 Non-overloaded Defuns
+18.2.4 Non-overloaded Defuns
These are simple defuns. There is no typechecking of arguments. Parameters are bound to local variables for possible transformation of values, such as pulling values out of instance slots or allocating @@ -19700,7 +21320,7 @@ char *xxx(); These arguments are then passed to the foreign-call (where typechecking may occur). The return value from this function can be manipulated via the lout typemap.
-17.2.5 Overloaded Defuns
+18.2.5 Overloaded Defuns
In the case of overloaded functions, mulitple layers are generated. First, all the overloads for a given name are separated out into groups based on arity, and are wrapped in defmethods. Each method calls a @@ -19710,8 +21330,8 @@ char *xxx(); appropriate generic-function based on arity. This provides a single functional interface to all overloads. The return value from this function can be manipulated via the lout typemap.
-17.2.6 What about constant and variable - access?
+18.2.6 What about constant and variable + access?
Along with the described functional layering, when creating a .cxx wrapper, this module will generate getter and--if not immutable--setter, functions for variables and constants. If the @@ -19719,7 +21339,7 @@ char *xxx(); ff:def-foreign-variable forms will be generated for accessing constants and global variables. These, along with the defuns listed above are the intended API for calling into the foreign module.
-17.2.7 Object Wrapping
+18.2.7 Object Wrapping
All non-primitive types (Classes, structs, unions, and typedefs involving same) have a corresponding foreign-type defined on the lisp side via ff:def-foreign-type.
@@ -19733,10 +21353,10 @@ ff:def-foreign-variable forms will be generated for accessing legally be passed and the pointer to the C++ object automatically extracted. This is a natural feature of Allegro's foreign function interface. -17.3 Wrapping Details
+18.3 Wrapping Details
In this section is described how particular C/C++ constructs are translated into lisp.
-17.3.1 Namespaces
+18.3.1 Namespaces
C++ namespaces are translated into Lisp packages by SWIG. The Global namespace is mapped to a package named by the %module directive or the -module command-line argument. Further @@ -19797,9 +21417,9 @@ namespace car { toplevel modules package. This may lead to confusion if, for example, the current package is foo.car.tires and you attempt to use a common-lisp function such as (car '(1 2 3).
-17.3.2 Constants
+18.3.2 Constants
Constants, as declared by the preprocessor #define macro or SWIG -%constant directive, are included in SWIGs parse tree when it can +%constant directive, are included in SWIG's parse tree when it can be determined that they are, or could be reduced to, a literal value. Such values are translated into defconstant forms in the generated lisp wrapper when the -nocwrap command-line options is used. Else, wrapper @@ -19843,7 +21463,7 @@ namespace car {
Users are cautioned to get to know their constants before use, or not use the -nocwrap command-line option.
-17.3.3 Variables
+18.3.3 Variables
For C wrapping, a def-foreign-variable call is generated for access to global variables.
When wrapping C++ code, both global and member variables, getter @@ -19906,11 +21526,11 @@ globalvar> (globalvar.nnn::glob_float) 3.0
17.3.4 Enumerations
+18.3.4 Enumerations
In C, an enumeration value is an integer value, while in C++ an enumeration value is implicitly convertible to an integer value, but - can also be distinguished by it's enum type. For each enum declaration - a def-foreign-type is generated, assigning the enum a default type of + can also be distinguished by its enum type. For each enum declaration a + def-foreign-type is generated, assigning the enum a default type of :int. Users may adjust the foreign type of enums via SWIG typemaps .
Enum values are a bit trickier as they can be initialized using any @@ -19920,11 +21540,11 @@ globalvar> (globalvar.nnn::glob_float) being necessary to probe into foreign space to retrieve enum values. When generating a .cxx wrapper file, a more general solution is employed. A wrapper variable is created in the module_wrap.cxx file, - and a ff:def-foreign-variable call is generated to retrieve it's value + and a ff:def-foreign-variable call is generated to retrieve its value into lisp.
For example, the following header file
enum.h:@@ -19967,7 +21587,7 @@ EXPORT const int ACL_ENUM___FOO3__SWIG_0 = FOO3;-enum COL { RED, GREEN, BLUE }; +enum COL { RED, GREEN, BLUE }; enum FOO { FOO1 = 10, FOO2, FOO3 };17.3.5 Arrays
+18.3.5 Arrays
One limitation in the Allegro CL foreign-types module, is that, without macrology, expressions may not be used to specify the dimensions of an array declaration. This is not a horrible drawback @@ -20103,9 +21723,9 @@ namespace BAR { (make-instance 'ff:foreign-pointer :foreign-address (swig-ff-call)))
17.3.6 Classes and Structs and Unions - (oh my!)
-17.3.6.1 CLOS wrapping of
+18.3.6 Classes and Structs and Unions (oh + my!)
+18.3.6.1 CLOS wrapping of
Classes, unions, and structs are all treated the same way by the interface generator. For any of these objects, a def-foreign-type and a defclass form are generated. For every function that returns an object @@ -20114,14 +21734,14 @@ namespace BAR { returned in an instance of the appropriate class. This makes it much easier to write and debug code than if pointers were passed around as a jumble of integer values.
-17.3.6.2 CLOS Inheritance
+18.3.6.2 CLOS Inheritance
The CLOS class schema generated by the interface mirrors the inheritance of the classes in foreign code, with the ff:foreign-pointer class at its root. ff:foreign-pointer is a thin wrapper for pointers - that is made available by the foreign function interface. It's key + that is made available by the foreign function interface. Its key benefit is that it may be passed as an argument to any ff:def-foreign-call that is expecting a pointer as the parameter.
-17.3.6.3 Member fields and functions
+18.3.6.3 Member fields and functions
All public fields will have accessor getter/setter functions generated for them, as appropriate. All public member functions will have wrapper functions generated.
@@ -20129,8 +21749,8 @@ namespace BAR { private or protected), because the C++ compiler won't allow the wrapper functions to access such fields. Likewise, the interface does nothing for friend directives, -17.3.6.4 Why not directly access C++ - classes using foreign types?
+18.3.6.4 Why not directly access C++ + classes using foreign types?
The def-foreign-type generated by the SWIG interface is currently incomplete. We can reliably generate the object layout of simple structs and unions; they can be allocated via ff:allocate-fobject, and @@ -20142,21 +21762,21 @@ private or protected), because the C++ compiler won't result, it is recommended that users of any generated interface not attempt to access C++ instances via the foreign type system, but instead use the more robust wrapper functions.
-17.3.7 Templates
-17.3.7.1 Generating wrapper code for - templates
+18.3.7 Templates
+18.3.7.1 Generating wrapper code for + templates
SWIG provides support for dealing with templates, but by default, it will not generate any member variable or function wrappers for templated classes. In order to create these wrappers, you need to explicitly tell SWIG to instantiate them. This is done via the %template directive.
-17.3.7.2 Implicit Template - instantiation
+18.3.7.2 Implicit Template instantiation +
While no wrapper code is generated for accessing member variables, or calling member functions, type code is generated to include these templated classes in the foreign-type and CLOS class schema.
-17.3.8 Typedef, Templates, and Synonym - Types
+18.3.8 Typedef, Templates, and Synonym + Types
In C/C++ it is possible, via typedef, to have many names refer to the same type. In general, this is not a problem, though it can lead to confusion. Assume the below C++ header file:
@@ -20216,7 +21836,7 @@ synonym> (zzz foo) synonym>17.3.8.1 Choosing a primary type
+18.3.8.1 Choosing a primary type
The choice of a primary type is selected by the following criteria from a set of synonym types.
@@ -20226,8 +21846,8 @@ synonym>
-- For all other sets of synonymous types, the synonym which is parsed first becomes the primary type.
17.3.9 Function overloading/Parameter - defaulting
+18.3.9 Function overloading/Parameter + defaulting
For each possible argument combination, a distinct wrapper function is created in the .cxx file. On the Lisp side, a generic functions is defined for each possible arity the overloaded/defaulted call may have. @@ -20375,76 +21995,76 @@ overload> (xxx a 2) overload>
17.3.10 Operator wrapping and Operator - overloading
+18.3.10 Operator wrapping and Operator + overloading
Wrappers to defined C++ Operators are automatically renamed, using %rename, to the following defaults:
/* name conversion for overloaded operators. */ #ifdef __cplusplus -%rename(__add__) *::operator+; -%rename(__pos__) *::operator+(); -%rename(__pos__) *::operator+() const; +%rename(__add__) *::operator+; +%rename(__pos__) *::operator+(); +%rename(__pos__) *::operator+() const; -%rename(__sub__) *::operator-; -%rename(__neg__) *::operator-() const; -%rename(__neg__) *::operator-(); +%rename(__sub__) *::operator-; +%rename(__neg__) *::operator-() const; +%rename(__neg__) *::operator-(); -%rename(__mul__) *::operator*; -%rename(__deref__) *::operator*(); -%rename(__deref__) *::operator*() const; +%rename(__mul__) *::operator*; +%rename(__deref__) *::operator*(); +%rename(__deref__) *::operator*() const; -%rename(__div__) *::operator/; -%rename(__mod__) *::operator%; -%rename(__logxor__) *::operator^; -%rename(__logand__) *::operator&; -%rename(__logior__) *::operator|; -%rename(__lognot__) *::operator~(); -%rename(__lognot__) *::operator~() const; +%rename(__div__) *::operator/; +%rename(__mod__) *::operator%; +%rename(__logxor__) *::operator^; +%rename(__logand__) *::operator&; +%rename(__logior__) *::operator|; +%rename(__lognot__) *::operator~(); +%rename(__lognot__) *::operator~() const; -%rename(__not__) *::operator!(); -%rename(__not__) *::operator!() const; +%rename(__not__) *::operator!(); +%rename(__not__) *::operator!() const; -%rename(__assign__) *::operator=; +%rename(__assign__) *::operator=; %rename(__add_assign__) *::operator+=; -%rename(__sub_assign__) *::operator-=; -%rename(__mul_assign__) *::operator*=; -%rename(__div_assign__) *::operator/=; -%rename(__mod_assign__) *::operator%=; +%rename(__sub_assign__) *::operator-=; +%rename(__mul_assign__) *::operator*=; +%rename(__div_assign__) *::operator/=; +%rename(__mod_assign__) *::operator%=; %rename(__logxor_assign__) *::operator^=; %rename(__logand_assign__) *::operator&=; %rename(__logior_assign__) *::operator|=; -%rename(__lshift__) *::operator<<; +%rename(__lshift__) *::operator<<; %rename(__lshift_assign__) *::operator<<=; -%rename(__rshift__) *::operator>>; +%rename(__rshift__) *::operator>>; %rename(__rshift_assign__) *::operator>>=; -%rename(__eq__) *::operator==; -%rename(__ne__) *::operator!=; -%rename(__lt__) *::operator<; -%rename(__gt__) *::operator>; -%rename(__lte__) *::operator<=; -%rename(__gte__) *::operator>=; +%rename(__eq__) *::operator==; +%rename(__ne__) *::operator!=; +%rename(__lt__) *::operator<; +%rename(__gt__) *::operator>; +%rename(__lte__) *::operator<=; +%rename(__gte__) *::operator>=; -%rename(__and__) *::operator&&; -%rename(__or__) *::operator||; +%rename(__and__) *::operator&&; +%rename(__or__) *::operator||; -%rename(__preincr__) *::operator++(); -%rename(__postincr__) *::operator++(int); -%rename(__predecr__) *::operator--(); -%rename(__postdecr__) *::operator--(int); +%rename(__preincr__) *::operator++(); +%rename(__postincr__) *::operator++(int); +%rename(__predecr__) *::operator--(); +%rename(__postdecr__) *::operator--(int); -%rename(__comma__) *::operator,(); -%rename(__comma__) *::operator,() const; +%rename(__comma__) *::operator,(); +%rename(__comma__) *::operator,() const; %rename(__member_ref__) *::operator->; %rename(__member_func_ref__) *::operator->*; -%rename(__funcall__) *::operator(); -%rename(__aref__) *::operator[]; +%rename(__funcall__) *::operator(); +%rename(__aref__) *::operator[];Name mangling occurs on all such renamed identifiers, so that @@ -20504,39 +22124,39 @@ nil opoverload>
17.3.11 Varargs
+18.3.11 Varargs
Variable length argument lists are not supported, by default. If such a function is encountered, a warning will generated to stderr. Varargs are supported via the SWIG %varargs directive. This directive allows you to specify a (finite) argument list which will be inserted into the wrapper in place of the variable length argument - indicator. As an example, consider the function printf(). It's + indicator. As an example, consider the function printf(). Its declaration would appear as follows:
See the following section on Variable Length arguments provides examples on how %varargs can be used, along with other ways such functions can be wrapped.
-17.3.12 C++ Exceptions
+18.3.12 C++ Exceptions
Each C++ wrapper includes a handler to catch any exceptions that may be thrown while in foreign code. This helps prevent simple C++ errors from killing the entire lisp process. There is currently no mechanism to have these exceptions forwarded to the lisp condition system, nor has any explicit support of the exception related SWIG typemaps been implemented.
-17.3.13 Pass by value, pass by - reference
+18.3.13 Pass by value, pass by reference +
Allegro CL does not support the passing of non-primitive foreign structures by value. As a result, SWIG must automatically detect and convert function parameters and return values to pointers whenever necessary. This is done via the use of typemaps, and should not require any fine tuning by the user, even for newly defined types.
-17.4 Typemaps
+18.4 Typemaps
SWIG Typemaps provide a powerful tool for automatically generating code to handle various menial tasks required of writing an interface to foreign code. The purpose of this section is to describe each of the typemaps used by the Allegro CL module. Please read the chapter on Typemaps for more information.
-17.4.1 Code Generation in the C++ - Wrapper
+18.4.1 Code Generation in the C++ Wrapper +
Every C++ wrapper generated by SWIG takes the following form:
-@@ -20559,7 +22179,7 @@ return-val wrapper-name(parm0, parm1, ..., parmN) }17.4.1.1 IN Typemap
+18.4.1.1 IN Typemap
the in typemap is used to generate code to convert parameters passed to C++ wrapper functions into the arguments desired for the call being wrapped. That is, it fills in the code for the @@ -20586,11 +22206,11 @@ $1 is the local variable to which it is being assigned. The default %typemap(in) SWIGTYPE "$1 = *$input;";
17.4.1.2 OUT Typemap
+18.4.1.2 OUT Typemap
The out typemap is used to generate code to form the return value of the wrapper from the return value of the wrapped function. This code is placed in the <convert and bind result to lresult> section - of the above code diagram. It's default mapping is as follows:
+ of the above code diagram. Its default mapping is as follows:-%typemap(out) bool "$result = (int)$1;"; @@ -20604,11 +22224,11 @@ $1 is the local variable to which it is being assigned. The default %typemap(out) SWIGTYPE "$result = new $1_type($1);";17.4.1.3 CTYPE Typemap
+18.4.1.3 CTYPE Typemap
This typemap is not used for code generation, but purely for the transformation of types in the parameter list of the wrapper function. - It's primary use is to handle by-value to by-reference conversion in - the wrappers parameter list. Its default settings are:
+ Its primary use is to handle by-value to by-reference conversion in the + wrappers parameter list. Its default settings are:-%typemap(ctype) bool "int"; @@ -20626,7 +22246,7 @@ $1 is the local variable to which it is being assigned. The default interface generator. SWIG also implements a number of other typemaps that can be used for generating code in the C/C++ wrappers. You can read about these common typemaps here. -17.4.2 Code generation in Lisp wrappers
+18.4.2 Code generation in Lisp wrappers
A number of custom typemaps have also been added to facilitate the generation of code in the lisp side of the interface. These are described below. The basic code generation structure is applied as a @@ -20637,7 +22257,7 @@ $1 is the local variable to which it is being assigned. The default necessary. Users writing their own typemaps should do likewise. See the explanation in the last paragraph of 16.3.1 Namespaces for details.
-17.4.2.1 LIN Typemap
+18.4.2.1 LIN Typemap
The LIN typemap allows for the manipulating the lisp objects passed as arguments to the wrapping defun before passing them to the foreign function call. For example, when passing lisp strings to foreign code, @@ -20664,10 +22284,10 @@ $1 is the local variable to which it is being assigned. The default
--%typemap(lin) SWIGTYPE "(cl:let (($out $in))\n $body)"; +%typemap(lin) SWIGTYPE "(cl:let (($out $in))\n $body)";17.4.2.2 LOUT Typemap
+18.4.2.2 LOUT Typemap
The LOUT typemap is the means by which we effect the wrapping of foreign pointers in CLOS instances. It is applied after all LIN typemaps, and immediately before the actual foreign-call.
@@ -20699,7 +22319,7 @@ $1 is the local variable to which it is being assigned. The default ACL_result)";17.4.2.3 FFITYPE Typemap
+18.4.2.3 FFITYPE Typemap
The FFITYPE typemap works as a helper for a body of code that converts C/C++ type specifications into Allegro CL foreign-type specifications. These foreign-type specifications appear in @@ -20737,7 +22357,7 @@ $1 is the local variable to which it is being assigned. The default %typemap(ffitype) SWIGTYPE & "(* :void)";
17.4.2.4 LISPTYPE Typemap
+18.4.2.4 LISPTYPE Typemap
This is another type only transformation map, and is used to provide the lisp-type, which is the optional third argument in argument specifier in a ff:def-foreign-call form. Specifying a lisp-type allows @@ -20751,7 +22371,7 @@ $1 is the local variable to which it is being assigned. The default %typemap(lisptype) signed char "cl:integer";
17.4.2.5 LISPCLASS Typemap
+18.4.2.5 LISPCLASS Typemap
The LISPCLASS typemap is used to generate the method signatures for the generic-functions which wrap overloaded functions and functions with defaulted arguments. The default entries are:
@@ -20769,8 +22389,8 @@ $1 is the local variable to which it is being assigned. The default %typemap(lispclass) char * "cl:string";17.4.3 Modifying SWIG behavior using - typemaps
+18.4.3 Modifying SWIG behavior using + typemaps
The following example shows how we made use of the above typemaps to add support for the wchar_t type.
@@ -20798,9 +22418,9 @@ $1 is the local variable to which it is being assigned. The default %typemap(lispclass) wchar_t* "cl:string";-17.5 Identifier Converter functions
-17.5.1 Creating symbols in the lisp - environment
+18.5 Identifier Converter functions
+18.5.1 Creating symbols in the lisp + environment
Various symbols must be generated in the lisp environment to which class definitions, functions, constants, variables, etc. must be bound. Rather than force a particular convention for naming these symbols, an @@ -20813,23 +22433,23 @@ $1 is the local variable to which it is being assigned. The default reference. It is therefore expected that the identifier-converter function reliably return the same (eq) symbol given the same set of arguments.
-17.5.2 Existing identifier-converter - functions
+18.5.2 Existing identifier-converter + functions
Two basic identifier routines have been defined.
-17.5.2.1 identifier-convert-null
+18.5.2.1 identifier-convert-null
No modification of the identifier string is performed. Based on other arguments, the identifier may be concatenated with other strings, from which a symbol will be created.
-17.5.2.2 identifier-convert-lispify
+18.5.2.2 identifier-convert-lispify
All underscores in the identifier string are converted to hyphens. Otherwise, identifier-convert-lispify performs the same symbol transformations.
-17.5.2.3 Default identifier to symbol - conversions
+18.5.2.3 Default identifier to symbol + conversions
Check the definitions of the above two default identifier-converters in Lib/allegrocl/allegrocl.swg for default naming conventions.
-17.5.3 Defining your own - identifier-converter
+18.5.3 Defining your own + identifier-converter
A user-defined identifier-converter function should conform to the following specification:
@@ -20841,10 +22461,10 @@ result ==> symbol or (setf symbol)The ID argument is a string representing an identifier in the foreign environment.
The :type keyword argument provides more information on the type of - identifier. It's value is a symbol. This allows the - identifier-converter to apply different heuristics when mapping - different types of identifiers to symbols. SWIG will generate calls to - your identifier-converter using the following types.
+ identifier. Its value is a symbol. This allows the identifier-converter + to apply different heuristics when mapping different types of + identifiers to symbols. SWIG will generate calls to your + identifier-converter using the following types.
- :class - names a CLOS class.
- :constant - names a defconstant
@@ -20865,11 +22485,11 @@ result ==> symbol or (setf symbol) non-nil, it indicates that the current identifier has scope in the specified class.The :arity keyword argument only appears in swig:swig-defmethod - forms generated for overloaded functions. It's value is an integer + forms generated for overloaded functions. Its value is an integer indicating the number of arguments passed to the routine indicated by this identifier.
-17.5.4 Instructing SWIG to use a - particular identifier-converter
+18.5.4 Instructing SWIG to use a particular + identifier-converter
By default, SWIG will use identifier-converter-null. To specify another convert function, use the -identifier-converter command-line argument. The value should be a string naming the function @@ -20879,7 +22499,7 @@ result ==> symbol or (setf symbol) % swig -allegrocl -c++ -module mymodule -identifier-converter my-identifier-converter
-18 SWIG and Android
+19 SWIG and Android
@@ -20898,16 +22518,16 @@ result ==> symbol or (setf symbol)This chapter describes SWIG's support of Android.
-18.1 Overview
+19.1 Overview
The Android chapter is fairly short as support for Android is the same as for Java, where the Java Native Interface (JNI) is used to call - from Android Java into C or C++ compiled code. Everything in the + from Android Java into C or C++ compiled code. Everything in the Java chapter applies to generating code for access from Android Java code. This chapter contains a few Android specific notes and examples.
-18.2 Android examples
-18.2.1 Examples introduction
+19.2 Android examples
+19.2.1 Examples introduction
The examples require the -Android SDK and +Android SDK and Android NDK which can be installed as per instructions in the links. The Eclipse version is not required for these examples as just the command line tools are used (shown for Linux as the host, but Windows @@ -20919,7 +22539,7 @@ Android NDK which can be installed as per instructions in the links.
$ export PATH=$HOME/android/android-sdk-linux_x86/tools:$HOME/android/android-sdk-linux_x86/platform-tools:$HOME/android/android-ndk-r6b:$PATH $ mkdir AndroidApps -$ cd AnrdoidApps +$ cd AndroidAppsThe examples use a target id of 1. This might need changing @@ -20934,7 +22554,7 @@ $ android list targets
The following examples are shipped with SWIG under the Examples/android directory and include a Makefile to build and install each example.
-18.2.2 Simple C example
+19.2.2 Simple C example
This simple C example shows how to call a C function as well as read and modify a global variable. First we'll create and build a pure Java Android app. Afterwards the JNI code will be generated by SWIG and @@ -21055,7 +22675,7 @@ Using hardware devices on the Android developer's site. When
$ adb devices List of devices attached -A32-6DBE0001-9FF80000-015D62C3-02018028 device +A32-6DBE0001-9FF80000-015D62C3-02018028 deviceThis means you are now ready to install the application...
@@ -21063,7 +22683,7 @@ A32-6DBE0001-9FF80000-015D62C3-02018028 device$ adb install bin/SwigSimple-debug.apk 95 KB/s (4834 bytes in 0.049s) - pkg: /data/local/tmp/SwigSimple-debug.apk + pkg: /data/local/tmp/SwigSimple-debug.apk Success- 18.2.3 C++ class example
+19.2.3 C++ class example
The steps for calling C++ code are almost identical to those in the previous C code example. All the steps required to compile and use a simple hierarchy of classes for shapes are shown in this example.
@@ -21238,11 +22858,11 @@ public: } virtual ~Shape() { nshapes--; - }; + } double x, y; void move(double dx, double dy); - virtual double area(void) = 0; - virtual double perimeter(void) = 0; + virtual double area() = 0; + virtual double perimeter() = 0; static int nshapes; }; @@ -21250,18 +22870,18 @@ class Circle : public Shape { private: double radius; public: - Circle(double r) : radius(r) { }; - virtual double area(void); - virtual double perimeter(void); + Circle(double r) : radius(r) { } + virtual double area(); + virtual double perimeter(); }; class Square : public Shape { private: double width; public: - Square(double w) : width(w) { }; - virtual double area(void); - virtual double perimeter(void); + Square(double w) : width(w) { } + virtual double area(); + virtual double perimeter(); };Run the app to see the result of calling the C++ code from Java:
- 18.2.4 Other examples
+19.2.4 Other examples
The Examples/android directory contains further examples which can be run and installed in a similar manner to the previous two examples.
Note that the 'extend' example is demonstrates the directors feature. Normally C++ exception handling and the STL is not available by default in the version of g++ shipped with Android, but this example turns these features on as described in the next section.
-18.3 C++ STL
+19.3 C++ STL
Should the C++ Standard Template Library (STL) be required, an Application.mk file needs to be created in the same directory as the Android.mk directory containing information about the STL @@ -21539,12 +23159,18 @@ Application.mk file to make the STLport static library available APP_STL := gnustl_static
-19 SWIG and C#
+20 SWIG and C#
--
-- Introduction
+- Introduction + +
- Differences to the Java module
- Void pointers
@@ -21576,7 +23202,7 @@ APP_STL := gnustl_static- Director caveats
- Multiples modules
+- Multiple modules
- C# Typemap examples
19.1 Introduction
+20.1 Introduction
The purpose of the C# module is to offer an automated way of accessing existing C/C++ code from .NET languages. The wrapper code implementation uses C# and the Platform Invoke (PInvoke) interface to @@ -21616,10 +23242,55 @@ Portable.NET.
required. The Microsoft Developer Network (MSDN) has a good reference guide in a section titled "Interop Marshaling". Monodoc, available from the Mono project, has a - very useful section titled + very useful section titled Interop with native libraries. -19.2 Differences to the Java - module
+20.1.1 SWIG 2 + Compatibility
+In order to minimize name collisions between names generated based + on input to SWIG and names used in the generated code from the .NET + framework, SWIG 3 fully qualifies the use of all .NET types. + Furthermore, SWIG 3 avoids using directives in generated code. + This breaks backwards compatibility with typemaps, pragmas, etc written + for use with SWIG 2 that assume the presence of using System; + or using System.Runtime.InteropServices; directives in the + intermediate class imports, module imports, or proxy imports. SWIG 3 + supports backwards compatibility though the use of the SWIG2_CSHARP + macro. If SWIG2_CSHARP is defined, SWIG 3 generates using + directives in the intermediate class, module class, and proxy class + code similar to those generated by SWIG 2. This can be done without + modifying any of the input code by passing the -DSWIG2_CSHARP + commandline parameter when executing swig.
+20.1.2 Additional command line options +
+The following table lists the additional commandline options + available for the C# module. They can also be seen by using:
++++swig -csharp -help +++
++ C# specific options + -dllimport <dl> Override DllImport attribute name to + <dl> + -namespace <nm> Generate wrappers into C# namespace <nm> ++ -noproxy Generate the low-level functional interface + instead of proxy classes + -oldvarnames Old intermediary method names for variable + wrappers + -outfile <file> Write all C# into a single <file> + located in the output directory The -outfile option combines all the generated C# code into a single + output file instead of creating multiple C# files. The default, when + this option is not provided, is to generate separate .cs files for the + module class, intermediary class and each of the generated proxy and + type wrapper classes. Note that the file extension (.cs) will not be + automatically added and needs to be provided. Due to possible compiler + limits it is not advisable to use -outfile for large projects.
+20.2 Differences to the Java + module
The C# module is very similar to the Java module, so until some more complete documentation has been written, please use the Java documentation as a guide to using SWIG with C#. The C# module @@ -21696,6 +23367,7 @@ javabody -> csbody javafinalize -> csfinalize javadestruct -> csdestruct javadestruct_derived -> csdestruct_derived +javainterfacecode -> csinterfacecode
- @@ -21758,6 +23430,9 @@ $*javaclassname -> $*csclassname $javaclazzname -> $csclazzname $javainput -> $csinput $jnicall -> $imcall +$javainterfacename -> $csinterfacename +$&javainterfacename -> $&csinterfacename +$*javainterfacename -> $*csinterfacename
- @@ -21791,7 +23466,7 @@ Date marshalling director example for further understanding of the char * could be marshalled in different ways,
@@ -21799,7 +23474,7 @@ char * function(char *); resulting intermediary C# code is:-%typemap(imtype, out="IntPtr") char * "string" +%typemap(imtype, out="global::System.IntPtr") char * "string" char * function(char *);-public static extern IntPtr function(string jarg1); +public static extern global::System.IntPtr function(string jarg1);- @@ -21818,8 +23493,8 @@ directors implementation. Note that there are C# attributes and
@@ -21878,7 +23553,7 @@ public:%typemap(imtype, - inattributes="[MarshalAs(UnmanagedType.LPStr)]", - outattributes="[return: MarshalAs(UnmanagedType.LPStr)]") const char * "String" + inattributes="[global::System.Runtime.InteropServices.MarshalAs(UnmanagedType.LPStr)]", + outattributes="[return: global::System.Runtime.InteropServices.MarshalAs(UnmanagedType.LPStr)]") const char * "String" const char * GetMsg() {} void SetMsg(const char *msg) {} @@ -21831,12 +23506,12 @@ void SetMsg(const char *msg) {}class examplePINVOKE { ... - [DllImport("example", EntryPoint="CSharp_GetMsg")] - [return: MarshalAs(UnmanagedType.LPStr)] + [global::System.Runtime.InteropServices.DllImport("example", EntryPoint="CSharp_GetMsg")] + [return: global::System.Runtime.InteropServices.MarshalAs(UnmanagedType.LPStr)] public static extern String GetMsg(); - [DllImport("example", EntryPoint="CSharp_SetMsg")] - public static extern void SetMsg([MarshalAs(UnmanagedType.LPStr)]String jarg1); + [global::System.Runtime.InteropServices.DllImport("example", EntryPoint="CSharp_SetMsg")] + public static extern void SetMsg([global::System.Runtime.InteropServices.MarshalAs(UnmanagedType.LPStr)]String jarg1); }-[ThreadSafe] -public class AClass : IDisposable { +public class AClass : global::System.IDisposable { ... [ThreadSafe(false)] public AClass(double a) ... @@ -21898,9 +23573,9 @@ public class AClass : IDisposable { shown below.--%typemap(csattributes) Couleur "[System.ComponentModel.Description(\"Colours\")]" -%csattributes Rouge "[System.ComponentModel.Description(\"Red\")]" -%csattributes Vert "[System.ComponentModel.Description(\"Green\")]" +%typemap(csattributes) Couleur "[global::System.ComponentModel.Description(\"Colours\")]" +%csattributes Rouge "[global::System.ComponentModel.Description(\"Red\")]" +%csattributes Vert "[global::System.ComponentModel.Description(\"Green\")]" %inline %{ enum Couleur { Rouge, Orange, Vert }; %} @@ -21909,12 +23584,12 @@ public class AClass : IDisposable {which will result in the following C# enum:
--[System.ComponentModel.Description("Colours")] +[global::System.ComponentModel.Description("Colours")] public enum Couleur { - [System.ComponentModel.Description("Red")] + [global::System.ComponentModel.Description("Red")] Rouge, Orange, - [System.ComponentModel.Description("Green")] + [global::System.ComponentModel.Description("Green")] Vert }@@ -21975,7 +23650,7 @@ Cygwin or MinGW environment for automatic configuration of the example makefiles. Any one of the three C# compilers (Portable.NET, Mono or Microsoft) can be detected from within a Cygwin or Mingw environment if installed in your path. -19.3 Void pointers
+20.3 Void pointers
By default SWIG treats void * as any other pointer and hence marshalls it as a type wrapper class called SWIGTYPE_p_void . If you want to marshall with the .NET System.IntPtr type @@ -21988,7 +23663,7 @@ Cygwin or MinGW environment for void * f(void *v);
19.4 C# Arrays
+20.4 C# Arrays
There are various ways to pass arrays from C# to C/C++. The default wrapping treats arrays as pointers and as such simple type wrapper classes are generated, eg SWIGTYPE_p_int when wrapping the C @@ -21997,8 +23672,8 @@ void * f(void *v); arrays is to enhance or customise with one of the following three approaches; namely the SWIG C arrays library, P/Invoke default array marshalling or pinned arrays.
-19.4.1 The SWIG C arrays - library
+20.4.1 The SWIG C arrays + library
The C arrays library keeps all the array memory in the unmanaged layer. The library is available to all language modules and is documented in the carrays.i library @@ -22025,8 +23700,8 @@ for (int i=0; i<10; i++) example.print_array(c.cast()); // Pass to C
19.4.2 - Managed arrays using P/Invoke default array marshalling
+20.4.2 + Managed arrays using P/Invoke default array marshalling
In the P/Invoke default marshalling scheme, one needs to designate whether the invoked function will treat a managed array parameter as input, output, or both. When the function is invoked, the CLR allocates @@ -22075,9 +23750,9 @@ public static void myArrayCopy(int[] sourceArray, int[] targetArray, int nitems) use default marshalling for the arrays:
@@ -22109,14 +23784,14 @@ void myArraySwap(int *array1, int *array2, int nitems);-[DllImport("example", EntryPoint="CSharp_myArrayCopy")] -public static extern void myArrayCopy([In, MarshalAs(UnmanagedType.LPArray)]int[] jarg1, - [Out, MarshalAs(UnmanagedType.LPArray)]int[] jarg2, +[global::System.Runtime.InteropServices.DllImport("example", EntryPoint="CSharp_myArrayCopy")] +public static extern void myArrayCopy([global::System.Runtime.InteropServices.In, global::System.Runtime.InteropServices.MarshalAs(UnmanagedType.LPArray)]int[] jarg1, + [global::System.Runtime.InteropServices.Out, global::System.Runtime.InteropServices.MarshalAs(UnmanagedType.LPArray)]int[] jarg2, int jarg3);and intermediary class method
-- [DllImport("example", EntryPoint="CSharp_myArraySwap")] - public static extern void myArraySwap([In, Out, MarshalAs(UnmanagedType.LPArray)]int[] jarg1, - [In, Out, MarshalAs(UnmanagedType.LPArray)]int[] jarg2, + [global::System.Runtime.InteropServices.DllImport("example", EntryPoint="CSharp_myArraySwap")] + public static extern void myArraySwap([global::System.Runtime.InteropServices.In, global::System.Runtime.InteropServices.Out, global::System.Runtime.InteropServices.MarshalAs(UnmanagedType.LPArray)]int[] jarg1, + [global::System.Runtime.InteropServices.In, global::System.Runtime.InteropServices.Out, global::System.Runtime.InteropServices.MarshalAs(UnmanagedType.LPArray)]int[] jarg2, int jarg3);19.4.3 Managed arrays using - pinning
+20.4.3 Managed arrays using pinning +
It is also possible to pin a given array in memory (i.e. fix its location in memory), obtain a direct pointer to it, and then pass this pointer to the wrapped C/C++ function. This approach involves no @@ -22162,7 +23837,7 @@ void myArrayCopy(int *sourceArray, int *targetArray, int nitems); fixed ( int *swig_ptrTo_sourceArray = sourceArray ) { fixed ( int *swig_ptrTo_targetArray = targetArray ) { { - examplePINVOKE.myArrayCopy((IntPtr)swig_ptrTo_sourceArray, (IntPtr)swig_ptrTo_targetArray, + examplePINVOKE.myArrayCopy((global::System.IntPtr)swig_ptrTo_sourceArray, (global::System.IntPtr)swig_ptrTo_targetArray, nitems); } } @@ -22178,11 +23853,11 @@ void myArrayCopy(int *sourceArray, int *targetArray, int nitems); parameter type.
--[DllImport("example", EntryPoint="CSharp_myArrayCopy")] -public static extern void myArrayCopy(IntPtr jarg1, IntPtr jarg2, int jarg3); +[global::System.Runtime.InteropServices.DllImport("example", EntryPoint="CSharp_myArrayCopy")] +public static extern void myArrayCopy(global::System.IntPtr jarg1, global::System.IntPtr jarg2, int jarg3);19.5 C# Exceptions
+20.5 C# Exceptions
It is possible to throw a C# Exception from C/C++ code. SWIG already provides the framework for throwing C# exceptions if it is able to detect that a C++ exception could be thrown. Automatically detecting @@ -22272,9 +23947,9 @@ msg and param_name parameters contain the C# exception attribute set. The %csnothrowexception feature is like %exception, but it does not have the canthrow attribute set so should only be used when a C# exception is not created.
-19.5.1 C# - exception example using "check" typemap
-Lets say we have the following simple C++ method:
+20.5.1 C# exception + example using "check" typemap
+Let's say we have the following simple C++ method:
void positivesonly(int number); @@ -22420,8 +24095,8 @@ method and C# code does not handle pending exceptions via the canthrow attributeActually it will issue this warning for any function beginning with SWIG_CSharpSetPendingException.
-19.5.2 C# - exception example using %exception
+20.5.2 C# + exception example using %exception
Let's consider a similar, but more common example that throws a C++ exception from within a wrapped function. We can use %exception as mentioned in Exception handling @@ -22433,6 +24108,7 @@ try { $action } catch (std::out_of_range e) { SWIG_CSharpSetPendingException(SWIG_CSharpApplicationException, e.what()); + return $null; } %} @@ -22477,8 +24153,8 @@ canthrow attribute set by default:
}-19.5.3 C# exception example using exception specifications
+20.5.3 + C# exception example using exception specifications
When C++ exception specifications are used, SWIG is able to detect that the method might throw an exception. By default SWIG will automatically generate code to catch the exception and convert it into @@ -22526,8 +24202,8 @@ SWIGEXPORT void SWIGSTDCALL CSharp_evensonly(int jarg1) {
Multiple catch handlers are generated should there be more than one exception specifications declared.
-19.5.4 Custom C# - ApplicationException example
+20.5.4 Custom C# + ApplicationException example
This example involves a user defined exception. The conventional .NET exception handling approach is to create a custom ApplicationException and throw it in your application. The goal in @@ -22570,7 +24246,7 @@ imclasscode pragma as follows:
static CustomExceptionDelegate customDelegate = new CustomExceptionDelegate(SetPendingCustomException); - [DllImport("$dllimport", EntryPoint="CustomExceptionRegisterCallback")] + [global::System.Runtime.InteropServices.DllImport("$dllimport", EntryPoint="CustomExceptionRegisterCallback")] public static extern void CustomExceptionRegisterCallback(CustomExceptionDelegate customCallback); @@ -22618,7 +24294,7 @@ SWIG_CSharpSetPendingExceptionArgument() does. In fact the method-// Custom C# Exception -class CustomApplicationException : System.ApplicationException { +class CustomApplicationException : global::System.ApplicationException { public CustomApplicationException(string message) : base(message) { } @@ -22653,7 +24329,7 @@ try { }19.6 C# Directors
+20.6 C# Directors
The SWIG directors feature adds extra code to the generated C# proxy classes that enable these classes to be used in cross-language polymorphism. Essentially, it enables unmanaged C++ code to call back @@ -22664,7 +24340,7 @@ try { C# directors. However, the Java directors section should also be read in order to gain more insight into directors.
-19.6.1 Directors example
+20.6.1 Directors example
Imagine we are wrapping a C++ base class, Base, from which we would like to inherit in C#. Such a class is shown below as well as another class, Caller, which calls the virtual method @@ -22765,8 +24441,8 @@ Base - UIntMethod(123) CSharpDerived - UIntMethod(123)
19.6.2 Directors - implementation
+20.6.2 Directors + implementation
The previous section demonstrated a simple example where the virtual UIntMethod method was called from C++ code, even when the overridden method is implemented in C#. The intention of this section @@ -22777,20 +24453,17 @@ Base class.
Below is the generated C# Base director class.
@@ -22945,7 +24618,7 @@ void SwigDirector_Base::BaseBoolMethod(Base const &b, bool flag) { }-using System; -using System.Runtime.InteropServices; - -public class Base : IDisposable { - private HandleRef swigCPtr; +public class Base : global::System.IDisposable { + private global::System.Runtime.InteropServices.HandleRef swigCPtr; protected bool swigCMemOwn; - internal Base(IntPtr cPtr, bool cMemoryOwn) { + internal Base(global::System.IntPtr cPtr, bool cMemoryOwn) { swigCMemOwn = cMemoryOwn; - swigCPtr = new HandleRef(this, cPtr); + swigCPtr = new global::System.Runtime.InteropServices.HandleRef(this, cPtr); } - internal static HandleRef getCPtr(Base obj) { - return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr; + internal static global::System.Runtime.InteropServices.HandleRef getCPtr(Base obj) { + return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr; } ~Base() { @@ -22799,12 +24472,12 @@ public class Base : IDisposable { public virtual void Dispose() { lock(this) { - if(swigCPtr.Handle != IntPtr.Zero && swigCMemOwn) { + if(swigCPtr.Handle != global::System.IntPtr.Zero && swigCMemOwn) { swigCMemOwn = false; examplePINVOKE.delete_Base(swigCPtr); } - swigCPtr = new HandleRef(null, IntPtr.Zero); - GC.SuppressFinalize(this); + swigCPtr = new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero); + global::System.GC.SuppressFinalize(this); } } @@ -22831,7 +24504,7 @@ public class Base : IDisposable { examplePINVOKE.Base_director_connect(swigCPtr, swigDelegate0, swigDelegate1); } - private bool SwigDerivedClassHasMethod(string methodName, Type[] methodTypes) { + private bool SwigDerivedClassHasMethod(string methodName, global::System.global::System.Type[] methodTypes) { System.Reflection.MethodInfo methodInfo = this.GetType().GetMethod(methodName, methodTypes); bool hasDerivedMethod = methodInfo.DeclaringType.IsSubclassOf(typeof(Base)); return hasDerivedMethod; @@ -22841,18 +24514,18 @@ public class Base : IDisposable { return UIntMethod(x); } - private void SwigDirectorBaseBoolMethod(IntPtr b, bool flag) { + private void SwigDirectorBaseBoolMethod(global::System.IntPtr b, bool flag) { BaseBoolMethod(new Base(b, false), flag); } internal delegate uint SwigDelegateBase_0(uint x); - internal delegate void SwigDelegateBase_1(IntPtr b, bool flag); + internal delegate void SwigDelegateBase_1(global::System.IntPtr b, bool flag); private SwigDelegateBase_0 swigDelegate0; private SwigDelegateBase_1 swigDelegate1; - private static Type[] swigMethodTypes0 = new Type[] { typeof(uint) }; - private static Type[] swigMethodTypes1 = new Type[] { typeof(Base), typeof(bool) }; + private static global::System.Type[] swigMethodTypes0 = new global::System.Type[] { typeof(uint) }; + private static global::System.Type[] swigMethodTypes1 = new global::System.Type[] { typeof(Base), typeof(bool) }; }19.6.3 Director caveats
+20.6.3 Director caveats
There is a subtle gotcha with directors. If default parameters are used, it is recommended to follow a pattern of always calling a single method in any C# derived class. An example will clarify this and the @@ -22990,22 +24663,22 @@ CSharpDefaults.DefaultMethod() will of course call this exact the implementation should pass the call on to CSharpDefaults.DefaultMethod(int)using the C++ default value, as shown above.
-19.7 Multiples modules
-When using multiple modules it is is - possible to compile each SWIG generated wrapper into a different - assembly. However, by default the generated code may not compile if - generated classes in one assembly use generated classes in another - assembly. The visibility of the getCPtr() and pointer - constructor generated from the csbody typemaps needs changing. - The default visibility is internal but it needs to be -public for access from a different assembly. Just changing - 'internal' to 'public' in the typemap achieves this. Two macros are - available in csharp.swg to make this easier and using them is - the preferred approach over simply copying the typemaps and modifying - as this is forward compatible with any changes in the csbody - typemap in future versions of SWIG. The macros are for the proxy and - typewrapper classes and can respectively be used to to make the method - and constructor public:
+20.7 Multiple modules
+When using multiple modules it is is possible + to compile each SWIG generated wrapper into a different assembly. + However, by default the generated code may not compile if generated + classes in one assembly use generated classes in another assembly. The + visibility of the getCPtr() and pointer constructor generated + from the csbody typemaps needs changing. The default + visibility is internal but it needs to be public for + access from a different assembly. Just changing 'internal' to 'public' + in the typemap achieves this. Two macros are available in +csharp.swg to make this easier and using them is the preferred + approach over simply copying the typemaps and modifying as this is + forward compatible with any changes in the csbody typemap in + future versions of SWIG. The macros are for the proxy and typewrapper + classes and can respectively be used to to make the method and + constructor public:
SWIG_CSBODY_PROXY(public, public, SWIGTYPE) @@ -23020,12 +24693,12 @@ public for access from a different assembly. Just changing [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] attribute if you don't want users to easily stumble upon these so called 'internal workings' of the wrappers. -19.8 C# Typemap examples
+20.8 C# Typemap examples
This section includes a few examples of typemaps. For more examples, you might look at the files "csharp.swg" and "typemaps.i " in the SWIG library. -19.8.1 - Memory management when returning references to member variables
+20.8.1 Memory + management when returning references to member variables
This example shows how to prevent premature garbage collection of objects when the underlying C++ class returns a pointer or reference to a member variable. The example is a direct equivalent to this @@ -23052,9 +24725,9 @@ public: Wheel wheel = new Bike(10).getWheel(); Console.WriteLine("wheel size: " + wheel.size); // Simulate a garbage collection - System.GC.Collect(); - System.GC.WaitForPendingFinalizers(); - Console.WriteLine("wheel size: " + wheel.size); + global::System.GC.Collect(); + global::System.GC.WaitForPendingFinalizers(); + global::System.Console.WriteLine("wheel size: " + wheel.size);
Don't be surprised that if the resulting output gives strange @@ -23087,9 +24760,9 @@ getWheel() method is called using the following typemaps.
// of dangling C++ pointer. Intended for methods that return pointers or // references to a member variable. %typemap(csout, excode=SWIGEXCODE) Wheel& getWheel { - IntPtr cPtr = $imcall;$excode + global::System.IntPtr cPtr = $imcall;$excode $csclassname ret = null; - if (cPtr != IntPtr.Zero) { + if (cPtr != global::System.IntPtr.Zero) { ret = new $csclassname(cPtr, $owner); ret.addReference(this); } @@ -23102,7 +24775,7 @@ getWheel() method is called using the following typemaps. in the generated getWheel() function:-public class Wheel : IDisposable { +public class Wheel : global::System.IDisposable { ... // Ensure that the GC doesn't collect any Bike instance set from C# private Bike bikeReference; @@ -23111,12 +24784,12 @@ public class Wheel : IDisposable { } } -public class Bike : IDisposable { +public class Bike : global::System.IDisposable { ... public Wheel getWheel() { - IntPtr cPtr = examplePINVOKE.Bike_getWheel(swigCPtr); + global::System.IntPtr cPtr = examplePINVOKE.Bike_getWheel(swigCPtr); Wheel ret = null; - if (cPtr != IntPtr.Zero) { + if (cPtr != global::System.IntPtr.Zero) { ret = new Wheel(cPtr, false); ret.addReference(this); } @@ -23126,8 +24799,8 @@ public class Bike : IDisposable {Note the addReference call.
-19.8.2 Memory - management for objects passed to the C++ layer
+20.8.2 Memory management + for objects passed to the C++ layer
The example is a direct equivalent to this Java equivalent. Managing memory can be tricky when using C++ and C# proxy classes. The previous example shows one such case and this @@ -23176,9 +24849,9 @@ public: container.setElement(element); Console.WriteLine("element.value: " + container.getElement().value); // Simulate a garbage collection - System.GC.Collect(); - System.GC.WaitForPendingFinalizers(); - Console.WriteLine("element.value: " + container.getElement().value); + global::System.GC.Collect(); + global::System.GC.WaitForPendingFinalizers(); + global::System.Console.WriteLine("element.value: " + container.getElement().value);
The temporary element created with new Element(20) could @@ -23188,14 +24861,14 @@ public: add in the appropriate references in the C# layer...
--public class Container : IDisposable { +public class Container : global::System.IDisposable { ... // Ensure that the GC doesn't collect any Element set from C# // as the underlying C++ class stores a shallow copy private Element elementReference; - private HandleRef getCPtrAndAddReference(Element element) { + private global::System.Runtime.InteropServices.HandleRef getCPtrAndAddReference(Element element) { elementReference = element; return Element.getCPtr(element); } @@ -23218,15 +24891,15 @@ public class Container : IDisposable { // Ensure that the GC doesn't collect any Element set from C# // as the underlying C++ class stores a shallow copy private Element elementReference; - private HandleRef getCPtrAndAddReference(Element element) { + private global::System.Runtime.InteropServices.HandleRef getCPtrAndAddReference(Element element) { elementReference = element; return Element.getCPtr(element); } %}19.8.3 Date marshalling using - the csin typemap and associated attributes
+20.8.3 Date marshalling using the + csin typemap and associated attributes
The NaN Exception example is a simple example of the "javain" typemap and its 'pre' attribute. This example demonstrates how a C++ date class, say CDate, can @@ -23260,7 +24933,7 @@ dateOut is a non-const output type.
C# proxy class CDate is used in the proxy interface:-public class Action : IDisposable { +public class Action : global::System.IDisposable { ... public Action(CDate dateIn, CDate dateOut) : this(examplePINVOKE.new_Action(CDate.getCPtr(dateIn), CDate.getCPtr(dateOut)), true) { @@ -23330,7 +25003,7 @@ dateIn = new System.DateTime(2012, 7, 14); follows:--public class Action : IDisposable { +public class Action : global::System.IDisposable { ... public int doSomething(System.DateTime dateIn, out System.DateTime dateOut) { CDate tempdateIn = new CDate(dateIn.Year, dateIn.Month, dateIn.Day); @@ -23348,7 +25021,7 @@ public class Action : IDisposable { } } - static private IntPtr SwigConstructAction(System.DateTime dateIn, out System.DateTime dateOut) { + static private global::System.IntPtr SwigConstructAction(System.DateTime dateIn, out System.DateTime dateOut) { CDate tempdateIn = new CDate(dateIn.Year, dateIn.Month, dateIn.Day); CDate tempdateOut = new CDate(); try { @@ -23490,8 +25163,8 @@ public class example { }19.8.4 A date example - demonstrating marshalling of C# properties
+20.8.4 A date example demonstrating + marshalling of C# properties
The previous section looked at converting a C++ date class to System.DateTime for parameters. This section extends this idea so that the correct marshalling is obtained when wrapping C++ variables. @@ -23539,8 +25212,8 @@ Structure data members. The typemap type required is thus CDate %typemap(csvarout, excode=SWIGEXCODE2) CDate * %{ /* csvarout typemap code */ get { - IntPtr cPtr = $imcall; - CDate tempDate = (cPtr == IntPtr.Zero) ? null : new CDate(cPtr, $owner);$excode + global::System.IntPtr cPtr = $imcall; + CDate tempDate = (cPtr == global::System.IntPtr.Zero) ? null : new CDate(cPtr, $owner);$excode return new System.DateTime(tempDate.getYear(), tempDate.getMonth(), tempDate.getDay(), 0, 0, 0); } %} @@ -23559,8 +25232,8 @@ public class example { } /* csvarout typemap code */ get { - IntPtr cPtr = examplePINVOKE.ImportantDate_get(); - CDate tempDate = (cPtr == IntPtr.Zero) ? null : new CDate(cPtr, false); + global::System.IntPtr cPtr = examplePINVOKE.ImportantDate_get(); + CDate tempDate = (cPtr == global::System.IntPtr.Zero) ? null : new CDate(cPtr, false); return new System.DateTime(tempDate.getYear(), tempDate.getMonth(), tempDate.getDay(), 0, 0, 0); } @@ -23596,8 +25269,8 @@ CDate.getCPtr(tempvalue). creating the temp$csinput variable is such an example; it is identical to what is in the 'pre' attribute. -
19.8.5 Date example - demonstrating the 'pre' and 'post' typemap attributes for directors
+20.8.5 Date example + demonstrating the 'pre' and 'post' typemap attributes for directors
The 'pre' and 'post' attributes in the "csdirectorin" typemap act like the attributes of the same name in the "csin" typemap. For example if we modify the Date marshalling @@ -23636,7 +25309,7 @@ CDate & parameter. The typemap may look like this:
... - private void SwigDirectorsomeCallback(IntPtr date) { + private void SwigDirectorsomeCallback(global::System.IntPtr date) { System.DateTime tempdate = new System.DateTime(); try { someCallback(out tempdate); @@ -23653,8 +25326,8 @@ CDate & parameter. The typemap may look like this:Pay special attention to the memory management issues, using these attributes.
-19.8.6 Turning wrapped classes - into partial classes
+20.8.6 Turning wrapped classes into + partial classes
C# supports the notion of partial classes whereby a class definition can be split into more than one file. It is possible to turn the wrapped C++ class into a partial C# class using the @@ -23671,7 +25344,7 @@ public:
The default C# proxy class generated is:
-public class ExtendMe : IDisposable { +public class ExtendMe : global::System.IDisposable { ... public int Part1() { ... @@ -23696,7 +25369,7 @@ ExtendMe class:The C# proxy class becomes a partial class:
-public partial class ExtendMe : IDisposable { +public partial class ExtendMe : global::System.IDisposable { ... public int Part1() { ... @@ -23708,7 +25381,7 @@ public partial class ExtendMe : IDisposable { elsewhere, for example:-public partial class ExtendMe : IDisposable { +public partial class ExtendMe : global::System.IDisposable { public int Part2() { return 2; } @@ -23727,8 +25400,8 @@ Console.WriteLine("part2: {0}", em.Part2()); code - Part1() and managed code - Part2(). The following example is an alternative approach to adding managed code to the generated proxy class. -19.8.7 Extending proxy - classes with additional C# code
+20.8.7 Extending proxy + classes with additional C# code
The previous example showed how to use partial classes to add functionality to a generated C# proxy class. It is also possible to extend a wrapped struct/class with C/C++ code by using the @@ -23749,7 +25422,7 @@ Console.WriteLine("part2: {0}", em.Part2());
The generated C# proxy class will instead be:
--public class ExtendMe : IDisposable { +public class ExtendMe : global::System.IDisposable { ... public int Part3() { return 3; @@ -23760,8 +25433,8 @@ public class ExtendMe : IDisposable { }19.8.8 Underlying type for - enums
+20.8.8 Underlying type for + enums
C# enums use int as the underlying type for each enum item. If you wish to change the underlying type to something else, then use the csbase typemap. For example when your C++ code uses a value larget @@ -23785,9 +25458,7 @@ public enum BigNumbers : uint { }
- - -20 SWIG and Chicken
+21 SWIG and Chicken
@@ -23848,7 +25519,7 @@ public enum BigNumbers : uint { -- object-oriented code is difficult to wrap by hand in CHICKEN -- and its typed pointer representation, essential for C and C++ libraries involving structures or classes. --20.1 Preliminaries
+21.1 Preliminaries
CHICKEN support was introduced to SWIG in version 1.3.18. SWIG relies on some recent additions to CHICKEN, which are only present in releases of CHICKEN with version number greater than or equal @@ -23856,7 +25527,7 @@ public enum BigNumbers : uint { the Garbage collection section below.
You may want to look at any of the examples in Examples/chicken/ directory for the basic steps to run SWIG CHICKEN.
-20.1.1 Running SWIG in C mode
+21.1.1 Running SWIG in C mode
To run SWIG CHICKEN in C mode, use the -chicken option.
-% swig -chicken example.i@@ -23875,7 +25546,7 @@ example.scm). The basic Scheme code must be compiled to C usingSo for the C mode of SWIG CHICKEN, example_wrap.c and oexample.c are the files that must be compiled to object files and linked into your project.
-20.1.2 Running SWIG in C++ mode
+21.1.2 Running SWIG in C++ mode
To run SWIG CHICKEN in C++ mode, use the -chicken -c++ option.
-% swig -chicken -c++ example.i@@ -23890,15 +25561,15 @@ oexample.c are the files that must be compiled to object files andSo for the C++ mode of SWIG CHICKEN, example_wrap.cxx and oexample.c are the files that must be compiled to object files and linked into your project.
-20.2 Code Generation
-20.2.1 Naming Conventions
+21.2 Code Generation
+21.2.1 Naming Conventions
Given a C variable, function or constant declaration named Foo_Bar, the declaration will be available in CHICKEN as an identifier ending with Foo-Bar. That is, an underscore is converted to a dash.
You may control what the CHICKEN identifier will be by using the %rename SWIG directive in the SWIG interface file.
-20.2.2 Modules
+21.2.2 Modules
The name of the module must be declared one of two ways:
- Placing %module example in the SWIG interface file.
@@ -23909,7 +25580,7 @@ Foo_Bar, the declaration will be available in CHICKEN as an (declare (unit modulename)), pass the -nounit option to SWIG.CHICKEN will be able to access the module using the
-(declare (uses modulename))
CHICKEN Scheme form.20.2.3 Constants and Variables
+21.2.3 Constants and Variables
Constants may be created using any of the four constructs in the interface file:
@@ -23932,7 +25603,7 @@ Foo_Bar, the declaration will be available in CHICKEN as an MYCONSTANT1 (MYCONSTANT1)). See Features and the %feature directive for info on how to apply the %feature. -
20.2.4 Functions
+21.2.4 Functions
C functions declared in the SWIG interface file will have corresponding CHICKEN Scheme procedures. For example, the C function "int sqrt(double x);" will be available using the Scheme form (sqrt @@ -23945,7 +25616,7 @@ Features and the %feature directive for info on how to apply the parameter, or a void return value and at least two argout parameters). The return values can then be accessed with
-(call-with-values)
.20.2.5 Exceptions
+21.2.5 Exceptions
The SWIG chicken module has support for exceptions thrown from C or C++ code to be caught in scheme. See Exception handling with %exception for more information about @@ -23982,7 +25653,7 @@ SFRI-12. Since the exception values are thrown directly, if
(test-throw 1))
20.3 TinyCLOS
+21.3 TinyCLOS
The author of TinyCLOS, Gregor Kiczales, describes TinyCLOS as: "Tiny CLOS is a Scheme implementation of a `kernelized' CLOS, with a metaobject protocol. The implementation is even simpler than the simple @@ -24007,7 +25678,7 @@ SFRI-12. Since the exception values are thrown directly, if
-the -closprefix mymod: argument is passed to SWIG, then the exported functions will be prefixed by the string "mymod:". If -useclassprefix is passed, -closprefix is ignored.
20.4 Linkage
+21.4 Linkage
Please refer to CHICKEN - A practical and portable Scheme system - User's manual for detailed help on how to link object files to create a CHICKEN Scheme program. Briefly, to link object files, be sure @@ -24020,8 +25691,8 @@ SFRI-12. Since the exception values are thrown directly, if
-(uses modname))
. This means that to load the module from scheme code, the code must include(declare (uses modname ))
.20.4.1 Static binary or shared library - linked at compile time
+21.4.1 Static binary or shared library linked + at compile time
We can easily use csc to build a static binary.
@@ -24053,8 +25724,8 @@ $ csc -v test_script.scm -lexample (load-library 'example "example.so"), in which case the test script does not need to be linked with example.so. The test_script.scm file can then be run with csi. -20.4.2 Building chicken extension - libraries
+21.4.2 Building chicken extension libraries +
Building a shared library like in the above section only works if the library is linked at compile time with a script containing
-(declare (uses ...))
or is loaded explicitly with@@ -24106,8 +25777,8 @@ mod2_wrap.c files that are created by SWIG are stand alone and do
more than once, just make sure known_space has **result, swig_type_info *type, int flags), passing a pointer to a struct representing the expected pointer type. flags is either zero or SWIG_POINTER_DISOWN (see below).See the Examples/chicken/egg directory in the SWIG source for an example that builds two eggs, one using the first method and one using the second method.
-20.4.3 Linking multiple SWIG modules with - TinyCLOS
+21.4.3 Linking multiple SWIG modules with + TinyCLOS
Linking together multiple modules that share type information using the
-%import
directive while also using -proxy is more complicated. For example, if mod2.i imports mod1.i @@ -24136,11 +25807,11 @@ mod2_wrap.c files that are created by SWIG are stand alone and do create an extension library or an egg, just create a module_load.scm file that(declare (uses ...))
all the modules.20.5 Typemaps
+21.5 Typemaps
The Chicken module handles all types via typemaps. This information is read from
-Lib/chicken/typemaps.i
andLib/chicken/chicken.swg
.20.6 Pointers
+21.6 Pointers
For pointer types, SWIG uses CHICKEN tagged pointers. A tagged pointer is an ordinary CHICKEN pointer with an extra slot for a void *. With SWIG CHICKEN, this void * is a pointer to a type-info structure. @@ -24160,7 +25831,7 @@ SWIG_NewPointerObj
20.6.1 Garbage collection
+21.6.1 Garbage collection
If the owner flag passed to
SWIG. This will not export code inside the _wrap.c file to register finalizers, and will then export destructor functions which must be called manually. -SWIG_NewPointerObj
is 1,NewPointerObj
will add a finalizer to the type which will call the destructor or delete method of that type. The destructor and delete @@ -24189,8 +25860,8 @@ Object ownership and %newobject for more information.20.7 Unsupported features and known - problems
+21.7 Unsupported features and known problems +
-
- No director support.
- No support for c++ standard types like std::vector.
@@ -24198,8 +25869,8 @@ Object ownership and %newobject for more information. correctly when using %feature(compactdefaultargs).20.7.1 TinyCLOS problems with Chicken - version <= 1.92
+21.7.1 TinyCLOS problems with Chicken version + <= 1.92
In Chicken versions equal to or below 1.92, TinyCLOS has a limitation such that generic methods do not properly work on methods with different number of specializers: TinyCLOS assumes that every method @@ -24235,7 +25906,7 @@ Lib/chicken/multi-generic.scm file in the SWIG source. This file functions inside TinyCLOS to correctly support multi-argument generics. Please see the comments at the top of both files for more information.
-21 SWIG and D
+22 SWIG and D
@@ -24255,13 +25926,13 @@ Lib/chicken/multi-generic.scm file in the SWIG source. This file-Special variable macros -%features +D and %feature Pragmas D Exceptions D Directors Other features -
- Extended namespace support (nspace)
+- Extended namespace support (nspace)
- Native pointer support
- Operator overloading
- Running the test-suite
@@ -24273,7 +25944,7 @@ Lib/chicken/multi-generic.scm file in the SWIG source. This file21.1 Introduction
+22.1 Introduction
From the D Programming Language web site: D is a systems programming language. Its focus is on combining the power and high performance of C and C++ with @@ -24302,10 +25973,10 @@ interface with C libraries. Why would a SWIG module for D be needed
+To help addressing these issues, the SWIG C# module has been forked to support D. Is has evolved quite a lot since then, but there are still many similarities, so if you do not find what you are looking for - on this page, it might be worth having a look at the chapter on -C# (and also on Java, since the C# module - was in turn forked from it).
-21.2 Command line invocation
+ on this page, it might be worth having a look at the chapter on +C# (and also on Java, since the C# module was in + turn forked from it).22.2 Command line invocation
To activate the D module, pass the -d option to SWIG at the command line. The same standard command line switches as with any other language module are available, plus the following D specific ones:
@@ -24315,7 +25986,7 @@ C# (and also on Java, since the C# moduleBy default, SWIG generates code for D1/Tango. Use the -d2 flag to target D2/Phobos instead.
--splitproxy +-splitproxy - By default, SWIG generates two D modules: the proxy module, named like the source module (either specified via the %module @@ -24348,9 +26019,9 @@ C# (and also on Java, since the C# module shared library.
21.3 Typemaps
-21.3.1 C# <-> D name - comparison
+22.3 Typemaps
+22.3.1 C# <-> D name comparison +
If you already know the SWIG C# module, you might find the following name comparison table useful:
@@ -24374,7 +26045,7 @@ C# (and also on Java, since the C# module csdestruct_derived <-> ddispose_derived-21.3.2 ctype, imtype, dtype
+22.3.2 ctype, imtype, dtype
Mapping of types between the C/C++ library, the C/C++ library wrapper exposing the C functions, the D wrapper module importing these functions and the D proxy code.
@@ -24383,8 +26054,8 @@ C# (and also on Java, since the C# module used in the extern(C) declarations of these functions in the intermediary D module. The dtype typemap contains the D types used in the D proxy module/class. -21.3.3 in, out, - directorin, directorout
+22.3.3 in, out, + directorin, directorout
Used for converting between the types for C/C++ and D when generating the code for the wrapper functions (on the C++ side).
The code from the in typemap is used to convert arguments to @@ -24395,31 +26066,32 @@ C# (and also on Java, since the C# module
The directorin typemap is used to convert parameters to the type used in the D director callback function, its return value is processed by directorout (see below).
-21.3.4 din, dout, - ddirectorin, ddirectorout
+22.3.4 din, dout, + ddirectorin, ddirectorout
Typemaps for code generation in D proxy and type wrapper classes.
-The din typemap is used for converting function - parameter types from the type used in the proxy module or class to the - type used in the intermediary D module (the -$dinput macro is replaced). To inject further parameter - processing code before or after the call to the intermediary layer, the - pre, post and terminator attributes can be - used (please refer to the C# date - marshalling example for more information on these).
-The dout typemap is used for converting function - return values from the return type used in the intermediary D module to - the type returned by the proxy function. The $excode special - variable in dout typemaps is replaced by the excode - typemap attribute code if the method can throw any exceptions from - unmanaged code, otherwise by nothing (the -$imcall and $owner macros are replaced).
-The code from the ddirectorin and -ddirectorout typemaps is used for conversion in director callback - functions. Arguments are converted to the type used in the proxy class - method they are calling by using the code from ddirectorin, - the proxy class method return value is converted to the type the C++ - code expects via the ddirectorout typemap (the -$dcall and $winput macros are replaced).
+The din typemap is used for converting + function parameter types from the type used in the proxy module or + class to the type used in the intermediary D module (the +$dinput macro is replaced). To inject further parameter processing + code before or after the call to the intermediary layer, the pre +, post and terminator attributes can be used (please + refer to the C# date marshalling + example for more information on these).
+The dout typemap is used for converting + function return values from the return type used in the intermediary D + module to the type returned by the proxy function. The $excode + special variable in dout typemaps is replaced by the +excode typemap attribute code if the method can throw any + exceptions from unmanaged code, otherwise by nothing (the +$imcall and $owner macros are replaced).
+The code from the ddirectorin + and ddirectorout typemaps is used for conversion in director + callback functions. Arguments are converted to the type used in the + proxy class method they are calling by using the code from +ddirectorin, the proxy class method return value is converted to + the type the C++ code expects via the ddirectorout typemap + (the $dcall and $winput + macros are replaced).
The full chain of type conversions when a director callback is invoked looks like this:
@@ -24436,14 +26108,14 @@ ddirectorout typemaps is used for conversion in director callback ↑ ↓ dtype DClass.method(dtype a)-21.3.5 typecheck typemaps
+22.3.5 typecheck typemaps
Because, unlike many scripting languages supported by SWIG, D does not need any dynamic dispatch helper to access an overloaded function, the purpose of these is merely to issue a warning for overloaded C++ functions that cannot be overloaded in D (as more than one C++ type maps to a single D type).
-21.3.6 Code injection - typemaps
+22.3.6 Code injection typemaps +
These typemaps are used for generating the skeleton of proxy classes for C++ types.
By overriding dbase, dinterfaces or @@ -24454,13 +26126,13 @@ dinterfaces_derived, the inheritance chain of the generated proxy additional D code which will be emitted into the class body respectively the imports section of the D module the class is written to.
-dconstructor, ddestructor -, ddispose and ddispose_derived are used to generate - the class constructor, destructor and dispose() method, - respectively. The auxiliary code for handling the pointer to the C++ - object is stored in dbody and dbody_derived. You can - override them for specific types.
-21.3.7 Special variable macros
+dconstructor, +ddestructor, ddispose and ddispose_derived are + used to generate the class constructor, destructor and dispose() + method, respectively. The auxiliary code for handling the pointer to + the C++ object is stored in dbody and dbody_derived. + You can override them for specific types.
+22.3.7 Special variable macros
The standard SWIG special variables are available for use within typemaps as described in the Typemaps documentation , for example $1, $input, $result etc.
@@ -24498,11 +26170,10 @@ $*dclassname would be replaced by the proxy class name on whether the function has a return value or not. It can be used to bail out early e.g. in case of errors (return $null;). -$dinput (C#: $csinput) +$dinput (C#: $csinput) - -This variable is used in din - typemaps and is replaced by the expression which is to be passed to - C/C++.
+This variable is used in din typemaps + and is replaced by the expression which is to be passed to C/C++.
For example, this input
@@ -24520,10 +26191,10 @@ void foo(SomeClass arg) { example_im.foo(SomeClass.getCPointer(arg)); }$imcall and $owner (C#: $imcall -) +$imcall and $owner (C#: +$imcall) - These variables are used in dout +
These variables are used in dout typemaps. $imcall contains the call to the intermediary module which provides the value to be used, and $owner signals if the caller is responsible for managing the object lifetime (that is, if the @@ -24559,9 +26230,9 @@ SomeClass bar() {
$dcall and $winput (C#: $cscall, $iminput) -- These variables are used in the director-specific typemaps -ddirectorin and +
+ for details.These variables are used in the director-specific typemaps +ddirectorin and ddirectorout. They are more or less the reverse of the $imcall and $dinput macros: $dcall contains the invocation of the D proxy method of which the return value is to be @@ -24582,7 +26253,7 @@ C# documentation
$directorconnect - This macro is only valid inside the +
This macro is only valid inside the dconstructor typemap and contains the value of the dconstructor typemap attribute if the currently wrapped class has directors enabled.
@@ -24596,7 +26267,7 @@ dconstructor typemap attribute if the currently wrapped class has }$importtype(SomeDType) +$importtype(SomeDType) - This macro is used in the dimports typemap if a dependency on another D type generated by SWIG is added by a custom typemap.
@@ -24643,7 +26314,7 @@ $importtype(AnotherInterface)Contains the fully qualified name of the intermediary D module.
21.4 %features
+22.4 D and %feature
The D module defines a number of directives which modify the SWIG features set globally or for a specific declaration:
@@ -24678,7 +26349,7 @@ struct A {
21.5 Pragmas
+22.5 Pragmas
There are a few SWIG pragmas specific to the D module, which you can use to influence the D code SWIG generates:
@@ -24691,16 +26362,16 @@ struct A {
-- %pragma(d) imdmoduleimports
Additional code to be emitted to the imports section of the - intermediary D module (the $importtype + intermediary D module (the $importtype macro can be used here). You probably want to use this in conjunction with the imdmodulecode pragma.
- %pragma(d) proxydmodulecode
Just like proxydmodulecode, the argument is copied to the - proxy D module (if SWIG is in split proxy - mode and/or the nspace feature is used, it is emitted to - the main proxy D module only).
+ proxy D module (if SWIG is in split proxy mode + and/or the nspace feature is used, it is emitted to the main + proxy D module only).- %pragma(d) globalproxyimports
- @@ -24736,7 +26407,7 @@ $symbol variable is replaced by the name of the symbol in the overwritten.
21.6 D Exceptions
+22.6 D Exceptions
Out of the box, C++ exceptions are fundamentally incompatible to their equivalent in the D world and cannot simply be propagated to a calling D method. There is, however, an easy way to solve this problem: @@ -24749,7 +26420,7 @@ $symbol variable is replaced by the name of the symbol in the
As this feature is implemented in exactly the same way it is for C#, please see the C# documentation for a more detailed explanation.
-21.7 D Directors
+22.7 D Directors
When the directors feature is activated, SWIG generates extra code on both the C++ and the D side to enable cross-language polymorphism. Essentially, this means that if you subclass a proxy class in D, C++ @@ -24758,9 +26429,8 @@ $symbol variable is replaced by the name of the symbol in the
There is no D specific documentation yet, but the way the feature is implemented is very similar to how it is done in Java and C#.
-21.8 Other features
-21.8.1 Extended namespace support (nspace -)
+22.8 Other features
+22.8.1 Extended namespace support (nspace)
By default, SWIG flattens all C++ namespaces into a single target language namespace, but as for Java and C#, the nspace feature is supported for D. If it is active, C++ @@ -24768,7 +26438,7 @@ Java and C#.
for the other languages, free variables and functions are not supported yet; currently, they are all allows written to the main proxy D module. -21.8.2 Native pointer support
+22.8.2 Native pointer support
Contrary to many of the scripting languages supported by SWIG, D fully supports C-style pointers. The D module thus includes a custom mechanism to wrap C pointers directly as D pointers where applicable, @@ -24793,7 +26463,7 @@ cprimitive attribute on its dtype attribute is used. For cprimitive="1", so the code from the nativepointer attribute is taken into account e.g. for float ** or the function pointer float (*)(float *).
-21.8.3 Operator overloading
+22.8.3 Operator overloading
The D module comes with basic operator overloading support for both D1 and D2. There are, however, a few limitations arising from conceptual differences between C++ and D:
@@ -24819,7 +26489,7 @@ D2. -, or implicit casting (which was introduced in D2 via alias this ). Despite the lack of automatic support, manually handling these cases should be perfectly possible. -21.8.4 Running the test-suite
+22.8.4 Running the test-suite
As with any other language, the SWIG test-suite can be built for D using the *-d-test-suite targets of the top-level Makefile. By default, D1 is targeted, to build it with D2, use the optional @@ -24830,13 +26500,13 @@ D_VERSION variable, e.g. make check-d-test-suite D_VERSION=2 library, you might have to add -ldl manually to the d_compile target in Examples/Makefile, because GDC does not currently honor the pragma(lib,...) statement.
-21.9 D Typemap examples
+22.9 D Typemap examples
There are no D-specific typemap examples yet. However, with the above name comparison table, you should be able to get an idea what can be done by looking at the corresponding C# section.
-21.10 Work in progress and planned - features
+22.10 Work in progress and planned + features
There are a couple of features which are not implemented yet, but would be very useful and might be added in the near future:
@@ -24864,16 +26534,17 @@ corresponding C# section. issues concerning const-correctness etc.
-22 SWIG and Go
+23 SWIG and Go
@@ -24901,61 +26587,144 @@ corresponding C# section.
- Overview
+- Examples
- Running SWIG with Go
- A tour of basic C/C++ wrapping @@ -24884,15 +26555,30 @@ corresponding C# section.
- Go Enumerations
- Go Classes
- Go Templates
-- Go Director Classes
+- Go Director Classes + +
- Default Go primitive type mappings
- Output arguments
- Adding additional go code
+- Go typemaps
This chapter describes SWIG's support of Go. For more information on the Go programming language see golang.org .
-22.1 Overview
-Go is a compiled language, not a scripting language. However, it - does not support direct calling of functions written in C/C++. The cgo - program may be used to generate wrappers to call C code from Go, but - there is no convenient way to call C++ code. SWIG fills this gap.
-There are (at least) two different Go compilers. One is the gc - compiler, normally invoked under the names 6g, 8g, or 5g. The other is - the gccgo compiler, which is a frontend to the gcc compiler suite. The +
23.1 Overview
+Go does not support direct calling of functions written in C/C++. + The cgo program may be used + to generate wrappers to call C code from Go, but there is no convenient + way to call C++ code. SWIG fills this gap.
+There are (at least) two different Go compilers. The first is the gc + compiler of the Go + distribution, normally invoked via the +go tool. The second Go compiler is the + gccgo compiler, which is a frontend to the GCC compiler suite. The interface to C/C++ code is completely different for the two Go - compilers. SWIG supports both, selected by a command line option.
-Because Go is a type-safe compiled language, SWIG's runtime type - checking and runtime library are not used with Go. This should be borne - in mind when reading the rest of the SWIG documentation.
-22.2 Running SWIG with Go
-To generate Go code, use the -go option with SWIG. By - default SWIG will generate code for the gc compilers. To generate code - for gccgo, you should also use the -gccgo option.
-22.2.1 Additional Commandline Options
-These are the command line options for SWIG's GO module. They can + compilers. SWIG supports both Go compilers, selected by the -gccgo + command line option.
+Go is a type-safe compiled language and the wrapper code generated + by SWIG is type-safe as well. In case of type issues the build will + fail and hence SWIG's runtime library and +runtime type checking are not used.
+23.2 Examples
+Working examples can be found in the +SWIG source tree .
+Please note that the examples in the SWIG source tree use makefiles + with the .i SWIG interface file extension for backwards compatibility + with Go 1.
+23.3 Running SWIG with Go
+Most Go programs are built using the +go tool. Since Go 1.1 the go tool has support for SWIG. To use it, + give your SWIG interface file the extension .swig (for C code) or + .swigcxx (for C++ code). Put that file in a GOPATH/src directory as + usual for Go sources. Put other C/C++ code in the same directory with + extensions of .c and .cxx. The go build and go install + commands will automatically run SWIG for you and compile the generated + wrapper code. To check the SWIG command line options the go tool uses + run go build -x. To access the automatically generated files + run go build -work. You'll find the files under the temporary + WORK directory.
+To manually generate and compile C/C++ wrapper code for Go, use the +-go option with SWIG. By default SWIG will generate code for the Go + compiler of the Go distribution. To generate code for gccgo, you should + also use the -gccgo option.
+When using the -cgo option, SWIG will generate files that + can be used directly by go build. Starting with the Go 1.5 + distribution the -cgo option has to be given. Put your SWIG + interface file in a directory under GOPATH/src, and give it a name that + does not end in the .swig or .swigcxx extension. Typically the + SWIG interface file extension is .i in this case.
++++% swig -go -cgo example.i +% go install ++You will now have a Go package that you can import from other Go + packages as usual.
+To use SWIG without the -cgo option, more steps are + required. Recall that this only works with Go versions before 1.5. When + using Go version 1.2 or later, or when using gccgo, the code generated + by SWIG can be linked directly into the Go program. A typical command + sequence when using the Go compiler of the Go distribution would look + like this:
++++% swig -go example.i +% gcc -c code.c # The C library being wrapped. +% gcc -c example_wrap.c +% go tool 6g example.go +% go tool 6c example_gc.c +% go tool pack grc example.a example.6 example_gc.6 code.o example_wrap.o +% go tool 6g main.go +% go tool 6l main.6 ++You can also put the wrapped code into a shared library, and when + using the Go versions before 1.2 this is the only supported option. A + typical command sequence for this approach would look like this:
++++% swig -go -use-shlib example.i +% gcc -c -fpic example.c +% gcc -c -fpic example_wrap.c +% gcc -shared example.o example_wrap.o -o example.so +% go tool 6g example.go +% go tool 6c example_gc.c +% go tool pack grc example.a example.6 example_gc.6 +% go tool 6g main.go # your code, not generated by SWIG +% go tool 6l main.6 ++23.3.1 Go-specific Commandline Options
+These are the command line options for SWIG's Go module. They can also be seen by using:
-swig -go -help-
- Go specific options + -intgo-type-size %lt;s%gt; Set the size for the Go type -int. This controls the size that the C/C++ code expects to see. The - %lt;s%gt; argument should be 32 or 64. This option is currently - required during the transition from Go 1.0 to Go 1.1, as the size of -int on 64-bit x86 systems changes between those releases (from 32 - bits to 64 bits). In the future the option may become optional, and - SWIG will assume that the size of int is the size of a C - pointer. +
-+ Go-specific options + -cgo Generate files to be used as input for the Go cgo + tool. This option is required for Go 1.5 and later, and works for Go + 1.2 and later. In the future this option will likely become the + default. -intgosize <s> Set the size for the Go type int +. This controls the size that the C/C++ code expects to see. The <s> + argument should be 32 or 64. This option is currently required during + the transition from Go 1.0 to Go 1.1, as the size of int on + 64-bit x86 systems changes between those releases (from 32 bits to 64 + bits). In the future the option may become optional, and SWIG will + assume that the size of int is the size of a C pointer. + generate code for the Go compiler of the Go distribution. -gccgo Generate code for gccgo. The default is to - generate code for 6g/8g/5g. - -package <name> Set the name of the Go package to <name>. The default package name is the SWIG module name. -soname %lt;name%gt; Set the runtime name of the shared + + -use-shlib Tell SWIG to emit code that uses a shared + library. This is only meaningful for the Go compiler of the Go + distribution, which needs to know at compile time whether a shared + library will be used. + generating code for the Go compiler of the Go distribution; when using + gccgo, the equivalent name will be taken from the -soname <name> Set the runtime name of the shared library that the dynamic linker should include at runtime. The default is the package name with ".so" appended. This is only used when - generating code for 6g/8g/5g; when using gccgo, the equivalent name - will be taken from the -soname
option passed to the - linker.-soname
+ option passed to the linker. Using this option implies the -use-shlib + option. +-go-pkgpath <pkgpath> When generating code for gccgo, + set the pkgpath to use. This corresponds to the -fgo-pkgpath + option to gccgo. - -go-prefix <prefix> When generating code for gccgo, set the prefix to use. This corresponds to the -fgo-prefix option - to gccgo. + to gccgo. If -go-pkgpath is used, -go-prefix will be + ignored. -long-type-size <s> Set the size for the C/C++ type -long. This controls whether long is converted to the Go - type int32 or int64. The <s> argument should be 32 or - 64. 22.2.2 Go Output Files
-When generating Go code, SWIG will generate the following files:
+23.3.2 Generated Wrapper Files
+There are two different approaches to generating wrapper files, + controlled by SWIG's -cgo option. The -cgo option + works with Go version 1.2 or later. It is required when using Go + version 1.5 or later.
+With or without the -cgo option, SWIG will generate the + following files when generating wrapper code:
-
- MODULE.go will contain the Go functions that your Go code will call. These functions will be wrappers for the C++ functions defined by @@ -24963,43 +26732,31 @@ long. This controls whether long is converted to the Go compiler.
- MODULE_wrap.c or MODULE_wrap.cxx will contain C/C++ functions will be invoked by the Go wrapper code. This file should be compiled with - the usual C or C++ compiler and linked into a shared library.
+ the usual C or C++ compiler.- MODULE_wrap.h will be generated if you use the directors feature. It provides a definition of the generated C++ director classes. It is generally not necessary to use this file, but in some special cases it may be helpful to include it in your code, compiled with the usual C or C++ compiler.
-- If using the gc compiler, MODULE_gc.c will contain C code which - should be compiled with the C compiler distributed as part of the gc - compiler: 6c, 8c, or 5c. It should then be combined with the compiled - MODULE.go using gopack. This file will not be generated when using - gccgo.
A typical command sequence would look like this:
----% swig -go example.i -% gcc -c -fpic example.c -% gcc -c -fpic example_wrap.c -% gcc -shared example.o example_wrap.o -o example.so -% 6g example.go -% 6c example_gc.c -% gopack grc example.a example.6 example_gc.6 -% 6g main.go # your code, not generated by SWIG -% 6l main.6 --22.3 A tour of basic C/C++ wrapping
+When neither the -cgo nor the -gccgo option is + used, SWIG will also generate an additional file:
++
+- MODULE_gc.c will contain C code which should be compiled with the C + compiler distributed as part of the gc compiler. It should then be + combined with the compiled MODULE.go using go tool pack.
+23.4 A tour of basic C/C++ wrapping
By default, SWIG attempts to build a natural Go interface to your C/C++ code. However, the languages are somewhat different, so some modifications have to occur. This section briefly covers the essential aspects of this wrapping.
-22.3.1 Go Package Name
+23.4.1 Go Package Name
All Go source code lives in a package. The name of this package will default to the name of the module from SWIG's %module directive. You may override this by using SWIG's -package command line option.
-22.3.2 Go Names
+23.4.2 Go Names
In Go, a function is only visible outside the current package if the first letter of the name is uppercase. This is quite different from C/C++. Because of this, C/C++ names are modified when generating the Go @@ -25019,16 +26776,16 @@ long. This controls whether long is converted to the Go the name of a type in Go. A constructor will be named New followed by that name, and the destructor will be named Delete followed by that name.
-22.3.3 Go Constants
+23.4.3 Go Constants
C/C++ constants created via #define or the %constant directive become Go constants, declared with a const declaration.
-22.3.4 Go Enumerations
+23.4.4 Go Enumerations
C/C++ enumeration types will cause SWIG to define an integer type with the name of the enumeration (with first letter forced to uppercase as usual). The values of the enumeration will become variables in Go; code should avoid modifying those variables.
-22.3.5 Go Classes
+23.4.5 Go Classes
Go has interfaces, methods and inheritance, but it does not have classes in the same sense as C++. This sections describes how SWIG represents C++ classes represented in Go.
@@ -25077,7 +26834,7 @@ type MyClass interface { MyMethod() int } -MyClassMyFactoryFunction() MyClass { +func MyClassMyFactoryFunction() MyClass { // swig magic here } @@ -25085,47 +26842,544 @@ MyClassMyFactoryFunction() MyClass {Note that the factory function does not return a go pointer; it actually returns a go interface. If the returned pointer can be null, you can check for this by calling the Swigcptr() method.
-22.3.5.1 Go Class Inheritance
+23.4.5.1 Go Class Memory Management
+Calling NewClassName for a C++ class ClassName + will allocate memory using the C++ memory allocator. This memory will + not be automatically freed by Go's garbage collector as the object + ownership is not tracked. When you are done with the C++ object you + must free it using DeleteClassName. +
+
+
The most Go idiomatic way to manage the memory for some C++ class + is to call NewClassName followed by a +defer of the DeleteClassName call. Using defer + ensures that the memory of the C++ object is freed as soon as the + function containing the defer statement returns. Furthemore +defer works great for short-lived objects and fits nicely C++'s + RAII idiom. Example:+++func UseClassName(...) ... { + o := NewClassName(...) + defer DeleteClassName(o) + // Use the ClassName object + return ... +} ++With increasing complexity, especially complex C++ object + hierarchies, the correct placement of defer statements becomes + harder and harder as C++ objects need to be freed in the correct order. + This problem can be eased by keeping a C++ object function local so + that it is only available to the function that creates a C++ object and + functions called by this function. Example:
++++func WithClassName(constructor args, f func(ClassName, ...interface{}) error, data ...interface{}) error { + o := NewClassName(constructor args) + defer DeleteClassName(o) + return f(o, data...) +} + +func UseClassName(o ClassName, data ...interface{}) (err error) { + // Use the ClassName object and additional data and return error. +} + +func main() { + WithClassName(constructor args, UseClassName, additional data) +} ++Using defer has limitations though, especially when it + comes to long-lived C++ objects whichs lifetimes are hard to predict. + For such C++ objects a common technique is to store the C++ object into + a Go object, and to use the Go function runtime.SetFinalizer + to add a finalizer which frees the C++ object when the Go object is + freed. It is strongly recommended to read the +runtime.SetFinalizer documentation before using this technique to + understand the runtime.SetFinalizer limitations. +
+Common pitfalls with runtime.SetFinalizer are:
++
+- If a hierarchy of C++ objects will be automatically freed by Go + finalizers then the Go objects that store the C++ objects need to + replicate the hierarchy of the C++ objects to prevent that C++ objects + are freed prematurely while other C++ objects still rely on them.
+- The usage of Go finalizers is problematic with C++'s RAII idiom as + it isn't predictable when the finalizer will run and this might require + a Close or Delete method to be added the Go object that stores a C++ + object to mitigate.
+- The Go finalizer function typically runs in a different OS thread + which can be problematic with C++ code that uses thread-local storage.
+runtime.SetFinalizer Example:
++++import ( + "runtime" + "wrap" // SWIG generated wrapper code +) + +type GoClassName struct { + wcn wrap.ClassName +} + +func NewGoClassName() *GoClassName { + o := &GoClassName{wcn: wrap.NewClassName()} + runtime.SetFinalizer(o, deleteGoClassName) + return o +} + +func deleteGoClassName(o *GoClassName) { + // Runs typically in a different OS thread! + wrap.DeleteClassName(o.wcn) + o.wcn = nil +} + +func (o *GoClassName) Close() { + // If the C++ object has a Close method. + o.wcn.Close() + + // If the GoClassName object is no longer in an usable state. + runtime.SetFinalizer(o, nil) // Remove finalizer. + deleteGoClassName() // Free the C++ object. +} ++23.4.5.2 Go Class Inheritance
C++ class inheritance is automatically represented in Go due to its use of interfaces. The interface for a child class will be a superset of the interface of its parent class. Thus a value of the child class type in Go may be passed to a function which expects the parent class. Doing the reverse will require an explicit type assertion, which will be checked dynamically.
-22.3.6 Go Templates
+23.4.6 Go Templates
In order to use C++ templates in Go, you must tell SWIG to create wrappers for a particular template instantation. To do this, use the %template directive.
-22.3.7 Go Director Classes
+23.4.7 Go Director Classes
SWIG's director feature permits a Go type to act as the subclass of - a C++ class with virtual methods. This is complicated by the fact that - C++ and Go define inheritance differently. In Go, structs can inherit - methods via anonymous field embedding. However, when a method is called - for an embedded struct, if that method calls any other methods, they - are called for the embedded struct, not for the original type. - Therefore, SWIG must use Go interfaces to represent C++ inheritance.
-In order to use the director feature in Go, you must define a type - in your Go code. You must then add methods for the type. Define a - method in Go for each C++ virtual function that you want to override. - You must then create a value of your new type, and pass a pointer to it - to the function NewDirectorClassName, where ClassName - is the name of the C++ class. That will return a value of type -ClassName.
-For example:
+ a C++ class. This is complicated by the fact that C++ and Go define + inheritance differently. SWIG normally represents the C++ class + inheritance automatically in Go via interfaces but with a Go type + representing a subclass of a C++ class some manual work is necessary. +This subchapter gives a step by step guide how to properly sublass a + C++ class with a Go type. In general it is strongly recommended to + follow this guide completely to avoid common pitfalls with directors in + Go.
+23.4.7.1 Example C++ code
+The step by step guide is based on two example C++ classes. + FooBarAbstract is an abstract C++ class and the FooBarCpp class + inherits from it. This guide explains how to implement a FooBarGo class + similar to the FooBarCpp class.
+FooBarAbstract abstract C++ class:
++++class FooBarAbstract +{ +public: + FooBarAbstract() {}; + virtual ~FooBarAbstract() {}; + + std::string FooBar() { + return this->Foo() + ", " + this->Bar(); + }; + +protected: + virtual std::string Foo() { + return "Foo"; + }; + + virtual std::string Bar() = 0; +}; ++FooBarCpp C++ class:
++++class FooBarCpp : public FooBarAbstract +{ +protected: + virtual std::string Foo() { + return "C++ " + FooBarAbstract::Foo(); + } + + virtual std::string Bar() { + return "C++ Bar"; + } +}; ++Returned string by the FooBarCpp::FooBar method is:
++++C++ Foo, C++ Bar ++The complete example, including the FooBarGoo class + implementation, can be found in +the end of the guide.
+23.4.7.2 Enable director feature
+The director feature is disabled by default. To use directors you + must make two changes to the interface file. First, add the "directors" + option to the %module directive, like this:
++++%module(directors="1") modulename ++Second, you must use the %feature("director") directive to tell SWIG + which classes should get directors. In the example the FooBarAbstract + class needs the director feature enabled so that the FooBarGo class can + inherit from it, like this:
++++%feature("director") FooBarAbstract; ++For a more detailed documentation of the director feature and how to + enable or disable it for specific classes and virtual methods see + SWIG's Java documentation on directors.
+23.4.7.3 Constructor and destructor +
+SWIG creates an additional set of constructor and destructor + functions once the director feature has been enabled for a C++ class. +NewDirectorClassName allows overriding virtual methods on the new + object instance and DeleteDirectorClassName needs to be used + to free a director object instance created with +NewDirectorClassName. More on overriding virtual methods follows + later in this guide under overriding + virtual methods.
+The default constructor and destructor functions NewClassName + and DeleteClassName can still be used as before so that + existing code doesn't break just because the director feature has been + enabled for a C++ class. The behavior is undefined if the default and + director constructor and destructor functions get mixed and so great + care needs to be taken that only one of the constructor and destructor + function pairs is used for any object instance. Both constructor + functions, the default and the director one, return the same interface + type. This makes it potentially hard to know which destructor function, + the default or the director one, needs to be called to delete an object + instance.
+In theory the DirectorInterface method could be used + to determine if an object instance was created via +NewDirectorClassName:
++++if o.DirectorInterface() != nil { + DeleteDirectorClassName(o) +} else { + DeleteClassName(o) +} ++In practice it is strongly recommended to embed a director + object instance in a Go struct so that a director object instance will + be represented as a distinct Go type that subclasses a C++ class. For + this Go type custom constructor and destructor functions take care of + the director constructor and destructor function calls and the + resulting Go class will appear to the user as any other SWIG wrapped + C++ class. More on properly subclassing a C++ class follows later in + this guide under subclass via embedding +.
+23.4.7.4 Override virtual methods +
+In order to override virtual methods on a C++ class with Go methods + the NewDirectorClassName constructor functions receives a +DirectorInterface argument. The methods in the +DirectorInterface are a subset of the public and protected virtual + methods of the C++ class. If the DirectorInterface contains a + method with a matching signature to a virtual method of the C++ class + then the virtual C++ method will be overwritten with the Go method. As + Go doesn't support protected methods all overriden protected virtual + C++ methods will be public in Go.
+As an example see part of the FooBarGo class:
++++type overwrittenMethodsOnFooBarAbstract struct { + fb FooBarAbstract +} + +func (om *overwrittenMethodsOnFooBarAbstract) Foo() string { + ... +} + +func (om *overwrittenMethodsOnFooBarAbstract) Bar() string { + ... +} + +func NewFooBarGo() FooBarGo { + om := &overwrittenMethodsOnFooBarAbstract{} + fb := NewDirectorFooBarAbstract(om) + om.fb = fb + ... +} ++The complete example, including the FooBarGoo class + implementation, can be found in +the end of the guide. In this part of the example the virtual + methods FooBarAbstract::Foo and FooBarAbstract::Bar + have been overwritten with Go methods similarly to how the +FooBarAbstract virtual methods are overwritten by the FooBarCpp + class.
+The DirectorInterface in the example is implemented by the +overwrittenMethodsOnFooBarAbstract Go struct type. A pointer to a +overwrittenMethodsOnFooBarAbstract struct instance will be given to + the NewDirectorFooBarAbstract constructor function. The + constructor return value implements the FooBarAbstract + interface. overwrittenMethodsOnFooBarAbstract could in theory + be any Go type but in practice a struct is used as it typically + contains at least a value of the C++ class interface so that the + overwritten methods can use the rest of the C++ class. If the +FooBarGo class would receive additional constructor arguments then + these would also typically be stored in the +overwrittenMethodsOnFooBarAbstract struct so that they can be used + by the Go methods.
+23.4.7.5 Call base methods
+Often a virtual method will be overwritten to extend the original + behavior of the method in the base class. This is also the case for the + FooBarCpp::Foo method of the example code:
++++virtual std::string Foo() { + return "C++ " + FooBarAbstract::Foo(); +} ++To use base methods the DirectorClassNameMethodName wrapper + functions are automatically generated by SWIG for public and protected + virtual methods. The FooBarGo.Foo implementation in the + example looks like this:
++++func (om *overwrittenMethodsOnFooBarAbstract) Foo() string { + return "Go " + DirectorFooBarAbstractFoo(om.fb) +} ++The complete example, including the FooBarGoo class + implementation, can be found in +the end of the guide.
+23.4.7.6 Subclass via embedding
+As previously mentioned in this + guide the default and director constructor functions return the + same interface type. To properly subclass a C++ class with a Go type + the director object instance returned by the NewDirectorClassName + constructor function should be embedded into a Go struct so that it + represents a distinct but compatible type in Go's type system. This Go + struct should be private and the constructor and destructor functions + should instead work with a public interface type so that the Go class + that subclasses a C++ class can be used as a compatible drop in.
+The subclassing part of the FooBarGo class for an example + looks like this:
++++type FooBarGo interface { + FooBarAbstract + deleteFooBarAbstract() + IsFooBarGo() +} + +type fooBarGo struct { + FooBarAbstract +} + +func (fbgs *fooBarGo) deleteFooBarAbstract() { + DeleteDirectorFooBarAbstract(fbgs.FooBarAbstract) +} + +func (fbgs *fooBarGo) IsFooBarGo() {} + +func NewFooBarGo() FooBarGo { + om := &overwrittenMethodsOnFooBarAbstract{} + fb := NewDirectorFooBarAbstract(om) + om.fb = fb + + return &fooBarGo{FooBarAbstract: fb} +} + +func DeleteFooBarGo(fbg FooBarGo) { + fbg.deleteFooBarAbstract() +} ++The complete example, including the FooBarGoo class + implementation, can be found in +the end of the guide. In this part of the example the private +fooBarGo struct embeds FooBarAbstract which lets the +fooBarGo Go type "inherit" all the methods of the +FooBarAbstract C++ class by means of embedding. The public +FooBarGo interface type includes the FooBarAbstract + interface and hence FooBarGo can be used as a drop in + replacement for FooBarAbstract while the reverse isn't + possible and would raise a compile time error. Furthemore the + constructor and destructor functions NewFooBarGo and +DeleteFooBarGo take care of all the director specifics and to the + user the class appears as any other SWIG wrapped C++ class.
+23.4.7.7 Memory management with + runtime.SetFinalizer
+In general all guidelines for C++ class + memory management apply as well to director classes. One often + overlooked limitation with runtime.SetFinalizer is that a + finalizer doesn't run in case of a cycle and director classes typically + have a cycle. The cycle in the FooBarGo class is here:
++++type overwrittenMethodsOnFooBarAbstract struct { + fb FooBarAbstract +} + +func NewFooBarGo() FooBarGo { + om := &overwrittenMethodsOnFooBarAbstract{} + fb := NewDirectorFooBarAbstract(om) // fb.v = om + om.fb = fb // Backlink causes cycle as fb.v = om! + ... +} ++In order to be able to use runtime.SetFinalizer + nevertheless the finalizer needs to be set on something that isn't in a + cycle and that references the director object instance. In the +FooBarGo class example the FooBarAbstract director + instance can be automatically deleted by setting the finalizer on +fooBarGo:
++++type fooBarGo struct { + FooBarAbstract +} + +type overwrittenMethodsOnFooBarAbstract struct { + fb FooBarAbstract +} + +func NewFooBarGo() FooBarGo { + om := &overwrittenMethodsOnFooBarAbstract{} + fb := NewDirectorFooBarAbstract(om) + om.fb = fb // Backlink causes cycle as fb.v = om! + + fbgs := &fooBarGo{FooBarAbstract: fb} + runtime.SetFinalizer(fbgs, FooBarGo.deleteFooBarAbstract) + return fbgs +} ++Furthermore if runtime.SetFinalizer is in use either the +DeleteClassName destructor function needs to be removed or the +fooBarGo struct needs additional data to prevent double deletion. + Please read the C++ class memory management + subchapter before using runtime.SetFinalizer to know all of + its gotchas.
+23.4.7.8 Complete FooBarGo + example class
+The complete and annotated FooBarGo class looks like this:
--type GoClass struct { } -func (p *GoClass) VirtualFunction() { } -func MakeClass() ClassName { - return NewDirectorClassName(&GoClass{}) +// FooBarGo is a superset of FooBarAbstract and hence FooBarGo can be used as a +// drop in replacement for FooBarAbstract but the reverse causes a compile time +// error. +type FooBarGo interface { + FooBarAbstract + deleteFooBarAbstract() + IsFooBarGo() +} + +// Via embedding fooBarGo "inherits" all methods of FooBarAbstract. +type fooBarGo struct { + FooBarAbstract +} + +func (fbgs *fooBarGo) deleteFooBarAbstract() { + DeleteDirectorFooBarAbstract(fbgs.FooBarAbstract) +} + +// The IsFooBarGo method ensures that FooBarGo is a superset of FooBarAbstract. +// This is also how the class hierarchy gets represented by the SWIG generated +// wrapper code. For an instance FooBarCpp has the IsFooBarAbstract and +// IsFooBarCpp methods. +func (fbgs *fooBarGo) IsFooBarGo() {} + +// Go type that defines the DirectorInterface. It contains the Foo and Bar +// methods that overwrite the respective virtual C++ methods on FooBarAbstract. +type overwrittenMethodsOnFooBarAbstract struct { + // Backlink to FooBarAbstract so that the rest of the class can be used by + // the overridden methods. + fb FooBarAbstract + + // If additional constructor arguments have been given they are typically + // stored here so that the overriden methods can use them. +} + +func (om *overwrittenMethodsOnFooBarAbstract) Foo() string { + // DirectorFooBarAbstractFoo calls the base method FooBarAbstract::Foo. + return "Go " + DirectorFooBarAbstractFoo(om.fb) +} + +func (om *overwrittenMethodsOnFooBarAbstract) Bar() string { + return "Go Bar" +} + +func NewFooBarGo() FooBarGo { + // Instantiate FooBarAbstract with selected methods overridden. The methods + // that will be overwritten are defined on + // overwrittenMethodsOnFooBarAbstract and have a compatible signature to the + // respective virtual C++ methods. Furthermore additional constructor + // arguments will be typically stored in the + // overwrittenMethodsOnFooBarAbstract struct. + om := &overwrittenMethodsOnFooBarAbstract{} + fb := NewDirectorFooBarAbstract(om) + om.fb = fb // Backlink causes cycle as fb.v = om! + + fbgs := &fooBarGo{FooBarAbstract: fb} + // The memory of the FooBarAbstract director object instance can be + // automatically freed once the FooBarGo instance is garbage collected by + // uncommenting the following line. Please make sure to understand the + // runtime.SetFinalizer specific gotchas before doing this. Furthemore + // DeleteFooBarGo should be deleted if a finalizer is in use or the fooBarGo + // struct needs additional data to prevent double deletion. + // runtime.SetFinalizer(fbgs, FooBarGo.deleteFooBarAbstract) + return fbgs +} + +// Recommended to be removed if runtime.SetFinalizer is in use. +func DeleteFooBarGo(fbg FooBarGo) { + fbg.deleteFooBarAbstract() }Any call in C++ code to the virtual function will wind up calling - the method defined in Go. The Go code may of course call other methods - on itself, and those methods may be defined either in Go or in C++.
-22.3.8 Default Go primitive - type mappings
+Returned string by the FooBarGo.FooBar method is:
++++Go Foo, Go Bar ++For comparison the FooBarCpp class looks like this:
++++class FooBarCpp : public FooBarAbstract +{ +protected: + virtual std::string Foo() { + return "C++ " + FooBarAbstract::Foo(); + } + + virtual std::string Bar() { + return "C++ Bar"; + } +}; ++For comparison the returned string by the FooBarCpp::FooBar + method is:
++++C++ Foo, C++ Bar ++The complete source of this example can be found under + SWIG/Examples/go/director/.
+23.4.8 Default Go primitive + type mappings
The following table lists the default type mapping from C/C++ to Go. This table will tell you which Go type to expect for a function which uses a given C/C++ type.
@@ -25139,10 +27393,8 @@ func MakeClass() ClassName {unsigned short uint16 int int - unsigned int uint - long int32 or int64, depending on -long-type-size - + unsigned long uint32 or uint64, depending on --long-type-size + long int64 unsigned long uint64 long long int64 unsigned long long uint64 @@ -25159,7 +27411,7 @@ func MakeClass() ClassName { float float32 These type mappings are defined by the "gotype" typemap. You may change that typemap, or add new values, to control how C/C++ types are mapped into Go types.
-22.3.9 Output arguments
+23.4.9 Output arguments
Because of limitations in the way output arguments are processed in swig, a function with output arguments will not have multiple return values. Instead, you must pass a pointer into the C++ function to tell @@ -25207,8 +27459,8 @@ fraction := modulename.Modf(5.0, ptr) void f(char *output); -
22.3.10 Adding additional go - code
+23.4.10 Adding additional go + code
Often the APIs generated by swig are not very natural in go, especially if there are output arguments. You can insert additional go wrapping code to add new APIs with
-%insert(go_wrapper)
, @@ -25274,14 +27526,93 @@ func (arg SwigcptrWrapped_MyClass) GetAValue() (int, bool) { just a few, then you might as well define your own struct that includes the swig-wrapped object, instead of adding methods to the swig-generated object.This only works if your wrappers do not need to import other go - modules. There is at present no way to insert import statements in the - correct place in swig-generated go. If you need to do that, you must - put your go code in a separate file.
-
+If you need to import other go packages, you can do this with
++%go_import
. For example,+++%go_import("fmt", _ "unusedPackage", rp "renamed/package") + +%insert(go_wrapper) %{ - -+23 SWIG and Guile
+func foo() { + fmt.Println("Some string:", rp.GetString()) +} + +// Importing the same package twice is permitted, +// Go code will be generated with only the first instance of the import. +%go_import("fmt") + +%insert(go_wrapper) %{ + +func bar() { + fmt.Println("Hello world!") +} + +%} +23.4.11 Go typemaps
+You can use the %typemap directive to modify SWIG's default + wrapping behavior for specific C/C++ types. You need to be familiar + with the material in the general "Typemaps" + chapter. That chapter explains how to define a typemap. This section + describes some specific typemaps used for Go.
+In general type conversion code may be written either in C/C++ or in + Go. The choice to make normally depends on where memory should be + allocated. To allocate memory controlled by the Go garbage collector, + write Go code. To allocate memory in the C/C++ heap, write C code.
++
++ Typemap Description + gotype The Go type to use for a C++ type. This type + will appear in the generated Go wrapper function. If this is not + defined SWIG will use a default as +described above. + imtype An intermediate Go type used by the "goin", + "goout", "godirectorin", and "godirectorout" typemaps. If this typemap + is not defined for a C/C++ type, the gotype typemape will be used. This + is useful when gotype is best converted to C/C++ using Go code. + goin Go code to convert from gotype to imtype when + calling a C/C++ function. SWIG will then internally convert imtype to a + C/C++ type and pass it down. If this is not defined, or is the empty + string, no conversion is done. + in C/C++ code to convert the internally generated C/C++ + type, based on imtype, into the C/C++ type that a function call + expects. If this is not defined the value will simply be cast to the + desired type. + out C/C++ code to convert the C/C++ type that a + function call returns into the internally generated C/C++ type, based + on imtype, that will be returned to Go. If this is not defined the + value will simply be cast to the desired type. + goout Go code to convert a value returned from a C/C++ + function from imtype to gotype. If this is not defined, or is the empty + string, no conversion is done. + argout C/C++ code to adjust an argument value when + returning from a function. This is called after the real C/C++ function + has run. This uses the internally generated C/C++ type, based on + imtype. This is only useful for a pointer type of some sort. If this is + not defined nothing will be done. + goargout Go code to adjust an argument value when + returning from a function. This is called after the real C/C++ function + has run. The value will be in imtype. This is only useful for a pointer + type of some sort. If this is not defined, or is the empty string, + nothing will be done. + directorin C/C++ code to convert the C/C++ type used to + call a director method into the internally generated C/C++ type, based + on imtype, that will be passed to Go. If this is not defined the value + will simply be cast to the desired type. + godirectorin Go code to convert a value used to call a + director method from imtype to gotype. If this is not defined, or is + the empty string, no conversion is done. + godirectorout Go code to convert a value returned from + a director method from gotype to imtype. If this is not defined, or is + the empty string, no conversion is done. + directorout C/C++ code to convert a value returned from + a director method from the internally generated C/C++ type, based on + imtype, into the type that the method should return If this is not + defined the value will simply be cast to the desired type.
+24 SWIG and Guile
@@ -25319,7 +27650,7 @@ func (arg SwigcptrWrapped_MyClass) GetAValue() (int, bool) {This section details guile-specific support in SWIG.
-23.1 Supported Guile Versions
+24.1 Supported Guile Versions
SWIG works with Guile versions 1.8.x and 2.0.x. Support for version 1.6.x has been dropped. The last version of SWIG that still works with Guile version 1.6.x is SWIG 2.0.9.
@@ -25327,11 +27658,11 @@ func (arg SwigcptrWrapped_MyClass) GetAValue() (int, bool) { for improved performance. This is currently not tested with swig so your mileage may vary. To be safe set environment variable GUILE_AUTO_COMPILE to 0 when using swig generated guile code. -23.2 Meaning of "Module"
+24.2 Meaning of "Module"
There are three different concepts of "module" involved, defined separately for SWIG, Guile, and Libtool. To avoid horrible confusion, we explicitly prefix the context, e.g., "guile-module".
-23.3 Old GH Guile API
+24.3 Old GH Guile API
Guile 1.8 and older could be interfaced using two different api's, the SCM or the GH API. The GH interface to guile is deprecated. Read more about why in the @@ -25340,12 +27671,12 @@ Guile manual.
from SWIG. The last version of SWIG that can still generate guile GH wrapper code is 2.0.9. Please use that version if you really need the GH wrapper code. -23.4 Linkage
+24.4 Linkage
Guile support is complicated by a lack of user community cohesiveness, which manifests in multiple shared-library usage conventions. A set of policies implementing a usage convention is called a linkage.
-23.4.1 Simple Linkage
+24.4.1 Simple Linkage
The default linkage is the simplest; nothing special is done. In this case the function
@@ -25395,8 +27726,8 @@ inner_main() function. See the "simple" and "matrix"SWIG_init()
is exported. Simple linkage can be used in several ways:(module-map (lambda (sym var) - (module-export! (current-module) (list sym))) - (current-module)) + (module-export! (current-module) (list sym))) + (current-module))SWIG can also generate this Scheme stub (from
define-module
@@ -25422,13 +27753,13 @@ export form.)If you want to include several SWIG modules, you would need to rename
-SWIG_init
via a preprocessor define to avoid symbol clashes. For this case, however, passive linkage is available.23.4.2 Passive Linkage
+24.4.2 Passive Linkage
Passive linkage is just like simple linkage, but it generates an initialization function whose name is derived from the module and package name (see below).
You should use passive linkage rather than simple linkage when you are using multiple modules.
-23.4.3 Native Guile Module Linkage
+24.4.3 Native Guile Module Linkage
SWIG can also generate wrapper code that does all the Guile module declarations on its own if you pass it the
@@ -25459,7 +27790,7 @@ inner_main() function. --Linkage module
command-line option.23.4.4 Old Auto-Loading Guile Module Linkage
+24.4.4 Old Auto-Loading Guile Module Linkage
Guile used to support an autoloading facility for object-code modules. This support has been marked deprecated in version 1.4.1 and is going to disappear sooner or later. SWIG still supports building @@ -25478,7 +27809,7 @@ scm_init_my_modules_foo_module,
When invoked with the
--Linkage ltdlmod
command-line option, SWIG generates an exported module initialization function with an appropriate name.23.4.5 Hobbit4D Linkage
+24.4.5 Hobbit4D Linkage
The only other linkage supported at this time creates shared object libraries suitable for use by hobbit's
-(hobbit4d link)
guile module. This is called the "hobbit" linkage, and requires also @@ -25494,14 +27825,14 @@ swig -guile -package my/lib -module foo foo.i case foo.i declares the module to be "foo"). The installed files are my/lib/libfoo.so.X.Y.Z and friends. This scheme is still very experimental; the (hobbit4d link) conventions are not well understood.23.5 Underscore Folding
+24.5 Underscore Folding
Underscores are converted to dashes in identifiers. Guile support may grow an option to inhibit this folding in the future, but no one has complained so far.
You can use the SWIG directives
-%name
and%rename
to specify the Guile name of the wrapped functions and variables (see CHANGES).23.6 Typemaps
+24.6 Typemaps
The Guile module handles all types via typemaps. This information is read from
@@ -25568,7 +27899,7 @@ receive. The latter is available if you issueLib/guile/typemaps.i
. Some non-standard typemap substitutions are supported:(use-modules must be called, the constant will appear as a scheme variable. See Features and the %feature directive for info on how to apply the %feature. -
, passing a pointer to a struct representing the The run-time type checker. If the Scheme object passed was not a SWIG smob representing a compatible pointer, a23.7 Representation of pointers as smobs
+24.7 Representation of pointers as smobs
For pointer types, SWIG uses Guile smobs. SWIG smobs print like this:
@@ -25582,7 +27913,7 @@ SWIG_ConvertPtr()#<swig struct xyzzy * 0x1234affe>
Two of them areequal?
if and only if they have the same type and value.wrong-type-arg
exception is raised. -23.7.1 Smobs
+24.7.1 Smobs
In earlier versions of SWIG, C pointers were represented as Scheme strings containing a hexadecimal rendering of the pointer value and a mangled type name. As Guile allows registering user types, so-called @@ -25596,7 +27927,7 @@ The run-time type checker. If the Scheme object passed was not a object and the second word of data is the swig_type_info * structure describing this type. If a generated GOOPS module has been loaded, smobs will be wrapped by the corresponding GOOPS class.
-23.7.2 Garbage Collection
+24.7.2 Garbage Collection
Garbage collection is a feature of Guile since version 1.6. As SWIG now requires Guile > 1.8, it is automatically included. Garbage collection works like this. Every swig_type_info structure stores in @@ -25610,25 +27941,25 @@ The run-time type checker. If the Scheme object passed was not a Object ownership and %newobject in the SWIG manual. All typemaps use an $owner var, and the guile module replaces $owner with 0 or 1 depending on feature:new.
-23.8 Exception Handling
+24.8 Exception Handling
SWIG code calls
scm_error
on exception, using the following mapping:- MAP(SWIG_MemoryError, "swig-memory-error"); - MAP(SWIG_IOError, "swig-io-error"); - MAP(SWIG_RuntimeError, "swig-runtime-error"); - MAP(SWIG_IndexError, "swig-index-error"); - MAP(SWIG_TypeError, "swig-type-error"); - MAP(SWIG_DivisionByZero, "swig-division-by-zero"); - MAP(SWIG_OverflowError, "swig-overflow-error"); - MAP(SWIG_SyntaxError, "swig-syntax-error"); - MAP(SWIG_ValueError, "swig-value-error"); - MAP(SWIG_SystemError, "swig-system-error"); + MAP(SWIG_MemoryError, "swig-memory-error"); + MAP(SWIG_IOError, "swig-io-error"); + MAP(SWIG_RuntimeError, "swig-runtime-error"); + MAP(SWIG_IndexError, "swig-index-error"); + MAP(SWIG_TypeError, "swig-type-error"); + MAP(SWIG_DivisionByZero, "swig-division-by-zero"); + MAP(SWIG_OverflowError, "swig-overflow-error"); + MAP(SWIG_SyntaxError, "swig-syntax-error"); + MAP(SWIG_ValueError, "swig-value-error"); + MAP(SWIG_SystemError, "swig-system-error");The default when not specified here is to use "swig-error". See Lib/exception.i for details.
-23.9 Procedure documentation
+24.9 Procedure documentation
If invoked with the command-line option
-procdoc file
, SWIG creates documentation strings for the generated wrapper functions, describing the procedure signature and return value, and @@ -25656,7 +27987,7 @@ The run-time type checker. If the Scheme object passed was not aDocumentation strings can be configured using the Guile-specific typemap argument
-doc
. SeeLib/guile/typemaps.i
for details.23.10 Procedures with setters
+24.10 Procedures with setters
For global variables, SWIG creates a single wrapper procedure
-( variable :optional value)
, which is used for both getting and setting the value. For struct members, SWIG creates two wrapper @@ -25678,7 +28009,7 @@ variable is created, so you can use(variable struct members, the procedures
(struct-member -get pointer)
and(struct-member-set pointer value)
are not generated.23.11 GOOPS Proxy Classes
+24.11 GOOPS Proxy Classes
SWIG can also generate classes and generic functions for use with Guile's Object-Oriented Programming System (GOOPS). GOOPS is a sophisticated object system in the spirit of the Common Lisp Object @@ -25816,7 +28147,7 @@ module.scm file in the directory specified by -outdir or the
Notice that <Foo> is used before it is defined. The fix is to just put the
-%import "foo.h"
before the%inline
block.23.11.1 Naming Issues
+24.11.1 Naming Issues
As you can see in the example above, there are potential naming conflicts. The default exported accessor for the
Foo::a
variable is nameda
. The name of the wrapper global @@ -25856,7 +28187,7 @@ Test-primitive.scm. The string "primitive" can be changed by th (use-modules ((Test) #:renamer (symbol-prefix-proc 'goops:))) -23.11.2 Linking
+24.11.2 Linking
The guile-modules generated above all need to be linked together. GOOPS support requires either passive or module linkage. The exported GOOPS guile-module will be the name of the swig-module and should be @@ -25982,7 +28313,7 @@ mod2 uses symbols from
mod1
, themod2
future SWIG can detect dependencies and export this line. (how do other language modules handle this problem?)
-24 SWIG and Java
+25 SWIG and Java
@@ -26038,7 +28369,13 @@ mod2 uses symbols frommod1
, themod2
C++ default arguments C++ namespaces C++ templates -C++ Smart Pointers +C++ Smart Pointers + + Further details on the generated @@ -26077,6 +28414,7 @@ mod2 uses symbols from +mod1
, themod2
Interfaces Cross language polymorphism using @@ -26089,6 +28427,8 @@ mod2 uses symbols from mod1
, themod2
Director threading issues Director performance tuning +Java exceptions from + directors Accessing protected members @@ -26180,7 +28520,7 @@ mod2 uses symbols frommod1
, themod2
This chapter describes SWIG's support of Java. It covers most SWIG features, but certain low-level details are covered in less depth than in earlier chapters.
-24.1 Overview
+25.1 Overview
The 100% Pure Java effort is a commendable concept, however in the real world programmers often either need to re-use their existing code or in some situations want to take advantage of Java but are forced @@ -26220,7 +28560,7 @@ tour of basic C/C++ wrapping section which explains how to call the directives are covered. The latter sections cover the advanced techniques of using typemaps for complete control of the wrapping process.
-24.2 Preliminaries
+25.2 Preliminaries
SWIG 1.1 works with JDKs from JDK 1.1 to JDK1.4 (Java 2 SDK1.4) and should also work with any later versions. Given the choice, you should probably use the latest version of Sun's JDK. The SWIG Java module is @@ -26236,10 +28576,10 @@ tour of basic C/C++ wrapping section which explains how to call the
The Java module requires your system to support shared libraries and dynamic loading. This is the commonly used method to load JNI code so your system will more than likely support this.
-Android uses Java JNI and also works with SWIG. Please read the +
Android uses Java JNI and also works with SWIG. Please read the Android chapter in conjunction with this one if you are targeting Android.
-24.2.1 Running SWIG
+25.2.1 Running SWIG
Suppose that you defined a SWIG module such as the following:
@@ -26282,7 +28622,7 @@ later. Note that the module name does not define a Java package and use.The following sections have further practical examples and details on how you might go about compiling and using the generated files.
-24.2.2 Additional Commandline Options
+25.2.2 Additional Commandline Options
The following table list the additional commandline options available for the Java module. They can also be seen by using:
@@ -26301,8 +28641,8 @@ swig -java -helpTheir use will become clearer by the time you have finished reading this section on SWIG and Java.
-24.2.3 Getting the right - header files
+25.2.3 Getting the right header + files
In order to compile the C/C++ wrappers, the compiler needs the jni.h and jni_md.h header files which are part of the JDK. They are usually in directories like this:
@@ -26314,8 +28654,8 @@ jni.h and jni_md.h header files which are part of the JDK.The exact location may vary on your machine, but the above locations are typical.
-24.2.4 Compiling a dynamic - module
+25.2.4 Compiling a dynamic module +
The JNI code exists in a dynamic module or shared library (DLL on Windows) and gets loaded by the JVM. Assuming you have code you need to link to in a file called example.c, in order to build a shared @@ -26324,8 +28664,8 @@ jni.h and jni_md.h header files which are part of the JDK.
@@ -26335,9 +28675,7 @@ $ ld -G example_wrap.o example.o -o libexample.so Examples/java directory. If that doesn't work, you will need to read the man-pages for your compiler and linker to get the right set of options. You might also check the -SWIG Wiki for additional information. -JNI compilation is a useful reference for compiling on different - platforms. +SWIG Wiki for additional information.$ swig -java example.i -$ gcc -c example_wrap.c -I/usr/java/include -I/usr/java/include/solaris -$ gcc -c example.c +$ gcc -fPIC -c example_wrap.c -I/usr/java/include -I/usr/java/include/solaris +$ gcc -fPIC -c example.c $ ld -G example_wrap.o example.o -o libexample.soImportant
-
If you are going to use optimisations turned on with gcc (for example -O2), ensure you also compile with -fno-strict-aliasing. The @@ -26352,7 +28690,7 @@ JNI compilation is a useful reference for compiling on different Dynamic linking problems for more information). The name of the module is specified using the %module directive or -module command line option.24.2.5 Using your module
+25.2.5 Using your module
To load your shared native library module in Java, simply use Java's System.loadLibrary method in a Java class:
@@ -26381,8 +28719,8 @@ $If it doesn't work have a look at the following section which discusses problems loading the shared library.
-24.2.6 Dynamic linking - problems
+25.2.6 Dynamic linking + problems
As shown in the previous section the code to load a native library (shared library) is System.loadLibrary("name"). This can fail with an UnsatisfiedLinkError exception and can be due to a number of @@ -26445,9 +28783,9 @@ $
$ java runme Exception in thread "main" java.lang.UnsatisfiedLinkError: exampleJNI.gcd(II)I - at exampleJNI.gcd(Native Method) - at example.gcd(example.java:12) - at runme.main(runme.java:18) + at exampleJNI.gcd(Native Method) + at example.gcd(example.java:12) + at runme.main(runme.java:18)where gcd is the missing JNI function that SWIG generated @@ -26465,16 +28803,15 @@ Exception in thread "main" java.lang.UnsatisfiedLinkError: exampleJNI. SWIG Wiki also has some settings for commonly used compiler and operating system combinations. The following section also contains some C++ specific linking problems and solutions.
-24.2.7 Compilation - problems and compiling with C++
+25.2.7 Compilation problems + and compiling with C++
On most machines, shared library files should be linked using the C++ compiler. For example:
@@ -26508,15 +28845,15 @@ $% swig -c++ -java example.i % g++ -c -fpic example.cxx -% g++ -c -fpic example_wrap.cxx -I/usr/java/j2sdk1.4.1/include -I/usr/java/ -j2sdk1.4.1/include/linux +% g++ -c -fpic example_wrap.cxx -I/usr/java/j2sdk1.4.1/include -I/usr/java/j2sdk1.4.1/include/linux % g++ -shared example.o example_wrap.o -o libexample.soFinally make sure the version of JDK header files matches the version of Java that you are running as incompatibilities could lead to compilation problems or unpredictable behaviour.
-24.2.8 Building on Windows
+25.2.8 Building on Windows
Building on Windows is roughly similar to the process used with Unix. You will want to produce a DLL that can be loaded by the Java Virtual Machine. This section covers the process of using SWIG with Microsoft Visual C++ 6 although the procedure may be similar with other compilers. In order for everything to work, you will need to have a JDK installed on your machine in order to read the JNI header files.
-24.2.8.1 Running SWIG from Visual - Studio
+25.2.8.1 Running SWIG from Visual + Studio
If you are developing your application within Microsoft Visual studio, SWIG can be invoked as a custom build option. The Examples\java directory has a few Windows Examples @@ -26565,7 +28902,7 @@ _wrap.c in the instructions above and add -c++ when invoking swig.
as described in the previous section. If the library fails to load have a look at Dynamic linking problems. -24.2.8.2 Using NMAKE
+25.2.8.2 Using NMAKE
Alternatively, a Makefile for use by NMAKE can be written. Make sure the environment variables for MSVC++ are available and the MSVC++ tools are in your path. Now, just write a short Makefile like this :
@@ -26607,11 +28944,11 @@ CFLAGS = /Z7 /Od /c /nologo JAVA_INCLUDE = -ID:\jdk1.3\include -ID:\jdk1.3\include\win32 java:: - swig -java -o $(WRAPFILE) $(INTERFACE) - $(CC) $(CFLAGS) $(JAVA_INCLUDE) $(SRCS) $(WRAPFILE) - set LIB=$(TOOLS)\lib - $(LINK) $(LOPT) -out:example.dll $(LIBS) example.obj example_wrap.obj - javac *.java + swig -java -o $(WRAPFILE) $(INTERFACE) + $(CC) $(CFLAGS) $(JAVA_INCLUDE) $(SRCS) $(WRAPFILE) + set LIB=$(TOOLS)\lib + $(LINK) $(LOPT) -out:example.dll $(LIBS) example.obj example_wrap.obj + javac *.javaTo build the DLL and compile the java code, run NMAKE (you may need @@ -26619,14 +28956,14 @@ java:: but hopefully its enough to get you started. Of course you may want to make changes for it to work for C++ by adding in the -c++ command line switch for swig and replacing .c with .cxx.
-24.3 A tour of basic C/C++ wrapping
+25.3 A tour of basic C/C++ wrapping
By default, SWIG attempts to build a natural Java interface to your C/C++ code. Functions are wrapped as functions, classes are wrapped as classes, variables are wrapped with JavaBean type getters and setters and so forth. This section briefly covers the essential aspects of this wrapping.
-24.3.1 Modules, packages - and generated Java classes
+25.3.1 Modules, packages and + generated Java classes
The SWIG %module directive specifies the name of the Java module. When you specify `%module example', the module name determines the name of some of the generated files in the module. The @@ -26658,7 +28995,7 @@ swig -java -package com.bloggs.swig -outdir com/bloggs/swig example.i
SWIG won't create the directory, so make sure it exists beforehand.
-24.3.2 Functions
+25.3.2 Functions
There is no such thing as a global Java function so global C functions are wrapped as static methods in the module class. For example,
@@ -26687,7 +29024,7 @@ public class example { System.out.println(example.fact(4));24.3.3 Global variables
+25.3.3 Global variables
C/C++ global variables are fully supported by SWIG. Java does not allow the overriding of the dot operator so all variables are accessed through getters and setters. Again because there is no such thing as a @@ -26757,7 +29094,7 @@ extern char *path; extern char *path; // Read-only (due to %immutable)
24.3.4 Constants
+25.3.4 Constants
C/C++ constants are wrapped as Java static final variables. To create a constant, use #define or the %constant directive. For example:
@@ -26887,7 +29224,7 @@ public class example implements exampleConstants { example.EXPRESSION or exampleConstants.EXPRESSION. Or if you decide this practice isn't so bad and your own class implements exampleConstants, you can of course just use EXPRESSION. -24.3.5 Enumerations
+25.3.5 Enumerations
SWIG handles both named and unnamed (anonymous) enumerations. There is a choice of approaches to wrapping named C/C++ enums. This is due to historical reasons as SWIG's initial support for enums was limited and @@ -26899,7 +29236,7 @@ exampleConstants, you can of course just use EXPRESSION.
final two approaches use simple integers for each enum item. Before looking at the various approaches for wrapping named C/C++ enums, anonymous enums are considered. -24.3.5.1 Anonymous enums
+25.3.5.1 Anonymous enums
There is no name for anonymous enums and so they are handled like constants. For example:
@@ -26952,7 +29289,7 @@ public interface exampleConstants {As in the case of constants, you can access them through either the module class or the constants interface, for example, example.ALE or exampleConstants.ALE.
-24.3.5.2 Typesafe enums
+25.3.5.2 Typesafe enums
This is the default approach to wrapping named enums. The typesafe enum pattern is a relatively well known construct to work around the lack of enums in versions of Java prior to JDK 1.5. It basically @@ -27034,7 +29371,7 @@ Java Tip 122: Beware of Java typesafe enumerations JavaWorld tips.
1.5 or later, proper Java enums could be used instead, without users having to change their code. The following section details proper Java enum generation. -24.3.5.3 Proper Java enums
+25.3.5.3 Proper Java enums
Proper Java enums were only introduced in JDK 1.5 so this approach is only compatible with more recent versions of Java. Java enums have been designed to overcome all the limitations of both typesafe and type @@ -27079,7 +29416,7 @@ Constants section can also be used for proper Java enums.
The additional support methods need not be generated if none of the enum items have initializers and this is covered later in the Simpler Java enums for enums without initializers section.
-24.3.5.4 Type unsafe enums
+25.3.5.4 Type unsafe enums
In this approach each enum item in a named enumeration is wrapped as a static final integer in a class named after the C/C++ enum name. This is a commonly used pattern in Java to simulate C/C++ enums, but it is @@ -27089,5595 +29426,7193 @@ Simpler Java enums for enums without initializers section.
look at an example.+-%include "enumtypeunsafe.swg" -%javaconst(1); -enum Beverage { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER }; +%include "enumtypeunsafe.swg" +%javaconst(1); +enum Beverage { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER }; ++will generate:
++++public final class Beverage { + public final static int ALE = 0; + public final static int LAGER = 10; + public final static int STOUT = LAGER + 1; + public final static int PILSNER = STOUT + 1; + public final static int PILZ = PILSNER; +} ++As is the case previously, the default is %javaconst(0) as + not all C/C++ values will compile as Java code. However, again it is + recommended to add in a %javaconst(1) directive. and the +%javaconstvalue(value) directive covered in the +Constants section can also be used for type unsafe enums. Note that + global enums are generated into a Java class within whatever package + you are using. C++ enums defined within a C++ class are generated into + a static final inner Java class within the Java proxy class.
+Note that unlike typesafe enums, this approach requires users to + mostly use different syntax compared with proper Java enums. Thus the + upgrade path to proper enums provided in JDK 1.5 is more painful.
+25.3.5.5 Simple enums
+This approach is similar to the type unsafe approach. Each enum item + is also wrapped as a static final integer. However, these integers are + not generated into a class named after the C/C++ enum. Instead, global + enums are generated into the constants interface. Also, enums defined + in a C++ class have their enum items generated directly into the Java + proxy class rather than an inner class within the Java proxy class. In + fact, this approach is effectively wrapping the enums as if they were + anonymous enums and the resulting code is as per +anonymous enums. The implementation is in the "enumsimple.swg" file.
+Compatibility Note: SWIG-1.3.21 and earlier versions wrapped + all enums using this approach. The type unsafe approach is preferable + to this one and this simple approach is only included for backwards + compatibility with these earlier versions of SWIG.
+25.3.6 Pointers
+C/C++ pointers are fully supported by SWIG. Furthermore, SWIG has no + problem working with incomplete type information. Here is a rather + simple interface:
++++%module example + +FILE *fopen(const char *filename, const char *mode); +int fputs(const char *, FILE *); +int fclose(FILE *); ++When wrapped, you will be able to use the functions in a natural way + from Java. For example:
++++SWIGTYPE_p_FILE f = example.fopen("junk","w"); +example.fputs("Hello World\n", f); +example.fclose(f); ++C pointers in the Java module are stored in a Java long and + cross the JNI boundary held within this 64 bit number. Many other SWIG + language modules use an encoding of the pointer in a string. These + scripting languages use the SWIG runtime type checker for dynamic type + checking as they do not support static type checking by a compiler. In + order to implement static type checking of pointers within Java, they + are wrapped by a simple Java class. In the example above the FILE * + pointer is wrapped with a type wrapper class called +SWIGTYPE_p_FILE.
+Once obtained, a type wrapper object can be freely passed around to + different C functions that expect to receive an object of that type. + The only thing you can't do is dereference the pointer from Java. Of + course, that isn't much of a concern in this example.
+As much as you might be inclined to modify a pointer value directly + from Java, don't. The value is not necessarily the same as the logical + memory address of the underlying object. The value will vary depending + on the native byte-ordering of the platform (i.e., big-endian vs. + little-endian). Most JVMs are 32 bit applications so any JNI code must + also be compiled as 32 bit. The net result is pointers in JNI code are + also 32 bits and are stored in the high order 4 bytes on big-endian + machines and in the low order 4 bytes on little-endian machines. By + design it is also not possible to manually cast a pointer to a new type + by using Java casts as it is particularly dangerous especially when + casting C++ objects. If you need to cast a pointer or change its value, + consider writing some helper functions instead. For example:
++++%inline %{ +/* C-style cast */ +Bar *FooToBar(Foo *f) { + return (Bar *) f; +} + +/* C++-style cast */ +Foo *BarToFoo(Bar *b) { + return dynamic_cast<Foo*>(b); +} + +Foo *IncrFoo(Foo *f, int i) { + return f+i; +} +%} ++Also, if working with C++, you should always try to use the new C++ + style casts. For example, in the above code, the C-style cast may + return a bogus result whereas as the C++-style cast will return a NULL + pointer if the conversion can't be performed.
+25.3.7 Structures
+If you wrap a C structure, it is wrapped by a Java class with + getters and setters for access to the member variables. For example,
++++struct Vector { + double x,y,z; +}; + ++is used as follows:
++++Vector v = new Vector(); +v.setX(3.5); +v.setY(7.2); +double x = v.getX(); +double y = v.getY(); ++The variable setters and getters are also based on the JavaBean + design pattern already covered under the Global variables section. + Similar access is provided for unions and the public data members of + C++ classes.
+This object is actually an instance of a Java class that has been + wrapped around a pointer to the C structure. This instance doesn't + actually do anything--it just serves as a proxy. The pointer to the C + object is held in the Java proxy class in much the same way as pointers + are held by type wrapper classes. Further details about Java proxy + classes are covered a little later.
+const members of a structure are read-only. Data members + can also be forced to be read-only using the %immutable + directive. For example:
++++struct Foo { + ... + %immutable; + int x; /* Read-only members */ + char *name; + %mutable; + ... +}; ++When char * members of a structure are wrapped, the + contents are assumed to be dynamically allocated using malloc + or new (depending on whether or not SWIG is run with the -c++ + option). When the structure member is set, the old contents will be + released and a new value created. If this is not the behavior you want, + you will have to use a typemap (described later).
+If a structure contains arrays, access to those arrays is managed + through pointers. For example, consider this:
++++struct Bar { + int x[16]; +}; ++If accessed in Java, you will see behavior like this:
++++Bar b = new Bar(); +SWIGTYPE_p_int x = b.getX(); ++This pointer can be passed around to functions that expect to + receive an int * (just like C). You can also set the value of + an array member using another pointer. For example:
++++Bar b = new Bar(); +SWIGTYPE_p_int x = b.getX(); +Bar c = new Bar(); +c.setX(x); // Copy contents of b.x to c.x ++For array assignment (setters not getters), SWIG copies the entire + contents of the array starting with the data pointed to by b.x +. In this example, 16 integers would be copied. Like C, SWIG makes no + assumptions about bounds checking---if you pass a bad pointer, you may + get a segmentation fault or access violation. The default wrapping + makes it hard to set or get just one element of the array and so array + access from Java is somewhat limited. This can be changed easily though + by using the approach outlined later in the +Wrapping C arrays with Java arrays and +Unbounded C Arrays sections.
+When a member of a structure is itself a structure, it is handled as + a pointer. For example, suppose you have two structures like this:
++++struct Foo { + int a; +}; + +struct Bar { + Foo f; +}; ++Now, suppose that you access the f member of Bar + like this:
++++Bar b = new Bar(); +Foo x = b.getF(); ++In this case, x is a pointer that points to the Foo + that is inside b. This is the same value as generated by this + C code:
++++Bar b; +Foo *x = &b->f; /* Points inside b */ ++Because the pointer points inside the structure, you can modify the + contents and everything works just like you would expect. For example:
++++Bar b = new Bar(); +b.getF().setA(3); // Modify b.f.a +Foo x = b.getF(); +x.setA(3); // Modify x.a - this is the same as b.f.a ++25.3.8 C++ classes
+C++ classes are wrapped by Java classes as well. For example, if you + have this class,
++++class List { +public: + List(); + ~List(); + int search(char *item); + void insert(char *item); + void remove(char *item); + char *get(int n); + int length; +}; ++you can use it in Java like this:
++++List l = new List(); +l.insert("Ale"); +l.insert("Stout"); +l.insert("Lager"); +String item = l.get(2); +int length = l.getLength(); ++Class data members are accessed in the same manner as C structures.
+Static class members are unsurprisingly wrapped as static members of + the Java class:
++++class Spam { +public: + static void foo(); + static int bar; +}; ++The static members work like any other Java static member:
++++Spam.foo(); +int bar = Spam.getBar(); ++25.3.9 C++ inheritance
+SWIG is fully aware of issues related to C++ inheritance. Therefore, + if you have classes like this
++++class Foo { +... +}; + +class Bar : public Foo { +... +}; ++those classes are wrapped into a hierarchy of Java classes that + reflect the same inheritance structure:
++++Bar b = new Bar(); +Class c = b.getClass(); +System.out.println(c.getSuperclass().getName()); ++will of course display:
++++Foo ++Furthermore, if you have functions like this
++++void spam(Foo *f); ++then the Java function spam() accepts instances of Foo + or instances of any other proxy classes derived from Foo.
+Note that Java does not support multiple inheritance so any multiple + inheritance in the C++ code is not going to work. A warning is given + when multiple inheritance is detected and only the first base class is + used.
+25.3.10 Pointers, references, + arrays and pass by value
+In C++, there are many different ways a function might receive and + manipulate objects. For example:
++++void spam1(Foo *x); // Pass by pointer +void spam2(Foo &x); // Pass by reference +void spam3(Foo x); // Pass by value +void spam4(Foo x[]); // Array of objects ++In Java, there is no detailed distinction like this--specifically, + there are only instances of classes. There are no pointers nor + references. Because of this, SWIG unifies all of these types together + in the wrapper code. For instance, if you actually had the above + functions, it is perfectly legal to do this from Java:
++++Foo f = new Foo(); // Create a Foo +example.spam1(f); // Ok. Pointer +example.spam2(f); // Ok. Reference +example.spam3(f); // Ok. Value. +example.spam4(f); // Ok. Array (1 element) ++Similar behavior occurs for return values. For example, if you had + functions like this,
++++Foo *spam5(); +Foo &spam6(); +Foo spam7(); ++then all three functions will return a pointer to some Foo + object. Since the third function (spam7) returns a value, newly + allocated memory is used to hold the result and a pointer is returned + (Java will release this memory when the returned object's finalizer is + run by the garbage collector).
+25.3.10.1 Null pointers
+Working with null pointers is easy. A Java null can be used + whenever a method expects a proxy class or typewrapper class. However, + it is not possible to pass null to C/C++ functions that take parameters + by value or by reference. If you try you will get a + NullPointerException.
++++example.spam1(null); // Pointer - ok +example.spam2(null); // Reference - NullPointerException +example.spam3(null); // Value - NullPointerException +example.spam4(null); // Array - ok ++For spam1 and spam4 above the Java null + gets translated into a NULL pointer for passing to the C/C++ function. + The converse also occurs, that is, NULL pointers are translated into +null Java objects when returned from a C/C++ function.
+25.3.11 C++ overloaded functions +
+C++ overloaded functions, methods, and constructors are mostly + supported by SWIG. For example, if you have two functions like this:
++++%module example + +void foo(int); +void foo(char *c); ++You can use them in Java in a straightforward manner:
++++example.foo(3); // foo(int) +example.foo("Hello"); // foo(char *c) ++Similarly, if you have a class like this,
++++class Foo { +public: + Foo(); + Foo(const Foo &); + ... +}; ++you can write Java code like this:
++++Foo f = new Foo(); // Create a Foo +Foo g = new Foo(f); // Copy f ++Overloading support is not quite as flexible as in C++. Sometimes + there are methods that SWIG cannot disambiguate as there can be more + than one C++ type mapping onto a single Java type. For example:
++++void spam(int); +void spam(unsigned short); ++Here both int and unsigned short map onto a Java int. Here is + another example:
++++void foo(Bar *b); +void foo(Bar &b); ++If declarations such as these appear, you will get a warning message + like this:
++++example.i:12: Warning 515: Overloaded method spam(unsigned short) ignored. +Method spam(int) at example.i:11 used. ++To fix this, you either need to either +rename or ignore one of the methods. For example:
++++%rename(spam_ushort) spam(unsigned short); +... +void spam(int); +void spam(unsigned short); // Now renamed to spam_ushort ++or
++++%ignore spam(unsigned short); +... +void spam(int); +void spam(unsigned short); // Ignored ++25.3.12 C++ default arguments
+Any function with a default argument is wrapped by generating an + additional function for each argument that is defaulted. For example, + if we have the following C++:
++-+%module example + +void defaults(double d=10.0, int i=0);will generate:
+The following methods are generated in the Java module class:
--public final class Beverage { - public final static int ALE = 0; - public final static int LAGER = 10; - public final static int STOUT = LAGER + 1; - public final static int PILSNER = STOUT + 1; - public final static int PILZ = PILSNER; +public class example { + public static void defaults(double d, int i) { ... } + public static void defaults(double d) { ... } + public static void defaults() { ... } }As is the case previously, the default is %javaconst(0) as - not all C/C++ values will compile as Java code. However, again it is - recommended to add in a %javaconst(1) directive. and the -%javaconstvalue(value) directive covered in the -Constants section can also be used for type unsafe enums. Note that - global enums are generated into a Java class within whatever package - you are using. C++ enums defined within a C++ class are generated into - a static final inner Java class within the Java proxy class.
-Note that unlike typesafe enums, this approach requires users to - mostly use different syntax compared with proper Java enums. Thus the - upgrade path to proper enums provided in JDK 1.5 is more painful.
-24.3.5.5 Simple enums
-This approach is similar to the type unsafe approach. Each enum item - is also wrapped as a static final integer. However, these integers are - not generated into a class named after the C/C++ enum. Instead, global - enums are generated into the constants interface. Also, enums defined - in a C++ class have their enum items generated directly into the Java - proxy class rather than an inner class within the Java proxy class. In - fact, this approach is effectively wrapping the enums as if they were - anonymous enums and the resulting code is as per -anonymous enums. The implementation is in the "enumsimple.swg" file.
-Compatibility Note: SWIG-1.3.21 and earlier versions wrapped - all enums using this approach. The type unsafe approach is preferable - to this one and this simple approach is only included for backwards - compatibility with these earlier versions of SWIG.
-24.3.6 Pointers
-C/C++ pointers are fully supported by SWIG. Furthermore, SWIG has no - problem working with incomplete type information. Here is a rather - simple interface:
+It is as if SWIG had parsed three separate overloaded methods. The + same approach is taken for static methods, constructors and member + methods.
+Compatibility note: Versions of SWIG prior to SWIG-1.3.23 + wrapped these with a single wrapper method and so the default values + could not be taken advantage of from Java. Further details on default + arguments and how to restore this approach are given in the more + general Default arguments section.
+25.3.13 C++ namespaces
+SWIG is aware of named C++ namespaces and they can be mapped to Java + packages, however, the default wrapping flattens the namespaces, + effectively ignoring them. So by default, the namespace names do not + appear in the module nor do namespaces result in a module that is + broken up into submodules or packages. For example, if you have a file + like this,
-%module example -FILE *fopen(const char *filename, const char *mode); -int fputs(const char *, FILE *); -int fclose(FILE *); +namespace foo { + int fact(int n); + struct Vector { + double x,y,z; + }; +};When wrapped, you will be able to use the functions in a natural way - from Java. For example:
+it works in Java as follows:
--SWIGTYPE_p_FILE f = example.fopen("junk","w"); -example.fputs("Hello World\n", f); -example.fclose(f); +int f = example.fact(3); +Vector v = new Vector(); +v.setX(3.4); +double y = v.getY();C pointers in the Java module are stored in a Java long and - cross the JNI boundary held within this 64 bit number. Many other SWIG - language modules use an encoding of the pointer in a string. These - scripting languages use the SWIG runtime type checker for dynamic type - checking as they do not support static type checking by a compiler. In - order to implement static type checking of pointers within Java, they - are wrapped by a simple Java class. In the example above the FILE * - pointer is wrapped with a type wrapper class called -SWIGTYPE_p_FILE.
-Once obtained, a type wrapper object can be freely passed around to - different C functions that expect to receive an object of that type. - The only thing you can't do is dereference the pointer from Java. Of - course, that isn't much of a concern in this example.
-As much as you might be inclined to modify a pointer value directly - from Java, don't. The value is not necessarily the same as the logical - memory address of the underlying object. The value will vary depending - on the native byte-ordering of the platform (i.e., big-endian vs. - little-endian). Most JVMs are 32 bit applications so any JNI code must - also be compiled as 32 bit. The net result is pointers in JNI code are - also 32 bits and are stored in the high order 4 bytes on big-endian - machines and in the low order 4 bytes on little-endian machines. By - design it is also not possible to manually cast a pointer to a new type - by using Java casts as it is particularly dangerous especially when - casting C++ objects. If you need to cast a pointer or change its value, - consider writing some helper functions instead. For example:
+If your program has more than one namespace, name conflicts (if any) + can be resolved using %rename For example:
--%inline %{ -/* C-style cast */ -Bar *FooToBar(Foo *f) { - return (Bar *) f; -} +%rename(Bar_spam) Bar::spam; -/* C++-style cast */ -Foo *BarToFoo(Bar *b) { - return dynamic_cast<Foo*>(b); +namespace Foo { + int spam(); } -Foo *IncrFoo(Foo *f, int i) { - return f+i; +namespace Bar { + int spam(); } -%}Also, if working with C++, you should always try to use the new C++ - style casts. For example, in the above code, the C-style cast may - return a bogus result whereas as the C++-style cast will return a NULL - pointer if the conversion can't be performed.
-24.3.7 Structures
-If you wrap a C structure, it is wrapped by a Java class with - getters and setters for access to the member variables. For example,
+If you have more than one namespace and you want to keep their + symbols separate, consider wrapping them as separate SWIG modules. Each + SWIG module can be placed into a separate package.
+The default behaviour described above can be improved via the +nspace feature. Note that it only works for classes, structs, unions + and enums declared within a named C++ namespace. When the nspace + feature is used, the C++ namespaces are converted into Java packages of + the same name. Proxy classes are thus declared within a package and + this proxy makes numerous calls to the JNI intermediary class which is + declared in the unnamed package by default. As Java does not support + types declared in a named package accessing types declared in an + unnamed package, the -package commandline option described + earlier generally should be used to provide a parent package. So if + SWIG is run using the -package com.myco option, a wrapped + class, MyWorld::Material::Color, can then be accessed as +com.myco.MyWorld.Material.Color. If you don't specify a package, + you will get the following warning:
++++example.i:16: Warning 826: The nspace feature is used on 'MyWorld::Material::Color' without -package. The generated code +may not compile as Java does not support types declared in a named package accessing types declared in an unnamed package. ++If it is undesirable to have a single top level package, the nspace + feature may be used without the -package commandline option + (and the resulting warning ignored) if all of the types exposed using + SWIG are placed in a package using the nspace feature and the + 'jniclasspackage' pragma is used to specify a package for the JNI + intermediary class.
+If the resulting use of the nspace feature and hence packages + results in a proxy class in one package deriving or using a proxy class + from another package, you will need to open up the visibility for the + pointer constructor and getCPtr method from the default + 'protected' to 'public' with the SWIG_JAVABODY_PROXY macro. + See Java code typemaps.
+25.3.14 C++ templates
+C++ templates don't present a huge problem for SWIG. However, in + order to create wrappers, you have to tell SWIG to create wrappers for + a particular template instantiation. To do this, you use the +%template directive. For example:
--struct Vector { - double x,y,z; +%module example +%{ +#include <utility> +%} + +template<class T1, class T2> +struct pair { + typedef T1 first_type; + typedef T2 second_type; + T1 first; + T2 second; + pair(); + pair(const T1&, const T2&); + ~pair(); }; +%template(pairii) pair<int,int>;is used as follows:
+In Java:
--Vector v = new Vector(); -v.setX(3.5); -v.setY(7.2); -double x = v.getX(); -double y = v.getY(); +pairii p = new pairii(3,4); +int first = p.getFirst(); +int second = p.getSecond();The variable setters and getters are also based on the JavaBean - design pattern already covered under the Global variables section. - Similar access is provided for unions and the public data members of - C++ classes.
-This object is actually an instance of a Java class that has been - wrapped around a pointer to the C structure. This instance doesn't - actually do anything--it just serves as a proxy. The pointer to the C - object is held in the Java proxy class in much the same way as pointers - are held by type wrapper classes. Further details about Java proxy - classes are covered a little later.
-const members of a structure are read-only. Data members - can also be forced to be read-only using the %immutable - directive. For example:
+Obviously, there is more to template wrapping than shown in this + example. More details can be found in the SWIG and + C++ chapter.
+25.3.15 C++ Smart Pointers
+25.3.15.1 The shared_ptr + Smart Pointer
+The C++11 standard provides std::shared_ptr which was + derived from the Boost implementation, boost::shared_ptr. Both + of these are available for Java in the SWIG library and usage is + outlined in the shared_ptr smart + pointer library section.
+25.3.15.2 Generic Smart + Pointers
+In certain C++ programs, it is common to use classes that have been + wrapped by so-called "smart pointers." Generally, this involves the use + of a template class that implements operator->() like this:
--struct Foo { +template<class T> class SmartPtr { ... - %immutable; - int x; /* Read-only members */ - char *name; - %mutable; + T *operator->(); ... -}; +}When char * members of a structure are wrapped, the - contents are assumed to be dynamically allocated using malloc - or new (depending on whether or not SWIG is run with the -c++ - option). When the structure member is set, the old contents will be - released and a new value created. If this is not the behavior you want, - you will have to use a typemap (described later).
-If a structure contains arrays, access to those arrays is managed - through pointers. For example, consider this:
+Then, if you have a class like this,
--struct Bar { - int x[16]; +class Foo { +public: + int x; + int bar(); };If accessed in Java, you will see behavior like this:
+A smart pointer would be used in C++ as follows:
--Bar b = new Bar(); -SWIGTYPE_p_int x = b.getX(); +SmartPtr<Foo> p = CreateFoo(); // Created somehow (not shown) +... +p->x = 3; // Foo::x +int y = p->bar(); // Foo::barThis pointer can be passed around to functions that expect to - receive an int * (just like C). You can also set the value of - an array member using another pointer. For example:
+To wrap this in Java, simply tell SWIG about the SmartPtr + class and the low-level Foo object. Make sure you instantiate +SmartPtr using %template if necessary. For example:
--Bar b = new Bar(); -SWIGTYPE_p_int x = b.getX(); -Bar c = new Bar(); -c.setX(x); // Copy contents of b.x to c.x +%module example +... +%template(SmartPtrFoo) SmartPtr<Foo>; +...For array assignment (setters not getters), SWIG copies the entire - contents of the array starting with the data pointed to by b.x -. In this example, 16 integers would be copied. Like C, SWIG makes no - assumptions about bounds checking---if you pass a bad pointer, you may - get a segmentation fault or access violation. The default wrapping - makes it hard to set or get just one element of the array and so array - access from Java is somewhat limited. This can be changed easily though - by using the approach outlined later in the -Wrapping C arrays with Java arrays and -Unbounded C Arrays sections.
-When a member of a structure is itself a structure, it is handled as - a pointer. For example, suppose you have two structures like this:
+Now, in Java, everything should just "work":
+-struct Foo { - int a; -}; - -struct Bar { - Foo f; +SmartPtrFoo p = example.CreateFoo(); // Create a smart-pointer somehow +p.setX(3); // Foo::x +int y = p.bar(); // Foo::bar ++If you ever need to access the underlying pointer returned by +operator->() itself, simply use the __deref__() method. + For example:
++++Foo f = p.__deref__(); // Returns underlying Foo * ++25.4 Further details on the generated + Java classes
+In the previous section, a high-level view of Java wrapping was + presented. A key component of this wrapping is that structures and + classes are wrapped by Java proxy classes and type wrapper classes are + used in situations where no proxies are generated. This provides a very + natural, type safe Java interface to the C/C++ code and fits in with + the Java programming paradigm. However, a number of low-level details + were omitted. This section provides a brief overview of how the proxy + classes work and then covers the type wrapper classes. Finally enum + classes are covered. First, the crucial intermediary JNI class is + considered.
+25.4.1 The intermediary JNI class
+In the "SWIG basics" and +"SWIG and C++" chapters, details of low-level structure and class + wrapping are described. To summarize those chapters, if you have a + global function and class like this
++-+class Foo { +public: + int x; + int spam(int num, Foo* foo); }; +void egg(Foo* chips);Now, suppose that you access the f member of Bar - like this:
+then SWIG transforms the class into a set of low-level procedural + wrappers. These procedural wrappers essentially perform the equivalent + of this C++ code:
--Bar b = new Bar(); -Foo x = b.getF(); +Foo *new_Foo() { + return new Foo(); +} +void delete_Foo(Foo *f) { + delete f; +} +int Foo_x_get(Foo *f) { + return f->x; +} +void Foo_x_set(Foo *f, int value) { + f->x = value; +} +int Foo_spam(Foo *f, int num, Foo* foo) { + return f->spam(num, foo); +}In this case, x is a pointer that points to the Foo - that is inside b. This is the same value as generated by this - C code:
+These procedural function names don't actually exist, but their + functionality appears inside the generated JNI functions. The JNI + functions have to follow a particular naming convention so the function + names are actually:
--Bar b; -Foo *x = &b->f; /* Points inside b */ +SWIGEXPORT jlong JNICALL Java_exampleJNI_new_1Foo(JNIEnv *jenv, jclass jcls); +SWIGEXPORT void JNICALL Java_exampleJNI_delete_1Foo(JNIEnv *jenv, jclass jcls, + jlong jarg1); +SWIGEXPORT void JNICALL Java_exampleJNI_Foo_1x_1set(JNIEnv *jenv, jclass jcls, + jlong jarg1, jobject jarg1_, jint jarg2); +SWIGEXPORT jint JNICALL Java_exampleJNI_Foo_1x_1get(JNIEnv *jenv, jclass jcls, + jlong jarg1, jobject jarg1_); +SWIGEXPORT jint JNICALL Java_exampleJNI_Foo_1spam(JNIEnv *jenv, jclass jcls, + jlong jarg1, jobject jarg1_, jint jarg2, + jlong jarg3, jobject jarg3_); +SWIGEXPORT void JNICALL Java_exampleJNI_egg(JNIEnv *jenv, jclass jcls, + jlong jarg1, jobject jarg1_);Because the pointer points inside the structure, you can modify the - contents and everything works just like you would expect. For example:
+For every JNI C function there has to be a static native Java + function. These appear in the intermediary JNI class:
--Bar b = new Bar(); -b.getF().setA(3); // Modify b.f.a -Foo x = b.getF(); -x.setA(3); // Modify x.a - this is the same as b.f.a +class exampleJNI { + public final static native long new_Foo(); + public final static native void delete_Foo(long jarg1); + public final static native void Foo_x_set(long jarg1, Foo jarg1_, int jarg2); + public final static native int Foo_x_get(long jarg1, Foo jarg1_); + public final static native int Foo_spam(long jarg1, Foo jarg1_, int jarg2, + long jarg3, Foo jarg3_); + public final static native void egg(long jarg1, Foo jarg1_); +}24.3.8 C++ classes
-C++ classes are wrapped by Java classes as well. For example, if you - have this class,
+This class contains the complete Java - C/C++ interface so all + function calls go via this class. As this class acts as a go-between + for all JNI calls to C/C++ code from the Java +proxy classes, type wrapper + classes and module class, it is + known as the intermediary JNI class.
+You may notice that SWIG uses a Java long wherever a pointer or + class object needs to be marshalled across the Java-C/C++ boundary. + This approach leads to minimal JNI code which makes for better + performance as JNI code involves a lot of string manipulation. SWIG + favours generating Java code over JNI code as Java code is compiled + into byte code and avoids the costly string operations needed in JNI + code. This approach has a downside though as the proxy class might get + collected before the native method has completed. You might notice + above that there is an additional parameters with a underscore postfix, + eg jarg1_. These are added in order to prevent +premature garbage collection when marshalling proxy classes.
+The functions in the intermediary JNI class cannot be accessed + outside of its package. Access to them is gained through the module + class for globals otherwise the appropriate proxy class.
+ +The name of the intermediary JNI class can be changed from its + default, that is, the module name with JNI appended after it. The + module directive attribute jniclassname is used to achieve + this:
--class List { -public: - List(); - ~List(); - int search(char *item); - void insert(char *item); - void remove(char *item); - char *get(int n); - int length; -}; +%module (jniclassname="name") modulenameyou can use it in Java like this:
+If name is the same as modulename then the module + class name gets changed from modulename to +modulenameModule.
+25.4.1.1 The intermediary JNI class + pragmas
+The intermediary JNI class can be tailored through the use of + pragmas, but is not commonly done. The pragmas for this class are:
++
++ Pragma Description + jniclassbase Base class for the intermediary JNI class ++ jniclasspackage Package in which to place the + intermediary JNI class + jniclassclassmodifiers Class modifiers and class type + for the intermediary JNI class + jniclasscode Java code is copied verbatim into the + intermediary JNI class + jniclassimports Java code, usually one or more import + statements, placed before the intermediary JNI class definition + jniclassinterfaces Comma separated interface classes for + the intermediary JNI class The pragma code appears in the generated intermediary JNI class + where you would expect:
--List l = new List(); -l.insert("Ale"); -l.insert("Stout"); -l.insert("Lager"); -String item = l.get(2); -int length = l.getLength(); +[ jniclassimports pragma ] +[ jniclassclassmodifiers pragma ] jniclassname extends [ jniclassbase pragma ] + implements [ jniclassinterfaces pragma ] { +[ jniclasscode pragma ] +... SWIG generated native methods ... +}Class data members are accessed in the same manner as C structures.
-Static class members are unsurprisingly wrapped as static members of - the Java class:
+The jniclasscode pragma is quite useful for adding in a + static block for loading the shared library / dynamic link library and + demonstrates how pragmas work:
--class Spam { -public: - static void foo(); - static int bar; -}; +%pragma(java) jniclasscode=%{ + static { + try { + System.loadLibrary("example"); + } catch (UnsatisfiedLinkError e) { + System.err.println("Native code library failed to load. \n" + e); + System.exit(1); + } + } +%}The static members work like any other Java static member:
+Pragmas will take either "" or %{ %} as + delimiters. For example, let's change the intermediary JNI class access + to just the default package-private access.
++++%pragma(java) jniclassclassmodifiers="class" ++All the methods in the intermediary JNI class will then not be + callable outside of the package as the method modifiers have been + changed from public access to default access. This is useful if you + want to prevent users calling these low level functions.
+25.4.2 The Java module class
+All global functions and variable getters/setters appear in the + module class. For our example, there is just one function:
++++public class example { + public static void egg(Foo chips) { + exampleJNI.egg(Foo.getCPtr(chips), chips); + } +} ++The module class is necessary as there is no such thing as a global + in Java so all the C globals are put into this class. They are + generated as static functions and so must be accessed as such by using + the module name in the static function call:
++++example.egg(new Foo()); ++The primary reason for having the module class wrapping the calls in + the intermediary JNI class is to implement static type checking. In + this case only a Foo can be passed to the egg + function, whereas any long can be passed to the egg + function in the intermediary JNI class.
+25.4.2.1 The Java module class + pragmas
+The module class can be tailored through the use of pragmas, in the + same manner as the intermediary JNI class. The pragmas are similarly + named and are used in the same way. The complete list follows:
++
++ Pragma Description + modulebase Base class for the module class + moduleclassmodifiers Class modifiers and class type for + the module class + modulecode Java code is copied verbatim into the module + class + moduleimports Java code, usually one or more import + statements, placed before the module class definition + moduleinterfaces Comma separated interface classes for + the module class The pragma code appears in the generated module class like this:
--Spam.foo(); -int bar = Spam.getBar(); +[ moduleimports pragma ] +[ modulemodifiers pragma ] modulename extends [ modulebase pragma ] + implements [ moduleinterfaces pragma ] { +[ modulecode pragma ] +... SWIG generated wrapper functions ... +}24.3.9 C++ inheritance
-SWIG is fully aware of issues related to C++ inheritance. Therefore, - if you have classes like this
+See The intermediary JNI class + pragmas section for further details on using pragmas.
+25.4.3 Java proxy classes
+A Java proxy class is generated for each structure, union or C++ + class that is wrapped. Proxy classes have also been called +peer classes. The default proxy class for our previous example looks + like this:
--class Foo { -... -}; +public class Foo { + private transient long swigCPtr; + protected transient boolean swigCMemOwn; -class Bar : public Foo { -... -}; + protected Foo(long cPtr, boolean cMemoryOwn) { + swigCMemOwn = cMemoryOwn; + swigCPtr = cPtr; + } + + protected static long getCPtr(Foo obj) { + return (obj == null) ? 0 : obj.swigCPtr; + } + + protected void finalize() { + delete(); + } + + public synchronized void delete() { + if(swigCPtr != 0 && swigCMemOwn) { + swigCMemOwn = false; + exampleJNI.delete_Foo(swigCPtr); + } + swigCPtr = 0; + } + + public void setX(int value) { + exampleJNI.Foo_x_set(swigCPtr, this, value); + } + + public int getX() { + return exampleJNI.Foo_x_get(swigCPtr, this); + } + + public int spam(int num, Foo foo) { + return exampleJNI.Foo_spam(swigCPtr, this, num, Foo.getCPtr(foo), foo); + } + + public Foo() { + this(exampleJNI.new_Foo(), true); + } + +}those classes are wrapped into a hierarchy of Java classes that - reflect the same inheritance structure:
+This class merely holds a pointer to the underlying C++ object ( +swigCPtr). It also contains all the methods in the C++ class it is + proxying plus getters and setters for public member variables. These + functions call the native methods in the intermediary JNI class. The + advantage of having this extra layer is the type safety that the proxy + class functions offer. It adds static type checking which leads to + fewer surprises at runtime. For example, you can see that if you + attempt to use the spam() function it will only compile when + the parameters passed are an int and a Foo. From a + user's point of view, it makes the class work as if it were a Java + class:
--Bar b = new Bar(); -Class c = b.getClass(); -System.out.println(c.getSuperclass().getName()); +Foo f = new Foo(); +f.setX(3); +int y = f.spam(5, new Foo());will of course display:
+25.4.3.1 Memory management
+Each proxy class has an ownership flag swigCMemOwn. The + value of this flag determines who is responsible for deleting the + underlying C++ object. If set to true, the proxy class's + finalizer will destroy the C++ object when the proxy class is garbage + collected. If set to false, then the destruction of the proxy class has + no effect on the C++ object.
+When an object is created by a constructor or returned by value, + Java automatically takes ownership of the result. On the other hand, + when pointers or references are returned to Java, there is often no way + to know where they came from. Therefore, the ownership is set to false. + For example:
--Foo +class Foo { +public: + Foo(); + Foo bar1(); + Foo &bar2(); + Foo *bar2(); +};Furthermore, if you have functions like this
+In Java:
--void spam(Foo *f); +Foo f = new Foo(); // f.swigCMemOwn = true +Foo f1 = f.bar1(); // f1.swigCMemOwn = true +Foo f2 = f.bar2(); // f2.swigCMemOwn = false +Foo f3 = f.bar3(); // f3.swigCMemOwn = falsethen the Java function spam() accepts instances of Foo - or instances of any other proxy classes derived from Foo.
-Note that Java does not support multiple inheritance so any multiple - inheritance in the C++ code is not going to work. A warning is given - when multiple inheritance is detected and only the first base class is - used.
-24.3.10 Pointers, - references, arrays and pass by value
-In C++, there are many different ways a function might receive and - manipulate objects. For example:
+This behavior for pointers and references is especially important + for classes that act as containers. For example, if a method returns a + pointer to an object that is contained inside another object, you + definitely don't want Java to assume ownership and destroy it!
+For the most part, memory management issues remain hidden. However, + there are situations where you might have to manually change the + ownership of an object. For instance, consider code like this:
--void spam1(Foo *x); // Pass by pointer -void spam2(Foo &x); // Pass by reference -void spam3(Foo x); // Pass by value -void spam4(Foo x[]); // Array of objects +class Obj {}; +class Node { + Obj *value; +public: + void set_value(Obj *v) { value = v; } +};In Java, there is no detailed distinction like this--specifically, - there are only instances of classes. There are no pointers nor - references. Because of this, SWIG unifies all of these types together - in the wrapper code. For instance, if you actually had the above - functions, it is perfectly legal to do this from Java:
+Now, consider the following Java code:
--Foo f = new Foo(); // Create a Foo -example.spam1(f); // Ok. Pointer -example.spam2(f); // Ok. Reference -example.spam3(f); // Ok. Value. -example.spam4(f); // Ok. Array (1 element) +Node n = new Node(); // Create a node +{ + Obj o = new Obj(); // Create an object + n.set_value(o); // Set value +} // o goes out of scopeSimilar behavior occurs for return values. For example, if you had - functions like this,
+In this case, the Node n is holding a reference to o + internally. However, SWIG has no way to know that this has occurred. + The Java proxy class still thinks that it has ownership of o. + As o has gone out of scope, it could be garbage collected in + which case the C++ destructor will be invoked and n will then + be holding a stale-pointer to o. If you're lucky, you will + only get a segmentation fault.
+To work around this, the ownership flag of o needs changing + to false. The ownership flag is a private member variable of + the proxy class so this is not possible without some customization of + the proxy class. This can be achieved by using a typemap to customise + the proxy class with pure Java code as detailed later in the section on + Java typemaps.
+Sometimes a function will create memory and return a pointer to a + newly allocated object. SWIG has no way of knowing this so by default + the proxy class does not manage the returned object. However, you can + tell the proxy class to manage the memory if you specify the +%newobject directive. Consider:
--Foo *spam5(); -Foo &spam6(); -Foo spam7(); +class Obj {...}; +class Factory { +public: + static Obj *createObj() { return new Obj(); } +};then all three functions will return a pointer to some Foo - object. Since the third function (spam7) returns a value, newly - allocated memory is used to hold the result and a pointer is returned - (Java will release this memory when the returned object's finalizer is - run by the garbage collector).
-24.3.10.1 Null pointers
-Working with null pointers is easy. A Java null can be used - whenever a method expects a proxy class or typewrapper class. However, - it is not possible to pass null to C/C++ functions that take parameters - by value or by reference. If you try you will get a - NullPointerException.
+If we call the factory function, then we have to manually delete the + memory:
--example.spam1(null); // Pointer - ok -example.spam2(null); // Reference - NullPointerException -example.spam3(null); // Value - NullPointerException -example.spam4(null); // Array - ok +Obj obj = Factory.createObj(); // obj.swigCMemOwn = false +... +obj.delete();For spam1 and spam4 above the Java null - gets translated into a NULL pointer for passing to the C/C++ function. - The converse also occurs, that is, NULL pointers are translated into -null Java objects when returned from a C/C++ function.
-24.3.11 C++ overloaded - functions
-C++ overloaded functions, methods, and constructors are mostly - supported by SWIG. For example, if you have two functions like this:
+Now add in the %newobject directive:
--%module example +%newobject Factory::createObj(); -void foo(int); -void foo(char *c); +class Obj {...}; +class Factory { +public: + static Obj *createObj() { return new Obj(); } +};You can use them in Java in a straightforward manner:
+A call to delete() is no longer necessary as the garbage + collector will make the C++ destructor call because swigCMemOwn + is now true.
--example.foo(3); // foo(int) -example.foo("Hello"); // foo(char *c) +Obj obj = Factory.createObj(); // obj.swigCMemOwn = true; +...Similarly, if you have a class like this,
+Some memory management issues are quite tricky to fix and may only + be noticeable after using for a long time. One such issue is premature + garbage collection of an object created from Java and resultant usage + from C++ code. The section on typemap examples cover two such + scenarios, Memory management + for objects passed to the C++ layer and +Memory management when returning references to member variables
+25.4.3.2 Inheritance
+Java proxy classes will mirror C++ inheritance chains. For example, + given the base class Base and its derived class Derived +:
--class Foo { +class Base { public: - Foo(); - Foo(const Foo &); - ... + virtual double foo(); +}; + +class Derived : public Base { +public: + virtual double foo(); };you can write Java code like this:
----Foo f = new Foo(); // Create a Foo -Foo g = new Foo(f); // Copy f --Overloading support is not quite as flexible as in C++. Sometimes - there are methods that SWIG cannot disambiguate as there can be more - than one C++ type mapping onto a single Java type. For example:
+The base class is generated much like any other proxy class seen so + far:
--void spam(int); -void spam(unsigned short); +public class Base { + private transient long swigCPtr; + protected transient boolean swigCMemOwn; + + protected Base(long cPtr, boolean cMemoryOwn) { + swigCMemOwn = cMemoryOwn; + swigCPtr = cPtr; + } + + protected static long getCPtr(Base obj) { + return (obj == null) ? 0 : obj.swigCPtr; + } + + protected void finalize() { + delete(); + } + + public synchronized void delete() { + if(swigCPtr != 0 && swigCMemOwn) { + swigCMemOwn = false; + exampleJNI.delete_Base(swigCPtr); + } + swigCPtr = 0; + } + + public double foo() { + return exampleJNI.Base_foo(swigCPtr, this); + } + + public Base() { + this(exampleJNI.new_Base(), true); + } + +}Here both int and unsigned short map onto a Java int. Here is - another example:
+The Derived class extends Base mirroring the C++ + class inheritance hierarchy.
--void foo(Bar *b); -void foo(Bar &b); +public class Derived extends Base { + private transient long swigCPtr; + + protected Derived(long cPtr, boolean cMemoryOwn) { + super(exampleJNI.SWIGDerivedUpcast(cPtr), cMemoryOwn); + swigCPtr = cPtr; + } + + protected static long getCPtr(Derived obj) { + return (obj == null) ? 0 : obj.swigCPtr; + } + + protected void finalize() { + delete(); + } + + public synchronized void delete() { + if(swigCPtr != 0 && swigCMemOwn) { + swigCMemOwn = false; + exampleJNI.delete_Derived(swigCPtr); + } + swigCPtr = 0; + super.delete(); + } + + public double foo() { + return exampleJNI.Derived_foo(swigCPtr, this); + } + + public Derived() { + this(exampleJNI.new_Derived(), true); + } + +}If declarations such as these appear, you will get a warning message - like this:
+Note the memory ownership is controlled by the base class. However + each class in the inheritance hierarchy has its own pointer value which + is obtained during construction. The SWIGDerivedUpcast() call + converts the pointer from a Derived * to a Base *. + This is a necessity as C++ compilers are free to implement pointers in + the inheritance hierarchy with different values.
+It is of course possible to extend Base using your own Java + classes. If Derived is provided by the C++ code, you could for + example add in a pure Java class Extended derived from +Base. There is a caveat and that is any C++ code will not know + about your pure Java class Extended so this type of derivation + is restricted. However, true cross language polymorphism can be + achieved using the directors feature.
+25.4.3.3 Proxy classes and garbage + collection
+By default each proxy class has a delete() and a +finalize() method. The finalize() method calls +delete() which frees any malloc'd memory for wrapped C structs or + calls the C++ class destructors. The idea is for delete() to + be called when you have finished with the C/C++ object. Ideally you + need not call delete(), but rather leave it to the garbage + collector to call it from the finalizer. When a program exits, the + garbage collector does not guarantee to call all finalizers. An insight + into the reasoning behind this can be obtained from +Hans Boehm's Destructors, Finalizers, and Synchronization paper. + Depending on what the finalizers do and which operating system you use, + this may or may not be a problem.
+If the delete() call into JNI code is just for memory + handling, there is not a problem when run on most operating systems, + for example Windows and Unix. Say your JNI code creates memory on the + heap which your finalizers should clean up, the finalizers may or may + not be called before the program exits. In Windows and Unix all memory + that a process uses is returned to the system on exit, so this isn't a + problem. This is not the case in some operating systems like vxWorks. + If however, your finalizer calls into JNI code invoking the C++ + destructor which in turn releases a TCP/IP socket for example, there is + no guarantee that it will be released. Note that with long running + programs the garbage collector will eventually run, thereby calling any + unreferenced object's finalizers.
+Some not so ideal solutions are:
++
+- +
+Call the System.runFinalizersOnExit(true) or +Runtime.getRuntime().runFinalizersOnExit(true) to ensure the + finalizers are called before the program exits. The catch is that this + is a deprecated function call as the documentation says:
+This method is inherently unsafe. It may result in + finalizers being called on live objects while other threads are + concurrently manipulating those objects, resulting in erratic behavior + or deadlock.+In many cases you will be lucky and find that it works, but it is not + to be advocated. Have a look at +Java web site and search for runFinalizersOnExit.
+- +
+From jdk1.3 onwards a new function, addShutdownHook(), was + introduced which is guaranteed to be called when your program exits. + You can encourage the garbage collector to call the finalizers, for + example, add this static block to the class that has the main() + function:
--example.i:12: Warning 515: Overloaded method spam(unsigned short) ignored. -Method spam(int) at example.i:11 used. + static { + Runtime.getRuntime().addShutdownHook( + new Thread() { + public void run() { System.gc(); System.runFinalization(); } + } + ); + }To fix this, you either need to either -rename or ignore one of the methods. For example:
+Although this usually works, the documentation doesn't guarantee that + runFinalization() will actually call the finalizers. As the + shutdown hook is guaranteed you could also make a JNI call to clean up + any resources that are being tracked by the C/C++ code.
+- +
+Call the delete() function manually which will immediately + invoke the C++ destructor. As a suggestion it may be a good idea to set + the object to null so that should the object be inadvertently used + again a Java null pointer exception is thrown, the alternative would + crash the JVM by using a null C pointer. For example given a SWIG + generated class A:
--%rename(spam_ushort) spam(unsigned short); -... -void spam(int); -void spam(unsigned short); // Now renamed to spam_ushort +A myA = new A(); +// use myA ... +myA.delete(); +// any use of myA here would crash the JVM +myA=null; +// any use of myA here would cause a Java null pointer exception to be thrownor
+The SWIG generated code ensures that the memory is not deleted + twice, in the event the finalizers get called in addition to the manual + delete() call.
+- +
+Write your own object manager in Java. You could derive all SWIG + classes from a single base class which could track which objects have + had their finalizers run, then call the rest of them on program + termination. The section on Java typemaps + details how to specify a pure Java base class.
+See the How to + Handle Java Finalization's Memory-Retention Issues article for + alternative approaches to managing memory by avoiding finalizers + altogether.
+25.4.3.4 The premature garbage collection + prevention parameter for proxy class marshalling
+As covered earlier, the C/C++ struct/class pointer is stored in the + proxy class as a Java long and when needed is passed into the native + method where it is cast into the appropriate type. This approach + provides very fast marshalling but could be susceptible to premature + garbage collection. Consider the following C++ code:
--%ignore spam(unsigned short); -... -void spam(int); -void spam(unsigned short); // Ignored +class Wibble { +}; +void wobble(Wibble &w);24.3.12 C++ default arguments
-Any function with a default argument is wrapped by generating an - additional function for each argument that is defaulted. For example, - if we have the following C++:
+The module class contains the Java wrapper for the global wobble + method:
--%module example - -void defaults(double d=10.0, int i=0); +public class example { + ... + public static void wobble(Wibble w) { + exampleJNI.wobble(Wibble.getCPtr(w), w); + } +}The following methods are generated in the Java module class:
+where example is the name of the module. All native methods + go through the intermediary class which has the native method declared + as such:
--public class example { - public static void defaults(double d, int i) { ... } - public static void defaults(double d) { ... } - public static void defaults() { ... } +public class exampleJNI { + ... + public final static native void wobble(long jarg1, Wibble jarg1_); }It is as if SWIG had parsed three separate overloaded methods. The - same approach is taken for static methods, constructors and member - methods.
-Compatibility note: Versions of SWIG prior to SWIG-1.3.23 - wrapped these with a single wrapper method and so the default values - could not be taken advantage of from Java. Further details on default - arguments and how to restore this approach are given in the more - general Default arguments section.
-24.3.13 C++ namespaces
-SWIG is aware of named C++ namespaces and they can be mapped to Java - packages, however, the default wrapping flattens the namespaces, - effectively ignoring them. So by default, the namespace names do not - appear in the module nor do namespaces result in a module that is - broken up into submodules or packages. For example, if you have a file - like this,
+The second parameter, jarg1_, is the premature garbage + collection prevention parameter and is added to the native method + parameter list whenever a C/C++ struct or class is marshalled as a Java + long. In order to understand why, consider the alternative where the + intermediary class method is declared without the additional parameter:
--%module example - -namespace foo { - int fact(int n); - struct Vector { - double x,y,z; - }; -}; +public class exampleJNI { + ... + public final static native void wobble(long jarg1); +}it works in Java as follows:
+and the following simple call to wobble:
--int f = example.fact(3); -Vector v = new Vector(); -v.setX(3.4); -double y = v.getY(); +{ + Wibble w = new Wibble(); + example.wobble(w); +}If your program has more than one namespace, name conflicts (if any) - can be resolved using %rename For example:
+The hotspot compiler effectively sees something like:
+-%rename(Bar_spam) Bar::spam; - -namespace Foo { - int spam(); +{ + Wibble w = new Wibble(); + long w_ptr = Wibble.getCPtr(w); + // w is no longer reachable + exampleJNI.wobble(w_ptr); } - -namespace Bar { - int spam(); ++The Wibble object is no longer reachable after the point + shown as in this bit of code, the Wibble object is not + referenced again after this point. This means that it is a candidate + for garbage collection. Should wobble be a long running + method, it is quite likely that the finalizer for the Wibble + instance will be called. This in turn will call its underlying C++ + destructor which is obviously disastrous while the method wobble + is running using this object. Even if wobble is not a long + running method, it is possible for the Wibble instance to be + finalized. By passing the Wibble instance into the native + method, it will not be finalized as the JVM guarantees not to finalize + any objects until the native method returns. Effectively, the code then + becomes
++-+{ + Wibble w = new Wibble(); + long w_ptr = Wibble.getCPtr(w); + exampleJNI.wobble(w_ptr, w); + // w is no longer reachable }If you have more than one namespace and you want to keep their - symbols separate, consider wrapping them as separate SWIG modules. Each - SWIG module can be placed into a separate package.
-The default behaviour described above can be improved via the -nspace feature. Note that it only works for classes, structs, unions - and enums declared within a named C++ namespace. When the nspace - feature is used, the C++ namespaces are converted into Java packages of - the same name. Proxy classes are thus declared within a package and - this proxy makes numerous calls to the JNI intermediary class which is - declared in the unnamed package by default. As Java does not support - types declared in a named package accessing types declared in an - unnamed package, the -package commandline option described - earlier generally should be used to provide a parent package. So if - SWIG is run using the -package com.myco option, a wrapped - class, MyWorld::Material::Color, can then be accessed as -com.myco.MyWorld.Material.Color. If you don't specify a package, - you will get the following warning:
-+-and therefore there is no possibility of premature garbage + collection. In practice, this premature garbage collection was only + ever observed in Sun's server JVM from jdk-1.3 onwards and in Sun's + client JVM from jdk-1.6 onwards.
+The premature garbage collection prevention parameter for proxy + classes is generated by default whenever proxy classes are passed by + value, reference or with a pointer. The implementation for this extra + parameter generation requires the "jtype" typemap to contain long + and the "jstype" typemap to contain the name of a proxy class.
+The additional parameter does impose a slight performance overhead + and the parameter generation can be suppressed globally with the +-nopgcpp commandline option. More selective suppression is possible + with the 'nopgcpp' attribute in the "jtype" +Java typemap. The attribute is a flag and so should be set to "1" to + enable the suppression, or it can be omitted or set to "0" to disable. + For example:
+--example.i:16: Warning 826: The nspace feature is used on 'MyWorld::Material::Color' without -package. The generated code -may not compile as Java does not support types declared in a named package accessing types declared in an unnamed package. +%typemap(jtype, nopgcpp="1") Wibble & "long"If it is undesirable to have a single top level package, the nspace - feature may be used without the -package commandline option - (and the resulting warning ignored) if all of the types exposed using - SWIG are placed in a package using the nspace feature and the - 'jniclasspackage' pragma is used to specify a package for the JNI - intermediary class.
-If the resulting use of the nspace feature and hence packages - results in a proxy class in one package deriving or using a proxy class - from another package, you will need to open up the visibility for the - pointer constructor and getCPtr method from the default - 'protected' to 'public' with the SWIG_JAVABODY_PROXY macro. - See Java code typemaps.
-24.3.14 C++ templates
-C++ templates don't present a huge problem for SWIG. However, in - order to create wrappers, you have to tell SWIG to create wrappers for - a particular template instantiation. To do this, you use the -%template directive. For example:
+Compatibility note: The generation of this additional + parameter did not occur in versions prior to SWIG-1.3.30.
+25.4.3.5 Single threaded + applications and thread safety
+Single threaded Java applications using JNI need to consider thread + safety. The same applies for the C# module where the .NET wrappers use + PInvoke. Consider the C++ class:
--%module example -%{ -#include <utility> -%} - -template<class T1, class T2> -struct pair { - typedef T1 first_type; - typedef T2 second_type; - T1 first; - T2 second; - pair(); - pair(const T1&, const T2&); - ~pair(); +class Test { + string str; +public: + Test() : str("initial") {} }; - -%template(pairii) pair<int,int>;In Java:
+and the Java proxy class generated by SWIG:
--pairii p = new pairii(3,4); -int first = p.getFirst(); -int second = p.getSecond(); +public class Test { + private transient long swigCPtr; + protected transient boolean swigCMemOwn; + + protected Test(long cPtr, boolean cMemoryOwn) { + swigCMemOwn = cMemoryOwn; + swigCPtr = cPtr; + } + + protected static long getCPtr(Test obj) { + return (obj == null) ? 0 : obj.swigCPtr; + } + + protected void finalize() { + delete(); + } + + // Call C++ destructor + public synchronized void delete() { + if(swigCPtr != 0 && swigCMemOwn) { + swigCMemOwn = false; + exampleJNI.delete_Test(swigCPtr); + } + swigCPtr = 0; + } + + // Call C++ constructor + public Test() { + this(exampleJNI.new_Test(), true); + } + +}Obviously, there is more to template wrapping than shown in this - example. More details can be found in the SWIG and - C++ chapter.
-24.3.15 C++ Smart Pointers
-In certain C++ programs, it is common to use classes that have been - wrapped by so-called "smart pointers." Generally, this involves the use - of a template class that implements operator->() like this:
+It has two methods that call JNI methods, namely, +exampleJNI.new_Test() for the C++ constructor and +exampleJNI.delete_Test() for the C++ destructor. If the garbage + collector collects an instance of this class, ie delete() is + not explicitly called, then the C++ destructor will be run in a + different thread to the main thread. This is because when an object is + marked for garbage collection, any objects with finalizers are added to + a finalization queue and the objects in the finalization queue have + their finalize() methods run in a separate finalization + thread. Therefore, if the C memory allocator is not thread safe, then + the heap will get corrupted sooner or later, when a concurrent C++ + delete and new are executed. It is thus essential, even in single + threaded usage, to link to the C multi-thread runtime libraries, for + example, use the /MD option for Visual C++ on Windows. Alternatively, + lock all access to C++ functions that have heap + allocation/deallocation.
+Note that some of the STL in Visual C++ 6 is not thread safe, so + although code might be linked to the multithread runtime libraries, + undefined behaviour might still occur in a single threaded Java + program. Similarly some older versions of Sun Studio have bugs in the + multi-threaded implementation of the std::string class and so will lead + to undefined behaviour in these supposedly single threaded Java + applications.
+The following innocuous Java usage of Test is an example that will + crash very quickly on a multiprocessor machine if the JNI compiled code + is linked against the single thread C runtime libraries.
--template<class T> class SmartPtr { - ... - T *operator->(); - ... +for (int i=0; i<100000; i++) { + System.out.println("Iteration " + i); + for (int k=0; k<10; k++) { + Test test = new Test(); + } + System.gc(); }Then, if you have a class like this,
+25.4.4 Type wrapper classes
+The generated type wrapper class, for say an int *, looks + like this:
--class Foo { -public: - int x; - int bar(); -}; +public class SWIGTYPE_p_int { + private transient long swigCPtr; + + protected SWIGTYPE_p_int(long cPtr, boolean bFutureUse) { + swigCPtr = cPtr; + } + + protected SWIGTYPE_p_int() { + swigCPtr = 0; + } + + protected static long getCPtr(SWIGTYPE_p_int obj) { + return obj.swigCPtr; + } +}A smart pointer would be used in C++ as follows:
+The methods do not have public access, so by default it is + impossible to do anything with objects of this class other than pass + them around. The methods in the class are part of the inner workings of + SWIG. If you need to mess around with pointers you will have to use + some typemaps specific to the Java module to achieve this. The section + on Java typemaps details how to modify the + generated code.
+Note that if you use a pointer or reference to a proxy class in a + function then no type wrapper class is generated because the proxy + class can be used as the function parameter. If however, you need + anything more complicated like a pointer to a pointer to a proxy class + then a typewrapper class is generated for your use.
+Note that SWIG generates a type wrapper class and not a proxy class + when it has not parsed the definition of a type that gets used. For + example, say SWIG has not parsed the definition of class Snazzy + because it is in a header file that you may have forgotten to use the +%include directive on. Should SWIG parse Snazzy * being + used in a function parameter, it will then generates a type wrapper + class around a Snazzy pointer. Also recall from earlier that + SWIG will use a pointer when a class is passed by value or by + reference:
--SmartPtr<Foo> p = CreateFoo(); // Created somehow (not shown) -... -p->x = 3; // Foo::x -int y = p->bar(); // Foo::bar +void spam(Snazzy *x, Snazzy &y, Snazzy z);To wrap this in Java, simply tell SWIG about the SmartPtr - class and the low-level Foo object. Make sure you instantiate -SmartPtr using %template if necessary. For example:
+Should SWIG not know anything about Snazzy then a +SWIGTYPE_p_Snazzy must be used for all 3 parameters in the spam + function. The Java function generated is:
--%module example -... -%template(SmartPtrFoo) SmartPtr<Foo>; -... +public static void spam(SWIGTYPE_p_Snazzy x, SWIGTYPE_p_Snazzy y, SWIGTYPE_p_Snazzy z) { + ... +}Now, in Java, everything should just "work":
+Note that typedefs are tracked by SWIG and the typedef name is used + to construct the type wrapper class name. For example, consider the + case where Snazzy is a typedef to an int which SWIG + does parse:
--SmartPtrFoo p = example.CreateFoo(); // Create a smart-pointer somehow -p.setX(3); // Foo::x -int y = p.bar(); // Foo::bar +typedef int Snazzy; +void spam(Snazzy *x, Snazzy &y, Snazzy z);If you ever need to access the underlying pointer returned by -operator->() itself, simply use the __deref__() method. - For example:
+Because the typedefs have been tracked the Java function generated + is:
--Foo f = p.__deref__(); // Returns underlying Foo * +public static void spam(SWIGTYPE_p_int x, SWIGTYPE_p_int y, int z) { ... }24.4 Further details on the - generated Java classes
-In the previous section, a high-level view of Java wrapping was - presented. A key component of this wrapping is that structures and - classes are wrapped by Java proxy classes and type wrapper classes are - used in situations where no proxies are generated. This provides a very - natural, type safe Java interface to the C/C++ code and fits in with - the Java programming paradigm. However, a number of low-level details - were omitted. This section provides a brief overview of how the proxy - classes work and then covers the type wrapper classes. Finally enum - classes are covered. First, the crucial intermediary JNI class is - considered.
-24.4.1 The intermediary JNI class
-In the "SWIG basics" and -"SWIG and C++" chapters, details of low-level structure and class - wrapping are described. To summarize those chapters, if you have a - global function and class like this
+25.4.5 Enum classes
+SWIG can generate three types of enum classes. The +Enumerations section discussed these but omitted all the details. + The following sub-sections detail the various types of enum classes + that can be generated.
+25.4.5.1 Typesafe enum classes +
+The following example demonstrates the typesafe enum classes which + SWIG generates:
--class Foo { -public: - int x; - int spam(int num, Foo* foo); -}; -void egg(Foo* chips); +%include "enumtypesafe.swg" +%javaconst(1); +enum Beverage { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER };then SWIG transforms the class into a set of low-level procedural - wrappers. These procedural wrappers essentially perform the equivalent - of this C++ code:
+The following is the code that SWIG generates:
--Foo *new_Foo() { - return new Foo(); -} -void delete_Foo(Foo *f) { - delete f; -} -int Foo_x_get(Foo *f) { - return f->x; -} -void Foo_x_set(Foo *f, int value) { - f->x = value; -} -int Foo_spam(Foo *f, int num, Foo* foo) { - return f->spam(num, foo); +public final class Beverage { + public final static Beverage ALE = new Beverage("ALE"); + public final static Beverage LAGER = new Beverage("LAGER", 10); + public final static Beverage STOUT = new Beverage("STOUT"); + public final static Beverage PILSNER = new Beverage("PILSNER"); + public final static Beverage PILZ = new Beverage("PILZ", PILSNER); + + public final int swigValue() { + return swigValue; + } + + public String toString() { + return swigName; + } + + public static Beverage swigToEnum(int swigValue) { + if (swigValue < swigValues.length && swigValue >= 0 && + swigValues[swigValue].swigValue == swigValue) + return swigValues[swigValue]; + for (int i = 0; i < swigValues.length; i++) + if (swigValues[i].swigValue == swigValue) + return swigValues[i]; + throw new IllegalArgumentException("No enum " + Beverage.class + " with value " + + swigValue); + } + + private Beverage(String swigName) { + this.swigName = swigName; + this.swigValue = swigNext++; + } + + private Beverage(String swigName, int swigValue) { + this.swigName = swigName; + this.swigValue = swigValue; + swigNext = swigValue+1; + } + + private Beverage(String swigName, Beverage swigEnum) { + this.swigName = swigName; + this.swigValue = swigEnum.swigValue; + swigNext = this.swigValue+1; + } + + private static Beverage[] swigValues = { ALE, LAGER, STOUT, PILSNER, PILZ }; + private static int swigNext = 0; + private final int swigValue; + private final String swigName; }These procedural function names don't actually exist, but their - functionality appears inside the generated JNI functions. The JNI - functions have to follow a particular naming convention so the function - names are actually:
+As can be seen, there are a fair number of support methods for the + typesafe enum pattern. The typesafe enum pattern involves creating a + fixed number of static instances of the enum class. The constructors + are private to enforce this. Three constructors are available - two for + C/C++ enums with an initializer and one for those without an + initializer. Note that the two enums with initializers, LAGER + and PILZ, each call one the two different initializer + constructors. In order to use one of these typesafe enums, the +swigToEnum static method must be called to return a reference to + one of the static instances. The JNI layer returns the enum value from + the C/C++ world as an integer and this method is used to find the + appropriate Java enum static instance. The swigValue method is + used for marshalling in the other direction. The toString + method is overridden so that the enum name is available.
+25.4.5.2 Proper Java enum + classes
+The following example demonstrates the Java enums approach:
--SWIGEXPORT jlong JNICALL Java_exampleJNI_new_1Foo(JNIEnv *jenv, jclass jcls); -SWIGEXPORT void JNICALL Java_exampleJNI_delete_1Foo(JNIEnv *jenv, jclass jcls, - jlong jarg1); -SWIGEXPORT void JNICALL Java_exampleJNI_Foo_1x_1set(JNIEnv *jenv, jclass jcls, - jlong jarg1, jobject jarg1_, jint jarg2); -SWIGEXPORT jint JNICALL Java_exampleJNI_Foo_1x_1get(JNIEnv *jenv, jclass jcls, - jlong jarg1, jobject jarg1_); -SWIGEXPORT jint JNICALL Java_exampleJNI_Foo_1spam(JNIEnv *jenv, jclass jcls, - jlong jarg1, jobject jarg1_, jint jarg2, - jlong jarg3, jobject jarg3_); -SWIGEXPORT void JNICALL Java_exampleJNI_egg(JNIEnv *jenv, jclass jcls, - jlong jarg1, jobject jarg1_); +%include "enums.swg" +%javaconst(1); +enum Beverage { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER };For every JNI C function there has to be a static native Java - function. These appear in the intermediary JNI class:
+SWIG will generate the following Java enum:
--class exampleJNI { - public final static native long new_Foo(); - public final static native void delete_Foo(long jarg1); - public final static native void Foo_x_set(long jarg1, Foo jarg1_, int jarg2); - public final static native int Foo_x_get(long jarg1, Foo jarg1_); - public final static native int Foo_spam(long jarg1, Foo jarg1_, int jarg2, - long jarg3, Foo jarg3_); - public final static native void egg(long jarg1, Foo jarg1_); +public enum Beverage { + ALE, + LAGER(10), + STOUT, + PILSNER, + PILZ(PILSNER); + + public final int swigValue() { + return swigValue; + } + + public static Beverage swigToEnum(int swigValue) { + Beverage[] swigValues = Beverage.class.getEnumConstants(); + if (swigValue < swigValues.length && swigValue >= 0 && + swigValues[swigValue].swigValue == swigValue) + return swigValues[swigValue]; + for (Beverage swigEnum : swigValues) + if (swigEnum.swigValue == swigValue) + return swigEnum; + throw new IllegalArgumentException("No enum " + Beverage.class + + " with value " + swigValue); + } + + private Beverage() { + this.swigValue = SwigNext.next++; + } + + private Beverage(int swigValue) { + this.swigValue = swigValue; + SwigNext.next = swigValue+1; + } + + private Beverage(Beverage swigEnum) { + this.swigValue = swigEnum.swigValue; + SwigNext.next = this.swigValue+1; + } + + private final int swigValue; + + private static class SwigNext { + private static int next = 0; + } }This class contains the complete Java - C/C++ interface so all - function calls go via this class. As this class acts as a go-between - for all JNI calls to C/C++ code from the Java -proxy classes, type wrapper - classes and module class, it is - known as the intermediary JNI class.
-You may notice that SWIG uses a Java long wherever a pointer or - class object needs to be marshalled across the Java-C/C++ boundary. - This approach leads to minimal JNI code which makes for better - performance as JNI code involves a lot of string manipulation. SWIG - favours generating Java code over JNI code as Java code is compiled - into byte code and avoids the costly string operations needed in JNI - code. This approach has a downside though as the proxy class might get - collected before the native method has completed. You might notice - above that there is an additional parameters with a underscore postfix, - eg jarg1_. These are added in order to prevent -premature garbage collection when marshalling proxy classes.
-The functions in the intermediary JNI class cannot be accessed - outside of its package. Access to them is gained through the module - class for globals otherwise the appropriate proxy class.
- -The name of the intermediary JNI class can be changed from its - default, that is, the module name with JNI appended after it. The - module directive attribute jniclassname is used to achieve - this:
+The enum items appear first. Like the typesafe enum pattern, the + constructors are private. The constructors are required to handle C/C++ + enums with initializers. The next variable is in the +SwigNext inner class rather than in the enum class as static + primitive variables cannot be modified from within enum constructors. + Marshalling between Java enums and the C/C++ enum integer value is + handled via the swigToEnum and swigValue methods. All + the constructors and methods in the Java enum are required just to + handle C/C++ enums with initializers. These needn't be generated if the + enum being wrapped does not have any initializers and the +Simpler Java enums for enums without initializers section describes + how typemaps can be used to achieve this.
+25.4.5.3 Type unsafe enum + classes
+The following example demonstrates type unsafe enums:
++++%include "enumtypeunsafe.swg" +%javaconst(1); +enum Beverage { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER }; ++SWIG will generate the following simple class:
--%module (jniclassname="name") modulename +public final class Beverage { + public final static int ALE = 0; + public final static int LAGER = 10; + public final static int STOUT = LAGER + 1; + public final static int PILSNER = STOUT + 1; + public final static int PILZ = PILSNER; +}If name is the same as modulename then the module - class name gets changed from modulename to -modulenameModule.
-24.4.1.1 The intermediary JNI - class pragmas
-The intermediary JNI class can be tailored through the use of - pragmas, but is not commonly done. The pragmas for this class are:
--
-- Pragma Description jniclassbase Base class for the intermediary JNI class +25.4.6 Interfaces
+By default SWIG wraps all C++ classes as Java classes. As Java only + supports derivation from a single base class, SWIG has to ignore all + bases except the first when a C++ class inherits from more than one + base class. However, there is a family of SWIG macros that change the + default wrapping and allows a C++ class to be wrapped as a Java + interface instead of a Java class. These macros provide a way to + support some sort of multiple inheritance as there is no limit to the + number of interfaces that a Java class can inherit from.
+When a C++ class is wrapped as a Java interface, a Java proxy class + is still needed. The swiginterface.i library file provides + three macros for marking a C++ class to be wrapped as a Java interface. + There is more than one macro in order to provide a choice for choosing + the Java interface and Java proxy names.
++
++ Interface Macro Name Description + + %interface(CTYPE) Proxy class name is + unchanged, interface name has SwigInterface added as a suffix + for C++ class CTYPE. + %interface_impl(CTYPE) Proxy class name has +SwigImpl as a suffix, interface name has SwigInterface + added as a suffix for C++ class CTYPE. + %interface_custom("PROXY", "INTERFACE", CTYPE) +Proxy class name is given by the string PROXY, interface name + is given by the string INTERFACE for C++ class CTYPE. + The PROXY and INTERFACE names can use the +string formatting functions used in %rename. The table below has a few examples showing the resulting proxy and + interface names.
++
-+ Example Usage Proxy Class Name + Interface Class Name + %interface(Base) Base +BaseSwigInterface + %interface_impl(Base) BaseSwigImpl +Base + %interface_custom("BaseProxy", "IBase", Base) +BaseProxy IBase + %interface_custom("%sProxy", "IBase", Base) +BaseProxy IBase + %interface_custom("%sProxy", "%sInterface", Base) +BaseProxy BaseProxyInterface - %interface_custom("%sProxy", "%(rstrip:[Proxy])sInterface", + Base) BaseProxy BaseInterface - jniclasspackage Package in which to place the - intermediary JNI class - jniclassclassmodifiers Class modifiers and class type - for the intermediary JNI class - jniclasscode Java code is copied verbatim into the - intermediary JNI class - jniclassimports Java code, usually one or more import - statements, placed before the intermediary JNI class definition jniclassinterfaces Comma separated interface classes for - the intermediary JNI class The pragma code appears in the generated intermediary JNI class - where you would expect:
+The 2nd last example shows the names used in the string formatting + functions. The input for PROXY that "%s" expands to + is the proxy name, that is, Base. The input for INTERFACE that + "%s" expands to is the proxy name, that is, BaseProxy +.
+The last example shows rstrip and in this case strips the +Proxy suffix and then adds on Interface.
+Consider the following C++ code:
--[ jniclassimports pragma ] -[ jniclassclassmodifiers pragma ] jniclassname extends [ jniclassbase pragma ] - implements [ jniclassinterfaces pragma ] { -[ jniclasscode pragma ] -... SWIG generated native methods ... +namespace Space { + struct Base1 { + virtual void Method1(); + }; + struct Base2 { + virtual void Method2(); + }; + struct Derived : Base1, Base2 { + }; + void UseBases(const Base1 &b1, const Base2 &b2); }The jniclasscode pragma is quite useful for adding in a - static block for loading the shared library / dynamic link library and - demonstrates how pragmas work:
-++By default all classes are wrapped and are available in Java, but, +Derived has all bases ignored except the first. SWIG generates a + warning for the above code:
+--%pragma(java) jniclasscode=%{ - static { - try { - System.loadLibrary("example"); - } catch (UnsatisfiedLinkError e) { - System.err.println("Native code library failed to load. \n" + e); - System.exit(1); - } - } -%} +example.i:10: Warning 813: Warning for Derived, base Base2 ignored. +Multiple inheritance is not supported in Java.Pragmas will take either "" or %{ %} as - delimiters. For example, let's change the intermediary JNI class access - to just the default package-private access.
+If we decide to wrap the two base classes as interfaces and add the + following before SWIG parses the above example code:
--%pragma(java) jniclassclassmodifiers="class" +%include <swiginterface.i> +%interface_impl(Space::Base1); +%interface_impl(Space::Base2);All the methods in the intermediary JNI class will then not be - callable outside of the package as the method modifiers have been - changed from public access to default access. This is useful if you - want to prevent users calling these low level functions.
-24.4.2 The Java module class
-All global functions and variable getters/setters appear in the - module class. For our example, there is just one function:
+then two interface files are generated, Base1.java and Base2.java in + addition to proxy class files, Base1SwigImpl.java and + Base2SwigImpl.java. The contents of interface file Base1.java for +Base1 is shown below:
--public class example { - public static void egg(Foo chips) { - exampleJNI.egg(Foo.getCPtr(chips), chips); - } +public interface Base1 { + long Base1_GetInterfaceCPtr(); + void Method1(); }The module class is necessary as there is no such thing as a global - in Java so all the C globals are put into this class. They are - generated as static functions and so must be accessed as such by using - the module name in the static function call:
----example.egg(new Foo()); --The primary reason for having the module class wrapping the calls in - the intermediary JNI class is to implement static type checking. In - this case only a Foo can be passed to the egg - function, whereas any long can be passed to the egg - function in the intermediary JNI class.
-24.4.2.1 The Java module - class pragmas
-The module class can be tailored through the use of pragmas, in the - same manner as the intermediary JNI class. The pragmas are similarly - named and are used in the same way. The complete list follows:
--
-- Pragma Description - modulebase Base class for the module class - moduleclassmodifiers Class modifiers and class type for - the module class - modulecode Java code is copied verbatim into the module - class - moduleimports Java code, usually one or more import - statements, placed before the module class definition - moduleinterfaces Comma separated interface classes for - the module class The pragma code appears in the generated module class like this:
+The proxy class in Base1SwigImpl.java for Base1 is as it would have + been if %interface was not used, except the name has changed + to Base1SwigImpl and it implements the appropriate base:
--[ moduleimports pragma ] -[ modulemodifiers pragma ] modulename extends [ modulebase pragma ] - implements [ moduleinterfaces pragma ] { -[ modulecode pragma ] -... SWIG generated wrapper functions ... +public class Base1SwigImpl implements Base1 { +... + public long Base1_GetInterfaceCPtr() { + return exampleJNI.Base1SwigImpl_Base1_GetInterfaceCPtr(swigCPtr); + } + + public void Method1() { + exampleJNI.Base1SwigImpl_Method1(swigCPtr, this); + } +... }See The intermediary JNI class - pragmas section for further details on using pragmas.
-24.4.3 Java proxy classes
-A Java proxy class is generated for each structure, union or C++ - class that is wrapped. Proxy classes have also been called -peer classes. The default proxy class for our previous example looks - like this:
+In fact any class deriving from Base will now implement the + interface instead of deriving from it (or ignoring the base in the case + of multiple base classes). Hence the Derived proxy class will + now implement both bases:
+-public class Foo { - private long swigCPtr; - protected boolean swigCMemOwn; - - protected Foo(long cPtr, boolean cMemoryOwn) { - swigCMemOwn = cMemoryOwn; - swigCPtr = cPtr; +public class Derived implements Base1, Base2 { +... + public long Base1_GetInterfaceCPtr() { + return exampleJNI.Derived_Base1_GetInterfaceCPtr(swigCPtr); } - protected static long getCPtr(Foo obj) { - return (obj == null) ? 0 : obj.swigCPtr; + public long Base2_GetInterfaceCPtr() { + return exampleJNI.Derived_Base2_GetInterfaceCPtr(swigCPtr); } - protected void finalize() { - delete(); + public void Method1() { + exampleJNI.Derived_Method1(swigCPtr, this); } - public synchronized void delete() { - if(swigCPtr != 0 && swigCMemOwn) { - swigCMemOwn = false; - exampleJNI.delete_Foo(swigCPtr); - } - swigCPtr = 0; + public void Method2() { + exampleJNI.Derived_Method2(swigCPtr, this); } - - public void setX(int value) { - exampleJNI.Foo_x_set(swigCPtr, this, value); +... +} ++Wherever a class marked as an interface is used, such as the +UseBases method in the example, the interface name is used as the + type in the Java layer:
++++ public static void UseBases(Base1 b1, Base2 b2) { + exampleJNI.UseBases(b1.Base1_GetInterfaceCPtr(), b1, b2.Base2_GetInterfaceCPtr(), b2); } ++Note that each Java interface has a method added to obtain the + correct C++ pointer for passing to the native function - +Base1_GetInterfaceCPtr for Base1. This method is similar + to the getCPtr method in the proxy classes. In fact, as shown + above in the Derived class, the proxy classes implement this + generated interface by calling a native method ( +Derived_Base1_GetInterfaceCPtr) which calls an appropriate C++ cast + of the pointer up the inheritance chain.
+The interface macros are implemented using the interface + feature and typemaps. For example:
++++%define %interface(CTYPE...) +%feature("interface", name="%sSwigInterface") CTYPE; +INTERFACE_TYPEMAPS(CTYPE) +%enddef ++The feature accepts one attribute called name, which is the + name of the Java interface mentioned earlier. The +INTERFACE_TYPEMAPS macro implements the typemaps and can be viewed + in the swiginterface.i file and contain the usual Java + typemaps for generating code plus the javainterfacecode + typemap which is only used when a class is marked with the +interface feature. See Java code + typemaps for details.
+25.5 Cross language polymorphism using + directors
+Proxy classes provide a natural, object-oriented way to wrap C++ + classes. as described earlier, each proxy instance has an associated + C++ instance, and method calls from Java to the proxy are passed to the + C++ instance transparently via C wrapper functions.
+This arrangement is asymmetric in the sense that no corresponding + mechanism exists to pass method calls down the inheritance chain from + C++ to Java. In particular, if a C++ class has been extended in Java + (by deriving from the proxy class), these classes will not be visible + from C++ code. Virtual method calls from C++ are thus not able to + access the lowest implementation in the inheritance chain.
+SWIG can address this problem and make the relationship between C++ + classes and proxy classes more symmetric. To achieve this goal, new + classes called directors are introduced at the bottom of the C++ + inheritance chain. The job of the directors is to route method calls + correctly, either to C++ implementations higher in the inheritance + chain or to Java implementations lower in the inheritance chain. The + upshot is that C++ classes can be extended in Java and from C++ these + extensions look exactly like native C++ classes. Neither C++ code nor + Java code needs to know where a particular method is implemented: the + combination of proxy classes, director classes, and C wrapper functions + transparently takes care of all the cross-language method routing.
+25.5.1 Enabling directors
+The director feature is disabled by default. To use directors you + must make two changes to the interface file. First, add the "directors" + option to the %module directive, like this:
++++%module(directors="1") modulename ++Without this option no director code will be generated. Second, you + must use the %feature("director") directive to tell SWIG which classes + and methods should get directors. The %feature directive can be applied + globally, to specific classes, and to specific methods, like this:
++++// generate directors for all classes that have virtual methods +%feature("director"); - public int getX() { - return exampleJNI.Foo_x_get(swigCPtr, this); - } +// generate directors for all virtual methods in class Foo +%feature("director") Foo; ++You can use the %feature("nodirector") directive to turn off + directors for specific classes or methods. So for example,
++++%feature("director") Foo; +%feature("nodirector") Foo::bar; ++will generate directors for all virtual methods of class Foo except + bar().
+Directors can also be generated implicitly through inheritance. In + the following, class Bar will get a director class that handles the + methods one() and two() (but not three()):
++++%feature("director") Foo; +class Foo { +public: + virtual void one(); + virtual void two(); +}; - public int spam(int num, Foo foo) { - return exampleJNI.Foo_spam(swigCPtr, this, num, Foo.getCPtr(foo), foo); - } +class Bar: public Foo { +public: + virtual void three(); +}; ++25.5.2 Director classes
+For each class that has directors enabled, SWIG generates a new + class that derives from both the class in question and a special +Swig::Director class. These new classes, referred to as director + classes, can be loosely thought of as the C++ equivalent of the Java + proxy classes. The director classes store a pointer to their underlying + Java proxy classes.
+For simplicity let's ignore the Swig::Director class and + refer to the original C++ class as the director's base class. By + default, a director class extends all virtual methods in the + inheritance chain of its base class (see the preceding section for how + to modify this behavior). Thus all virtual method calls, whether they + originate in C++ or in Java via proxy classes, eventually end up in at + the implementation in the director class. The job of the director + methods is to route these method calls to the appropriate place in the + inheritance chain. By "appropriate place" we mean the method that would + have been called if the C++ base class and its Java derived classes + were seamlessly integrated. That seamless integration is exactly what + the director classes provide, transparently skipping over all the messy + JNI glue code that binds the two languages together.
+In reality, the "appropriate place" is one of only two + possibilities: C++ or Java. Once this decision is made, the rest is + fairly easy. If the correct implementation is in C++, then the lowest + implementation of the method in the C++ inheritance chain is called + explicitly. If the correct implementation is in Java, the Java API is + used to call the method of the underlying Java object (after which the + usual virtual method resolution in Java automatically finds the right + implementation).
+25.5.3 Overhead and code bloat
+Enabling directors for a class will generate a new director method + for every virtual method in the class' inheritance chain. This alone + can generate a lot of code bloat for large hierarchies. Method + arguments that require complex conversions to and from Java types can + result in large director methods. For this reason it is recommended + that directors are selectively enabled only for specific classes that + are likely to be extended in Java and used in C++.
+Although directors make it natural to mix native C++ objects with + Java objects (as director objects), one should be aware of the obvious + fact that method calls to Java objects from C++ will be much slower + than calls to C++ objects. Additionally, compared to classes that do + not use directors, the call routing in the director methods adds a + small overhead. This situation can be optimized by selectively enabling + director methods (using the %feature directive) for only those methods + that are likely to be extended in Java.
+25.5.4 Simple directors example
+Consider the following SWIG interface file:
++++%module(directors="1") example; - public Foo() { - this(exampleJNI.new_Foo(), true); +%feature("director") DirectorBase; + +class DirectorBase { +public: + virtual ~DirectorBase() {} + virtual void upcall_method() {} +}; + +void callup(DirectorBase *director) { + director->upcall_method(); +} ++The following
+DirectorDerived
Java class is derived + from the Java proxy classDirectorBase
and overrides+upcall_method()
. When C++ code invokesupcall_method()
+, the SWIG-generated C++ code redirects the call via JNI to the Java+DirectorDerived
subclass. Naturally, the SWIG generated C++ code + and the generated Java intermediary class marshal and convert arguments + between C++ and Java when needed.+-+public class DirectorDerived extends DirectorBase { + public DirectorDerived() { } + public void upcall_method() { + System.out.println("DirectorDerived::upcall_method() invoked."); + } }This class merely holds a pointer to the underlying C++ object ( -swigCPtr). It also contains all the methods in the C++ class it is - proxying plus getters and setters for public member variables. These - functions call the native methods in the intermediary JNI class. The - advantage of having this extra layer is the type safety that the proxy - class functions offer. It adds static type checking which leads to - fewer surprises at runtime. For example, you can see that if you - attempt to use the spam() function it will only compile when - the parameters passed are an int and a Foo. From a - user's point of view, it makes the class work as if it were a Java - class:
+Running the following Java code
--Foo f = new Foo(); -f.setX(3); -int y = f.spam(5, new Foo()); +DirectorDerived director = new DirectorDerived(); +example.callup(director);24.4.3.1 Memory management
-Each proxy class has an ownership flag swigCMemOwn. The - value of this flag determines who is responsible for deleting the - underlying C++ object. If set to true, the proxy class's - finalizer will destroy the C++ object when the proxy class is garbage - collected. If set to false, then the destruction of the proxy class has - no effect on the C++ object.
-When an object is created by a constructor or returned by value, - Java automatically takes ownership of the result. On the other hand, - when pointers or references are returned to Java, there is often no way - to know where they came from. Therefore, the ownership is set to false. - For example:
+will result in the following being output:
--class Foo { -public: - Foo(); - Foo bar1(); - Foo &bar2(); - Foo *bar2(); -}; +DirectorDerived::upcall_method() invoked.In Java:
+25.5.5 Director threading issues +
+Depending on your operating system and version of Java and how you + are using threads, you might find the JVM hangs on exit. There are a + couple of solutions to try out. The preferred solution requires jdk-1.4 + and later and uses AttachCurrentThreadAsDaemon instead of +AttachCurrentThread whenever a call into the JVM is required. This + can be enabled by defining the + SWIG_JAVA_ATTACH_CURRENT_THREAD_AS_DAEMON macro when compiling the C++ + wrapper code. For older JVMs define SWIG_JAVA_NO_DETACH_CURRENT_THREAD + instead, to avoid the DetachCurrentThread call but this will + result in a memory leak instead. For further details inspect the source + code in the java/director.swg library file.
+Macros can be defined on the commandline when compiling your C++ + code, or alternatively added to the C++ wrapper file as shown below:
--Foo f = new Foo(); // f.swigCMemOwn = true -Foo f1 = f.bar1(); // f1.swigCMemOwn = true -Foo f2 = f.bar2(); // f2.swigCMemOwn = false -Foo f3 = f.bar3(); // f3.swigCMemOwn = false +%insert("runtime") %{ +#define SWIG_JAVA_NO_DETACH_CURRENT_THREAD +%}This behavior for pointers and references is especially important - for classes that act as containers. For example, if a method returns a - pointer to an object that is contained inside another object, you - definitely don't want Java to assume ownership and destroy it!
-For the most part, memory management issues remain hidden. However, - there are situations where you might have to manually change the - ownership of an object. For instance, consider code like this:
+25.5.6 Director performance + tuning
+When a new instance of a director (or subclass) is created in Java, + the C++ side of the director performs a runtime check per director + method to determine if that particular method is overridden in Java or + if it should invoke the C++ base implementation directly. Although this + makes initialization slightly more expensive, it is generally a good + overall tradeoff.
+However, if all director methods are expected to usually be + overridden by Java subclasses, then initialization can be made faster + by avoiding these checks via the assumeoverride attribute. For + example:
--class Obj {}; -class Node { - Obj *value; -public: - void set_value(Obj *v) { value = v; } -}; +%feature("director", assumeoverride=1) Foo;Now, consider the following Java code:
+The disadvantage is that invocation of director methods from C++ + when Java doesn't actually override the method will require an + additional call up into Java and back to C++. As such, this option is + only useful when overrides are extremely common and instantiation is + frequent enough that its performance is critical.
+25.5.7 Java exceptions from + directors
+With directors routing method calls to Java, and proxies routing + them to C++, the handling of exceptions is an important concern. The + default behavior from SWIG 3.0 onwards is to convert the thrown Java + exception into a SWIG defined
+DirectorException
C++ + exception. SWIG 2.0 and earlier versions didn't provide any mechanism + to handle the Java director method exceptions in C++.Converting Java exceptions into C++ exceptions can be done in two + different ways using the
director:except
+feature. In the simplest approach, a code block is attached to each + director method to handle the mapping of Java exceptions into C++ + exceptions.+-Node n = new Node(); // Create a node -{ - Obj o = new Obj(); // Create an object - n.set_value(o); // Set value -} // o goes out of scope +%feature("director:except") MyClass::method(int x) { + jthrowable $error = jenv->ExceptionOccurred(); + if ($error) { + jenv->ExceptionClear(); + if (Swig::ExceptionMatches(jenv, $error, "java/lang/IndexOutOfBoundsException")) + throw std::out_of_range(Swig::JavaExceptionMessage(jenv, $error).message()); + if (Swig::ExceptionMatches(jenv, $error, "$packagepath/MyJavaException")) + throw MyCppException(Swig::JavaExceptionMessage(jenv, $error).message()); + throw std::runtime_error("Unexpected exception thrown in MyClass::method"); + } +} + +class MyClass { + /** Throws either a std::out_of_range or MyCppException on error */ + void method(int x); +} ++This approach allows a flexible mapping of Java exceptions thrown by + director methods into C++ exceptions expected by a C++ caller. There + need not be any C++ exception specifications on the C++ + method. The utility function
+Swig::ExceptionMatches
and + classSwig::JavaExceptionMessage
are provided to simplify + writing code for wrappers that use thedirector:except
+ feature. The functionSwig::ExceptionMatches
matches the + type of thejthrowable
thrown against a fully qualified + JNI style class name, such as"java/lang/IOError"
. If the + throwable class is the same type, or derives from the given type,+Swig::ExceptionMatches
will return true. Care must be taken to + provide the correct fully qualified name, since for wrapped exceptions + the generated proxy class will have additional package qualification, + depending on the '-package' argument and use of the +nspace feature. The special variable$error
is expanded + by SWIG into a unique variable name and should be used for the + assignment of the exception that occurred. The special variable+$packagepath
is replaced by the outer package provided for SWIG + generation by the -package option. The utility class+Swig::JavaExceptionMessage
is a holder providing access to the + message from the thrown Java exception. Themessage()
+ method returns the exception message as aconst char *
, + which is only valid during the lifetime of the holder. Any code using + this message needs to copy it, for example into a std::string or a + newly constructed C++ exception.Using the above approach to write handlers for a large number of + methods will require repetitive duplication of the
+director:except
feature code. To mitigate this, an alternative + approach is provided via typemaps in a fashion analagous to the +"throws" typemap. The "throws" typemap provides an approach to + automatically map all the C++ exceptions listed in a method's defined + exceptions (either from a C++ exception specification or a+%catches
feature) into Java exceptions. The "directorthrows" + typemap provides the inverse mapping and should contain code to convert + a suitably matching Java exception into a C++ exception. The example + below converts a Javajava.lang.IndexOutOfBoundsException
+ exception to the typemap's type, that isstd::out_of_range
+:+++%typemap(directorthrows) std::out_of_range %{ + if (Swig::ExceptionMatches(jenv, $error, "java/lang/IndexOutOfBoundsException")) { + throw std::out_of_range(Swig::JavaExceptionMessage(jenv, $error).message()); + } +%} ++The "directorthrows" typemap is then used in conjunction with the
++director:except
feature if the$directorthrowshandlers
+ special variable is used in the feature code. Consider the following, + which also happens to be the default:+-+%feature("director:except") %{ + jthrowable $error = jenv->ExceptionOccurred(); + if ($error) { + jenv->ExceptionClear(); + $directorthrowshandlers + throw Swig::DirectorException(jenv, $error); + } +%}In this case, the Node n is holding a reference to o - internally. However, SWIG has no way to know that this has occurred. - The Java proxy class still thinks that it has ownership of o. - As o has gone out of scope, it could be garbage collected in - which case the C++ destructor will be invoked and n will then - be holding a stale-pointer to o. If you're lucky, you will - only get a segmentation fault.
-To work around this, the ownership flag of o needs changing - to false. The ownership flag is a private member variable of - the proxy class so this is not possible without some customization of - the proxy class. This can be achieved by using a typemap to customise - the proxy class with pure Java code as detailed later in the section on - Java typemaps.
-Sometimes a function will create memory and return a pointer to a - newly allocated object. SWIG has no way of knowing this so by default - the proxy class does not manage the returned object. However, you can - tell the proxy class to manage the memory if you specify the -%newobject directive. Consider:
+The code generated using the
+director:except
feature + replaces the$directorthrowshandlers
special variable with + the code in the "directorthrows" typemaps, for each and every exception + defined for the method. The possible exceptions can be defined either + with a C++ exception specification or%catches
as + described for the "throws" typemap.Consider the following director method:
--class Obj {...}; -class Factory { -public: - static Obj *createObj() { return new Obj(); } -}; + ... + virtual void doSomething(int index) throw (std::out_of_range); + ...If we call the factory function, then we have to manually delete the - memory:
+When combined with the default
director:except
feature + and the "directorthrows" typemap above, the resulting code generated in + the director method after calling up to Java will be:--Obj obj = Factory.createObj(); // obj.swigCMemOwn = false -... -obj.delete(); +jthrowable swigerror = jenv->ExceptionOccurred(); +if (swigerror) { + jenv->ExceptionClear(); + if (Swig::ExceptionMatches(jenv, swigerror, "java/lang/IndexOutOfBoundsException")) { + throw std::out_of_range(Swig::JavaExceptionMessage(jenv, swigerror).message()); + } + + throw Swig::DirectorException(jenv, swigerror); +}Now add in the %newobject directive:
+Note: Beware of using exception specifications as the SWIG + director methods will be generated with the same exception + specifications and if the director method throws an exception that is + not specified it is likely to terminate your program. See the C++ + standard for more details. Using the %catches feature instead to define + the handled exceptions does not suffer this potential fate.
+Because the default code generation maps any unhandled Java + exceptions to
Swig::DirectorException
, any director + methods that have exception specifications may cause program + termination. To simply ignore unexpected exceptions, the default + handling can be changed with:--%newobject Factory::createObj(); - -class Obj {...}; -class Factory { -public: - static Obj *createObj() { return new Obj(); } -}; +%feature("director:except") %{ + jthrowable $error = jenv->ExceptionOccurred(); + if ($error) { + jenv->ExceptionClear(); + $directorthrowshandlers + return $null; // exception is ignored + } +%}A call to delete() is no longer necessary as the garbage - collector will make the C++ destructor call because swigCMemOwn - is now true.
+Alternatively an exception compatible with the existing director + method exception specifications can be thrown. Assuming that all + methods allow std::runtime_error to be thrown, the
return $null;
+ could be changed to:--Obj obj = Factory.createObj(); // obj.swigCMemOwn = true; -... + throw std::runtime_error(Swig::JavaExceptionMessage(jenv, $error).message());Some memory management issues are quite tricky to fix and may only - be noticeable after using for a long time. One such issue is premature - garbage collection of an object created from Java and resultant usage - from C++ code. The section on typemap examples cover two such - scenarios, Memory management - for objects passed to the C++ layer and -Memory management when returning references to member variables
-24.4.3.2 Inheritance
-Java proxy classes will mirror C++ inheritance chains. For example, - given the base class Base and its derived class Derived -:
+In more complex situations, a separate
+director:except
+ feature may need to be attached to specific methods.Below is a complete example demonstrating the use of the + "directorthrows" typemaps. In this example, a generic "directorthrows" + typemap is appropriate for all three exceptions - all take single + string constructors. If the exceptions had different constructors, it + would be necessary to have separate typemaps for each exception type. +
+-class Base { -public: - virtual double foo(); -}; +%module(directors="1") example -class Derived : public Base { -public: - virtual double foo(); -}; +%{ + #include <string> + #include <stdexcept> +%} + +// Define exceptions in header section using std::runtime_error +%define DEFINE_EXCEPTION(NAME) +%{ + namespace MyNS { + struct NAME : public std::runtime_error { NAME(const std::string &what) : runtime_error(what) {} }; + } +%} +%enddef + +// Expose C++ exceptions as Java Exceptions by changing the Java base class and providing a getMessage() +%define DECLARE_EXCEPTION(NAME) +%typemap(javabase) MyNS::NAME "java.lang.Exception"; +%rename(getMessage) MyNS::NAME::what; +namespace MyNS { + struct NAME { + NAME(const std::string& what); + const char * what(); + }; +} +%enddef + +DEFINE_EXCEPTION(ExceptionA) +DEFINE_EXCEPTION(ExceptionB) +DEFINE_EXCEPTION(Unexpected) + +// Mark three methods to map director thrown exceptions. +%feature("director:except") MyClass::meth1(int); +%feature("director:except") MyClass::meth2; +%feature("director:except") meth3; + +%typemap(directorthrows) MyNS::ExceptionA, MyNS::ExceptionB, MyNS::Unexpected %{ + if (Swig::ExceptionMatches(jenv, $error, "$packagepath/$javaclassname")) + throw $1_type(Swig::JavaExceptionMessage(jenv, $error).message()); +%} + +DECLARE_EXCEPTION(ExceptionA) +DECLARE_EXCEPTION(ExceptionB) +DECLARE_EXCEPTION(Unexpected) + +%catches(MyNS::ExceptionA, MyNS::ExceptionB, MyNS::Unexpected) MyClass::meth2(); + +%inline { + class MyClass { + public: + virtual void meth1(int x) throw(MyNS::ExceptionA, MyNS::ExceptionB) = 0; + virtual void meth2() = 0; /* throws MyNS::ExceptionA, MyNS::ExceptionB, MyNS::Unexpected */ + virtual void meth3(float x) throw(MyNS::Unexpected) = 0; + virtual ~MyClass() {} + }; +} ++In this case the three different "directorthrows" typemaps will be + used to generate the three different exception handlers for
+meth1
+,meth2
andmeth3
. The generated handlers will + have "if" blocks for each exception type specified, in the exception + specification or%catches
feature.Note that the "directorthrows" typemaps are important only if it is + important for the the exceptions passed through the C++ layer to be + mapped to distinct C++ exceptions. If director methods are being called + by C++ code that is itself wrapped in a SWIG generated Java wrapper and + access is always through this wrapper, the default
++Swig::DirectorException
class provides enough information to + reconstruct the original exception. In this case removing the+$directorthrowshandlers
special variable from the default+director:except
feature and simply always throwing a+Swig::DirectorException
will achieve the desired result. Along + with this a generic exception feature is added to convert any caught+Swig::DirectorException
s back into the underlying Java exceptions + via theSwig::DirectorException::raiseJavaException
+ method, as demonstrated with%javaexception
below:+++%javaexception("Exception") MyClass::myMethod %{ + try { + $action + } catch (Swig::DirectorException &e) { + // raise/throw the Java exception that originally caused the DirectorException + e.raiseJavaException(jenv); + return $null; + } +%} ++See the Exception handling with + %exception and %javaexception section for more on converting C++ + exceptions to Java exceptions.
+25.6 Accessing protected members
+When using directors, the protected virtual methods are also + wrapped. These methods are wrapped with a protected Java proxy method, + so the only way that Java code can access these is from within a Java + class derived from the director class.
+Members which are protected and non-virtual can also be accessed + when using the 'allprotected' mode. The allprotected mode requires + directors and is turned on by setting the allprotected option + in addition to the directors option in the %module directive, + like this:
++-+%module(directors="1", allprotected="1") modulenameThe base class is generated much like any other proxy class seen so - far:
+Protected member variables and methods (both static and non-static) + will then be wrapped with protected access in the Java proxy class.
+Note: Neither the directors option nor the allprotected mode + support types defined with protected scope. This includes any enums or + typedefs declared in the protected section of the C++ class.
+The following simple example is a class with numerous protected + members, including the constructor and destructor:
--public class Base { - private long swigCPtr; - protected boolean swigCMemOwn; +%module(directors="1", allprotected="1") example - protected Base(long cPtr, boolean cMemoryOwn) { - swigCMemOwn = cMemoryOwn; - swigCPtr = cPtr; - } +%feature("director") ProtectedBase; - protected static long getCPtr(Base obj) { - return (obj == null) ? 0 : obj.swigCPtr; - } +// Ignore use of unsupported types (those defined in the protected section) +%ignore ProtectedBase::typedefs; - protected void finalize() { - delete(); - } +%inline %{ - public synchronized void delete() { - if(swigCPtr != 0 && swigCMemOwn) { - swigCMemOwn = false; - exampleJNI.delete_Base(swigCPtr); - } - swigCPtr = 0; - } +class ProtectedBase { +protected: + ProtectedBase() {} + virtual ~ProtectedBase() {} + virtual void virtualMethod() const {} + void nonStaticMethod(double d) const {} + static void staticMethod(int i) {} + int instanceMemberVariable; + static int staticMemberVariable; - public double foo() { - return exampleJNI.Base_foo(swigCPtr, this); - } + // unsupported: types defined with protected access and the methods/variables which use them + typedef int IntegerType; + IntegerType typedefs(IntegerType it) { return it; } +}; +int ProtectedBase::staticMemberVariable = 10; - public Base() { - this(exampleJNI.new_Base(), true); - } +%} -}The Derived class extends Base mirroring the C++ - class inheritance hierarchy.
+Note that the IntegerType has protected scope and the + members which use this type must be ignored as they cannot be wrapped.
+The proxy methods are protected, so the only way the protected + members can be accessed is within a class that derives from the + director class, such as the following:
--public class Derived extends Base { - private long swigCPtr; - - protected Derived(long cPtr, boolean cMemoryOwn) { - super(exampleJNI.SWIGDerivedUpcast(cPtr), cMemoryOwn); - swigCPtr = cPtr; - } - - protected static long getCPtr(Derived obj) { - return (obj == null) ? 0 : obj.swigCPtr; - } - - protected void finalize() { - delete(); +class MyProtectedBase extends ProtectedBase +{ + public MyProtectedBase() { } - public synchronized void delete() { - if(swigCPtr != 0 && swigCMemOwn) { - swigCMemOwn = false; - exampleJNI.delete_Derived(swigCPtr); - } - swigCPtr = 0; - super.delete(); - } + public void accessProtected() { + virtualMethod(); + nonStaticMethod(1.2); + staticMethod(99); - public double foo() { - return exampleJNI.Derived_foo(swigCPtr, this); - } + setInstanceMemberVariable(5); + int i = getInstanceMemberVariable(); - public Derived() { - this(exampleJNI.new_Derived(), true); + setStaticMemberVariable(10); + i = getStaticMemberVariable(); } - }Note the memory ownership is controlled by the base class. However - each class in the inheritance hierarchy has its own pointer value which - is obtained during construction. The SWIGDerivedUpcast() call - converts the pointer from a Derived * to a Base *. - This is a necessity as C++ compilers are free to implement pointers in - the inheritance hierarchy with different values.
-It is of course possible to extend Base using your own Java - classes. If Derived is provided by the C++ code, you could for - example add in a pure Java class Extended derived from -Base. There is a caveat and that is any C++ code will not know - about your pure Java class Extended so this type of derivation - is restricted. However, true cross language polymorphism can be - achieved using the directors feature.
-24.4.3.3 Proxy classes and - garbage collection
-By default each proxy class has a delete() and a -finalize() method. The finalize() method calls -delete() which frees any malloc'd memory for wrapped C structs or - calls the C++ class destructors. The idea is for delete() to - be called when you have finished with the C/C++ object. Ideally you - need not call delete(), but rather leave it to the garbage - collector to call it from the finalizer. When a program exits, the - garbage collector does not guarantee to call all finalizers. An insight - into the reasoning behind this can be obtained from -Hans Boehm's Destructors, Finalizers, and Synchronization paper. - Depending on what the finalizers do and which operating system you use, - this may or may not be a problem.
-If the delete() call into JNI code is just for memory - handling, there is not a problem when run on most operating systems, - for example Windows and Unix. Say your JNI code creates memory on the - heap which your finalizers should clean up, the finalizers may or may - not be called before the program exits. In Windows and Unix all memory - that a process uses is returned to the system on exit, so this isn't a - problem. This is not the case in some operating systems like vxWorks. - If however, your finalizer calls into JNI code invoking the C++ - destructor which in turn releases a TCP/IP socket for example, there is - no guarantee that it will be released. Note that with long running - programs the garbage collector will eventually run, thereby calling any - unreferenced object's finalizers.
-Some not so ideal solutions are:
--
-- -
-Call the System.runFinalizersOnExit(true) or -Runtime.getRuntime().runFinalizersOnExit(true) to ensure the - finalizers are called before the program exits. The catch is that this - is a deprecated function call as the documentation says:
-This method is inherently unsafe. It may result in - finalizers being called on live objects while other threads are - concurrently manipulating those objects, resulting in erratic behavior - or deadlock.-In many cases you will be lucky and find that it works, but it is not - to be advocated. Have a look at -Java web site and search for runFinalizersOnExit.
-- -
-From jdk1.3 onwards a new function, addShutdownHook(), was - introduced which is guaranteed to be called when your program exits. - You can encourage the garbage collector to call the finalizers, for - example, add this static block to the class that has the main() - function:
+25.7 Common customization + features
+An earlier section presented the absolute basics of C/C++ wrapping. + If you do nothing but feed SWIG a header file, you will get an + interface that mimics the behavior described. However, sometimes this + isn't enough to produce a nice module. Certain types of functionality + might be missing or the interface to certain functions might be + awkward. This section describes some common SWIG features that are used + to improve the interface to existing C/C++ code.
+25.7.1 C/C++ helper functions
+Sometimes when you create a module, it is missing certain bits of + functionality. For example, if you had a function like this
-- static { - Runtime.getRuntime().addShutdownHook( - new Thread() { - public void run() { System.gc(); System.runFinalization(); } - } - ); - } +typedef struct Image {...}; +void set_transform(Image *im, double m[4][4]);Although this usually works, the documentation doesn't guarantee that - runFinalization() will actually call the finalizers. As the - shutdown hook is guaranteed you could also make a JNI call to clean up - any resources that are being tracked by the C/C++ code.
-- -
-Call the delete() function manually which will immediately - invoke the C++ destructor. As a suggestion it may be a good idea to set - the object to null so that should the object be inadvertently used - again a Java null pointer exception is thrown, the alternative would - crash the JVM by using a null C pointer. For example given a SWIG - generated class A:
+it would be accessible from Java, but there may be no easy way to + call it. The problem here is that a type wrapper class is generated for + the two dimensional array parameter so there is no easy way to + construct and manipulate a suitable double [4][4] value. To + fix this, you can write some extra C helper functions. Just use the +%inline directive. For example:
--A myA = new A(); -// use myA ... -myA.delete(); -// any use of myA here would crash the JVM -myA=null; -// any use of myA here would cause a Java null pointer exception to be thrown +%inline %{ +/* Note: double[4][4] is equivalent to a pointer to an array double (*)[4] */ +double (*new_mat44())[4] { + return (double (*)[4]) malloc(16*sizeof(double)); +} +void free_mat44(double (*x)[4]) { + free(x); +} +void mat44_set(double x[4][4], int i, int j, double v) { + x[i][j] = v; +} +double mat44_get(double x[4][4], int i, int j) { + return x[i][j]; +} +%}The SWIG generated code ensures that the memory is not deleted - twice, in the event the finalizers get called in addition to the manual - delete() call.
-- -
-Write your own object manager in Java. You could derive all SWIG - classes from a single base class which could track which objects have - had their finalizers run, then call the rest of them on program - termination. The section on Java typemaps - details how to specify a pure Java base class.
-See the How to - Handle Java Finalization's Memory-Retention Issues article for - alternative approaches to managing memory by avoiding finalizers - altogether.
-24.4.3.4 The premature garbage collection - prevention parameter for proxy class marshalling
-As covered earlier, the C/C++ struct/class pointer is stored in the - proxy class as a Java long and when needed is passed into the native - method where it is cast into the appropriate type. This approach - provides very fast marshalling but could be susceptible to premature - garbage collection. Consider the following C++ code:
+From Java, you could then write code like this:
--class Wibble { -}; -void wobble(Wibble &w); +Image im = new Image(); +SWIGTYPE_p_a_4__double a = example.new_mat44(); +example.mat44_set(a,0,0,1.0); +example.mat44_set(a,1,1,1.0); +example.mat44_set(a,2,2,1.0); +... +example.set_transform(im,a); +example.free_mat44(a);The module class contains the Java wrapper for the global wobble - method:
+Admittedly, this is not the most elegant looking approach. However, + it works and it wasn't too hard to implement. It is possible to improve + on this using Java code, typemaps, and other customization features as + covered in later sections, but sometimes helper functions are a quick + and easy solution to difficult cases.
+25.7.2 Class extension with %extend +
+One of the more interesting features of SWIG is that it can extend + structures and classes with new methods or constructors. Here is a + simple example:
--public class example { - ... - public static void wobble(Wibble w) { - exampleJNI.wobble(Wibble.getCPtr(w), w); - } -} +%module example +%{ +#include "someheader.h" +%} + +struct Vector { + double x,y,z; +}; + +%extend Vector { + char *toString() { + static char tmp[1024]; + sprintf(tmp,"Vector(%g,%g,%g)", $self->x,$self->y,$self->z); + return tmp; + } + Vector(double x, double y, double z) { + Vector *v = (Vector *) malloc(sizeof(Vector)); + v->x = x; + v->y = y; + v->z = z; + return v; + } +};where example is the name of the module. All native methods - go through the intermediary class which has the native method declared - as such:
+Now, in Java
--public class exampleJNI { - ... - public final static native void wobble(long jarg1, Wibble jarg1_); -} +Vector v = new Vector(2,3,4); +System.out.println(v);The second parameter, jarg1_, is the premature garbage - collection prevention parameter and is added to the native method - parameter list whenever a C/C++ struct or class is marshalled as a Java - long. In order to understand why, consider the alternative where the - intermediary class method is declared without the additional parameter:
+will display
--public class exampleJNI { - ... - public final static native void wobble(long jarg1); -} +Vector(2,3,4)and the following simple call to wobble:
+%extend works with both C and C++ code. It does not modify + the underlying object in any way---the extensions only show up in the + Java interface.
+25.7.3 Exception handling with + %exception and %javaexception
+If a C or C++ function throws an error, you may want to convert that + error into a Java exception. To do this, you can use the %exception + directive. The %exception directive simply lets you rewrite + part of the generated wrapper code to include an error check. It is + detailed in full in the Exception + handling with %exception section.
+In C, a function often indicates an error by returning a status code + (a negative number or a NULL pointer perhaps). Here is a simple example + of how you might handle that:
--{ - Wibble w = new Wibble(); - example.wobble(w); +%exception malloc { + $action + if (!result) { + jclass clazz = (*jenv)->FindClass(jenv, "java/lang/OutOfMemoryError"); + (*jenv)->ThrowNew(jenv, clazz, "Not enough memory"); + return $null; + } } +void *malloc(size_t nbytes);The hotspot compiler effectively sees something like:
+In Java,
--{ - Wibble w = new Wibble(); - long w_ptr = Wibble.getCPtr(w); - // w is no longer reachable - exampleJNI.wobble(w_ptr); -} +SWIGTYPE_p_void a = example.malloc(2000000000);The Wibble object is no longer reachable after the point - shown as in this bit of code, the Wibble object is not - referenced again after this point. This means that it is a candidate - for garbage collection. Should wobble be a long running - method, it is quite likely that the finalizer for the Wibble - instance will be called. This in turn will call its underlying C++ - destructor which is obviously disastrous while the method wobble - is running using this object. Even if wobble is not a long - running method, it is possible for the Wibble instance to be - finalized. By passing the Wibble instance into the native - method, it will not be finalized as the JVM guarantees not to finalize - any objects until the native method returns. Effectively, the code then - becomes
+will produce a familiar looking Java exception:
--{ - Wibble w = new Wibble(); - long w_ptr = Wibble.getCPtr(w); - exampleJNI.wobble(w_ptr, w); - // w is no longer reachable -} +Exception in thread "main" java.lang.OutOfMemoryError: Not enough memory + at exampleJNI.malloc(Native Method) + at example.malloc(example.java:16) + at runme.main(runme.java:112)and therefore there is no possibility of premature garbage - collection. In practice, this premature garbage collection was only - ever observed in Sun's server JVM from jdk-1.3 onwards and in Sun's - client JVM from jdk-1.6 onwards.
-The premature garbage collection prevention parameter for proxy - classes is generated by default whenever proxy classes are passed by - value, reference or with a pointer. The implementation for this extra - parameter generation requires the "jtype" typemap to contain long - and the "jstype" typemap to contain the name of a proxy class.
-The additional parameter does impose a slight performance overhead - and the parameter generation can be suppressed globally with the --nopgcpp commandline option. More selective suppression is possible - with the 'nopgcpp' attribute in the "jtype" -Java typemap. The attribute is a flag and so should be set to "1" to - enable the suppression, or it can be omitted or set to "0" to disable. - For example:
+If a library provides some kind of general error handling framework, + you can also use that. For example:
--%typemap(jtype, nopgcpp="1") Wibble & "long" +%exception malloc { + $action + if (err_occurred()) { + jclass clazz = (*jenv)->FindClass(jenv, "java/lang/OutOfMemoryError"); + (*jenv)->ThrowNew(jenv, clazz, "Not enough memory"); + return $null; + } +} +void *malloc(size_t nbytes);Compatibility note: The generation of this additional - parameter did not occur in versions prior to SWIG-1.3.30.
-24.4.3.5 Single threaded - applications and thread safety
-Single threaded Java applications using JNI need to consider thread - safety. The same applies for the C# module where the .NET wrappers use - PInvoke. Consider the C++ class:
+If no declaration name is given to %exception, it is + applied to all wrapper functions. The $action is a SWIG + special variable and is replaced by the C/C++ function call being + wrapped. The return $null; handles all native method return + types, namely those that have a void return and those that do not. This + is useful for typemaps that will be used in native method returning all + return types. See the section on Java + special variables for further explanation.
+C++ exceptions are also easy to handle. We can catch the C++ + exception and rethrow it as a Java exception like this:
--class Test { - string str; +%exception getitem { + try { + $action + } catch (std::out_of_range &e) { + jclass clazz = jenv->FindClass("java/lang/Exception"); + jenv->ThrowNew(clazz, "Range error"); + return $null; + } +} + +class FooClass { public: - Test() : str("initial") {} + FooClass *getitem(int index); // Might throw std::out_of_range exception + ... };and the Java proxy class generated by SWIG:
----public class Test { - private long swigCPtr; - protected boolean swigCMemOwn; - - protected Test(long cPtr, boolean cMemoryOwn) { - swigCMemOwn = cMemoryOwn; - swigCPtr = cPtr; - } - - protected static long getCPtr(Test obj) { - return (obj == null) ? 0 : obj.swigCPtr; - } - - protected void finalize() { - delete(); - } - - // Call C++ destructor - public synchronized void delete() { - if(swigCPtr != 0 && swigCMemOwn) { - swigCMemOwn = false; - exampleJNI.delete_Test(swigCPtr); - } - swigCPtr = 0; - } - - // Call C++ constructor - public Test() { - this(exampleJNI.new_Test(), true); - } - -} --It has two methods that call JNI methods, namely, -exampleJNI.new_Test() for the C++ constructor and -exampleJNI.delete_Test() for the C++ destructor. If the garbage - collector collects an instance of this class, ie delete() is - not explicitly called, then the C++ destructor will be run in a - different thread to the main thread. This is because when an object is - marked for garbage collection, any objects with finalizers are added to - a finalization queue and the objects in the finalization queue have - their finalize() methods run in a separate finalization - thread. Therefore, if the C memory allocator is not thread safe, then - the heap will get corrupted sooner or later, when a concurrent C++ - delete and new are executed. It is thus essential, even in single - threaded usage, to link to the C multi-thread runtime libraries, for - example, use the /MD option for Visual C++ on Windows. Alternatively, - lock all access to C++ functions that have heap - allocation/deallocation.
-Note that some of the STL in Visual C++ 6 is not thread safe, so - although code might be linked to the multithread runtime libraries, - undefined behaviour might still occur in a single threaded Java - program. Similarly some older versions of Sun Studio have bugs in the - multi-threaded implementation of the std::string class and so will lead - to undefined behaviour in these supposedly single threaded Java - applications.
-The following innocuous Java usage of Test is an example that will - crash very quickly on a multiprocessor machine if the JNI compiled code - is linked against the single thread C runtime libraries.
+In the example above, java.lang.Exception is a checked + exception class and so ought to be declared in the throws clause of +getitem. Classes can be specified for adding to the throws clause + using %javaexception(classes) instead of %exception, + where classes is a string containing one or more comma + separated Java classes. The %clearjavaexception feature is the + equivalent to %clearexception and clears previously declared + exception handlers. The %nojavaexception feature is the + equivalent to %noexception and disables the exception handler. + See Clearing features + for the difference on disabling and clearing features.
--for (int i=0; i<100000; i++) { - System.out.println("Iteration " + i); - for (int k=0; k<10; k++) { - Test test = new Test(); - } - System.gc(); +%javaexception("java.lang.Exception") getitem { + try { + $action + } catch (std::out_of_range &e) { + jclass clazz = jenv->FindClass("java/lang/Exception"); + jenv->ThrowNew(clazz, "Range error"); + return $null; + } } + +class FooClass { +public: + FooClass *getitem(int index); // Might throw std::out_of_range exception + ... +};24.4.4 Type wrapper classes
-The generated type wrapper class, for say an int *, looks - like this:
+The generated proxy method now generates a throws clause containing +java.lang.Exception:
--public class SWIGTYPE_p_int { - private long swigCPtr; - - protected SWIGTYPE_p_int(long cPtr, boolean bFutureUse) { - swigCPtr = cPtr; - } - - protected SWIGTYPE_p_int() { - swigCPtr = 0; - } - - protected static long getCPtr(SWIGTYPE_p_int obj) { - return obj.swigCPtr; - } +public class FooClass { + ... + public FooClass getitem(int index) throws java.lang.Exception { ... } + ... }The methods do not have public access, so by default it is - impossible to do anything with objects of this class other than pass - them around. The methods in the class are part of the inner workings of - SWIG. If you need to mess around with pointers you will have to use - some typemaps specific to the Java module to achieve this. The section - on Java typemaps details how to modify the - generated code.
-Note that if you use a pointer or reference to a proxy class in a - function then no type wrapper class is generated because the proxy - class can be used as the function parameter. If however, you need - anything more complicated like a pointer to a pointer to a proxy class - then a typewrapper class is generated for your use.
-Note that SWIG generates a type wrapper class and not a proxy class - when it has not parsed the definition of a type that gets used. For - example, say SWIG has not parsed the definition of class Snazzy - because it is in a header file that you may have forgotten to use the -%include directive on. Should SWIG parse Snazzy * being - used in a function parameter, it will then generates a type wrapper - class around a Snazzy pointer. Also recall from earlier that - SWIG will use a pointer when a class is passed by value or by - reference:
+The examples above first use the C JNI calling syntax then the C++ + JNI calling syntax. The C++ calling syntax will not compile as C and + also vice versa. It is however possible to write JNI calls which will + compile under both C and C++ and is covered in the +Typemaps for both C and C++ compilation section.
+The language-independent exception.i library file can also + be used to raise exceptions. See the SWIG Library + chapter. The typemap example Handling + C++ exception specifications as Java exceptions provides further + exception handling capabilities.
+25.7.4 Method access with + %javamethodmodifiers
+A Java feature called %javamethodmodifiers can be used to + change the method modifiers from the default public. It + applies to both module class methods and proxy class methods. For + example:
--void spam(Snazzy *x, Snazzy &y, Snazzy z); +%javamethodmodifiers protect_me() "protected"; +void protect_me();Should SWIG not know anything about Snazzy then a -SWIGTYPE_p_Snazzy must be used for all 3 parameters in the spam - function. The Java function generated is:
+Will produce the method in the module class with protected access.
--public static void spam(SWIGTYPE_p_Snazzy x, SWIGTYPE_p_Snazzy y, SWIGTYPE_p_Snazzy z) { - ... +protected static void protect_me() { + exampleJNI.protect_me(); }Note that typedefs are tracked by SWIG and the typedef name is used - to construct the type wrapper class name. For example, consider the - case where Snazzy is a typedef to an int which SWIG - does parse:
+25.8 Tips and techniques
+Although SWIG is largely automatic, there are certain types of + wrapping problems that require additional user input. Examples include + dealing with output parameters, strings and arrays. This chapter + discusses the common techniques for solving these problems.
+25.8.1 Input and output + parameters using primitive pointers and references
+A common problem in some C programs is handling parameters passed as + simple pointers or references. For example:
--typedef int Snazzy; -void spam(Snazzy *x, Snazzy &y, Snazzy z); +void add(int x, int y, int *result) { + *result = x + y; +}Because the typedefs have been tracked the Java function generated - is:
+or perhaps
--public static void spam(SWIGTYPE_p_int x, SWIGTYPE_p_int y, int z) { ... } +int sub(int *x, int *y) { + return *x-*y; +}24.4.5 Enum classes
-SWIG can generate three types of enum classes. The -Enumerations section discussed these but omitted all the details. - The following sub-sections detail the various types of enum classes - that can be generated.
-24.4.5.1 Typesafe enum - classes
-The following example demonstrates the typesafe enum classes which - SWIG generates:
+The typemaps.i library file will help in these situations. + For example:
--%include "enumtypesafe.swg" -%javaconst(1); -enum Beverage { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER }; +%module example +%include "typemaps.i" + +void add(int, int, int *OUTPUT); +int sub(int *INPUT, int *INPUT);The following is the code that SWIG generates:
+In Java, this allows you to pass simple values. For example:
--public final class Beverage { - public final static Beverage ALE = new Beverage("ALE"); - public final static Beverage LAGER = new Beverage("LAGER", 10); - public final static Beverage STOUT = new Beverage("STOUT"); - public final static Beverage PILSNER = new Beverage("PILSNER"); - public final static Beverage PILZ = new Beverage("PILZ", PILSNER); - - public final int swigValue() { - return swigValue; - } - - public String toString() { - return swigName; - } - - public static Beverage swigToEnum(int swigValue) { - if (swigValue < swigValues.length && swigValue >= 0 && - swigValues[swigValue].swigValue == swigValue) - return swigValues[swigValue]; - for (int i = 0; i < swigValues.length; i++) - if (swigValues[i].swigValue == swigValue) - return swigValues[i]; - throw new IllegalArgumentException("No enum " + Beverage.class + " with value " + - swigValue); - } - - private Beverage(String swigName) { - this.swigName = swigName; - this.swigValue = swigNext++; - } - - private Beverage(String swigName, int swigValue) { - this.swigName = swigName; - this.swigValue = swigValue; - swigNext = swigValue+1; - } - - private Beverage(String swigName, Beverage swigEnum) { - this.swigName = swigName; - this.swigValue = swigEnum.swigValue; - swigNext = this.swigValue+1; - } - - private static Beverage[] swigValues = { ALE, LAGER, STOUT, PILSNER, PILZ }; - private static int swigNext = 0; - private final int swigValue; - private final String swigName; -} +int result = example.sub(7,4); +System.out.println("7 - 4 = " + result); +int[] sum = {0}; +example.add(3,4,sum); +System.out.println("3 + 4 = " + sum[0]);As can be seen, there are a fair number of support methods for the - typesafe enum pattern. The typesafe enum pattern involves creating a - fixed number of static instances of the enum class. The constructors - are private to enforce this. Three constructors are available - two for - C/C++ enums with an initializer and one for those without an - initializer. Note that the two enums with initializers, LAGER - and PILZ, each call one the two different initializer - constructors. In order to use one of these typesafe enums, the -swigToEnum static method must be called to return a reference to - one of the static instances. The JNI layer returns the enum value from - the C/C++ world as an integer and this method is used to find the - appropriate Java enum static instance. The swigValue method is - used for marshalling in the other direction. The toString - method is overridden so that the enum name is available.
-24.4.5.2 Proper Java enum - classes
-The following example demonstrates the Java enums approach:
+Which will display:
--%include "enums.swg" -%javaconst(1); -enum Beverage { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER }; +7 - 4 = 3 +3 + 4 = 7SWIG will generate the following Java enum:
+Notice how the INPUT parameters allow integer values to be + passed instead of pointers and how the OUTPUT parameter will + return the result in the first element of the integer array.
+If you don't want to use the names INPUT or OUTPUT +, use the %apply directive. For example:
--public enum Beverage { - ALE, - LAGER(10), - STOUT, - PILSNER, - PILZ(PILSNER); - - public final int swigValue() { - return swigValue; - } - - public static Beverage swigToEnum(int swigValue) { - Beverage[] swigValues = Beverage.class.getEnumConstants(); - if (swigValue < swigValues.length && swigValue >= 0 && - swigValues[swigValue].swigValue == swigValue) - return swigValues[swigValue]; - for (Beverage swigEnum : swigValues) - if (swigEnum.swigValue == swigValue) - return swigEnum; - throw new IllegalArgumentException("No enum " + Beverage.class + - " with value " + swigValue); - } - - private Beverage() { - this.swigValue = SwigNext.next++; - } - - private Beverage(int swigValue) { - this.swigValue = swigValue; - SwigNext.next = swigValue+1; - } - - private Beverage(Beverage swigEnum) { - this.swigValue = swigEnum.swigValue; - SwigNext.next = this.swigValue+1; - } +%module example +%include "typemaps.i" - private final int swigValue; +%apply int *OUTPUT { int *result }; +%apply int *INPUT { int *x, int *y}; - private static class SwigNext { - private static int next = 0; - } -} +void add(int x, int y, int *result); +int sub(int *x, int *y);The enum items appear first. Like the typesafe enum pattern, the - constructors are private. The constructors are required to handle C/C++ - enums with initializers. The next variable is in the -SwigNext inner class rather than in the enum class as static - primitive variables cannot be modified from within enum constructors. - Marshalling between Java enums and the C/C++ enum integer value is - handled via the swigToEnum and swigValue methods. All - the constructors and methods in the Java enum are required just to - handle C/C++ enums with initializers. These needn't be generated if the - enum being wrapped does not have any initializers and the -Simpler Java enums for enums without initializers section describes - how typemaps can be used to achieve this.
-24.4.5.3 Type unsafe - enum classes
-The following example demonstrates type unsafe enums:
+If a function mutates one of its parameters like this,
--%include "enumtypeunsafe.swg" -%javaconst(1); -enum Beverage { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER }; +void negate(int *x) { + *x = -(*x); +}SWIG will generate the following simple class:
+you can use INOUT like this:
--public final class Beverage { - public final static int ALE = 0; - public final static int LAGER = 10; - public final static int STOUT = LAGER + 1; - public final static int PILSNER = STOUT + 1; - public final static int PILZ = PILSNER; -} +%include "typemaps.i" +... +void negate(int *INOUT);24.5 Cross language polymorphism using - directors
-Proxy classes provide a natural, object-oriented way to wrap C++ - classes. as described earlier, each proxy instance has an associated - C++ instance, and method calls from Java to the proxy are passed to the - C++ instance transparently via C wrapper functions.
-This arrangement is asymmetric in the sense that no corresponding - mechanism exists to pass method calls down the inheritance chain from - C++ to Java. In particular, if a C++ class has been extended in Java - (by deriving from the proxy class), these classes will not be visible - from C++ code. Virtual method calls from C++ are thus not able to - access the lowest implementation in the inheritance chain.
-SWIG can address this problem and make the relationship between C++ - classes and proxy classes more symmetric. To achieve this goal, new - classes called directors are introduced at the bottom of the C++ - inheritance chain. The job of the directors is to route method calls - correctly, either to C++ implementations higher in the inheritance - chain or to Java implementations lower in the inheritance chain. The - upshot is that C++ classes can be extended in Java and from C++ these - extensions look exactly like native C++ classes. Neither C++ code nor - Java code needs to know where a particular method is implemented: the - combination of proxy classes, director classes, and C wrapper functions - transparently takes care of all the cross-language method routing.
-24.5.1 Enabling directors
-The director feature is disabled by default. To use directors you - must make two changes to the interface file. First, add the "directors" - option to the %module directive, like this:
+In Java, the input parameter is the first element in a 1 element + array and is replaced by the output of the function. For example:
--%module(directors="1") modulename +int[] neg = {3}; +example.negate(neg); +System.out.println("Negative of 3 = " + neg[0]);Without this option no director code will be generated. Second, you - must use the %feature("director") directive to tell SWIG which classes - and methods should get directors. The %feature directive can be applied - globally, to specific classes, and to specific methods, like this:
+And no prizes for guessing the output:
--// generate directors for all classes that have virtual methods -%feature("director"); - -// generate directors for all virtual methods in class Foo -%feature("director") Foo; +Negative of 3 = -3You can use the %feature("nodirector") directive to turn off - directors for specific classes or methods. So for example,
+These typemaps can also be applied to C++ references. The above + examples would work the same if they had been defined using references + instead of pointers. For example, the Java code to use the negate + function would be the same if it were defined either as it is above:
--%feature("director") Foo; -%feature("nodirector") Foo::bar; +void negate(int *INOUT);will generate directors for all virtual methods of class Foo except - bar().
-Directors can also be generated implicitly through inheritance. In - the following, class Bar will get a director class that handles the - methods one() and two() (but not three()):
+or using a reference:
--%feature("director") Foo; -class Foo { -public: - virtual void one(); - virtual void two(); -}; - -class Bar: public Foo { -public: - virtual void three(); -}; +void negate(int &INOUT);24.5.2 Director classes
-For each class that has directors enabled, SWIG generates a new - class that derives from both the class in question and a special -Swig::Director class. These new classes, referred to as director - classes, can be loosely thought of as the C++ equivalent of the Java - proxy classes. The director classes store a pointer to their underlying - Java proxy classes.
-For simplicity let's ignore the Swig::Director class and - refer to the original C++ class as the director's base class. By - default, a director class extends all virtual methods in the - inheritance chain of its base class (see the preceding section for how - to modify this behavior). Thus all virtual method calls, whether they - originate in C++ or in Java via proxy classes, eventually end up in at - the implementation in the director class. The job of the director - methods is to route these method calls to the appropriate place in the - inheritance chain. By "appropriate place" we mean the method that would - have been called if the C++ base class and its Java derived classes - were seamlessly integrated. That seamless integration is exactly what - the director classes provide, transparently skipping over all the messy - JNI glue code that binds the two languages together.
-In reality, the "appropriate place" is one of only two - possibilities: C++ or Java. Once this decision is made, the rest is - fairly easy. If the correct implementation is in C++, then the lowest - implementation of the method in the C++ inheritance chain is called - explicitly. If the correct implementation is in Java, the Java API is - used to call the method of the underlying Java object (after which the - usual virtual method resolution in Java automatically finds the right - implementation).
-24.5.3 Overhead and code bloat
-Enabling directors for a class will generate a new director method - for every virtual method in the class' inheritance chain. This alone - can generate a lot of code bloat for large hierarchies. Method - arguments that require complex conversions to and from Java types can - result in large director methods. For this reason it is recommended - that directors are selectively enabled only for specific classes that - are likely to be extended in Java and used in C++.
-Although directors make it natural to mix native C++ objects with - Java objects (as director objects), one should be aware of the obvious - fact that method calls to Java objects from C++ will be much slower - than calls to C++ objects. Additionally, compared to classes that do - not use directors, the call routing in the director methods adds a - small overhead. This situation can be optimized by selectively enabling - director methods (using the %feature directive) for only those methods - that are likely to be extended in Java.
-24.5.4 Simple directors example
-Consider the following SWIG interface file:
+Note: Since most Java primitive types are immutable and are passed + by value, it is not possible to perform in-place modification of a type + passed as a parameter.
+Be aware that the primary purpose of the typemaps.i file is + to support primitive datatypes. Writing a function like this
--%module(directors="1") example; - -%feature("director") DirectorBase; - -class DirectorBase { -public: - virtual ~DirectorBase() {} - virtual void upcall_method() {} -}; - -void callup(DirectorBase *director) { - director->upcall_method(); -} +void foo(Bar *OUTPUT);The following
+DirectorDerived
Java class is derived - from the Java proxy classDirectorBase
and overrides-upcall_method()
. When C++ code invokesupcall_method()
-, the SWIG-generated C++ code redirects the call via JNI to the Java-DirectorDerived
subclass. Naturally, the SWIG generated C++ code - and the generated Java intermediary class marshal and convert arguments - between C++ and Java when needed.will not have the intended effect since typemaps.i does not + define an OUTPUT rule for Bar.
+25.8.2 Simple pointers
+If you must work with simple pointers such as int * or +double * another approach to using typemaps.i is to use + the cpointer.i pointer library file. For example:
--public class DirectorDerived extends DirectorBase { - public DirectorDerived() { - } +%module example +%include "cpointer.i" - public void upcall_method() { - System.out.println("DirectorDerived::upcall_method() invoked."); - } -} +%inline %{ +extern void add(int x, int y, int *result); +%} + +%pointer_functions(int, intp);Running the following Java code
+The %pointer_functions(type,name) macro generates five + helper functions that can be used to create, destroy, copy, assign, and + dereference a pointer. In this case, the functions are as follows:
--DirectorDerived director = new DirectorDerived(); -example.callup(director); +int *new_intp(); +int *copy_intp(int *x); +void delete_intp(int *x); +void intp_assign(int *x, int value); +int intp_value(int *x);will result in the following being output:
+In Java, you would use the functions like this:
--DirectorDerived::upcall_method() invoked. +SWIGTYPE_p_int intPtr = example.new_intp(); +example.add(3,4,intPtr); +int result = example.intp_value(intPtr); +System.out.println("3 + 4 = " + result);24.5.5 Director threading - issues
-Depending on your operating system and version of Java and how you - are using threads, you might find the JVM hangs on exit. There are a - couple of solutions to try out. The preferred solution requires jdk-1.4 - and later and uses AttachCurrentThreadAsDaemon instead of -AttachCurrentThread whenever a call into the JVM is required. This - can be enabled by defining the - SWIG_JAVA_ATTACH_CURRENT_THREAD_AS_DAEMON macro when compiling the C++ - wrapper code. For older JVMs define SWIG_JAVA_NO_DETACH_CURRENT_THREAD - instead, to avoid the DetachCurrentThread call but this will - result in a memory leak instead. For further details inspect the source - code in the java/director.swg library file.
-Macros can be defined on the commandline when compiling your C++ - code, or alternatively added to the C++ wrapper file as shown below:
+If you replace %pointer_functions(int,intp) by +%pointer_class(int,intp), the interface is more class-like.
--%insert("runtime") %{ -#define SWIG_JAVA_NO_DETACH_CURRENT_THREAD -%} +intp intPtr = new intp(); +example.add(3,4,intPtr.cast()); +int result = intPtr.value(); +System.out.println("3 + 4 = " + result);24.5.6 Director performance - tuning
-When a new instance of a director (or subclass) is created in Java, - the C++ side of the director performs a runtime check per director - method to determine if that particular method is overridden in Java or - if it should invoke the C++ base implementation directly. Although this - makes initialization slightly more expensive, it is generally a good - overall tradeoff.
-However, if all director methods are expected to usually be - overridden by Java subclasses, then initialization can be made faster - by avoiding these checks via the assumeoverride attribute. For +
See the SWIG Library chapter for further + details.
+25.8.3 Wrapping C arrays with Java arrays +
+SWIG can wrap arrays in a more natural Java manner than the default + by using the arrays_java.i library file. Let's consider an example:
--%feature("director", assumeoverride=1) Foo; --The disadvantage is that invocation of director methods from C++ - when Java doesn't actually override the method will require an - additional call up into Java and back to C++. As such, this option is - only useful when overrides are extremely common and instantiation is - frequent enough that its performance is critical.
-24.6 Accessing protected members
-When using directors, the protected virtual methods are also - wrapped. These methods are wrapped with a protected Java proxy method, - so the only way that Java code can access these is from within a Java - class derived from the director class.
-Members which are protected and non-virtual can also be accessed - when using the 'allprotected' mode. The allprotected mode requires - directors and is turned on by setting the allprotected option - in addition to the directors option in the %module directive, - like this:
----%module(directors="1", allprotected="1") modulename +%include "arrays_java.i"; +int array[4]; +void populate(int x[]) { + int i; + for (i=0; i<4; i++) + x[i] = 100 + i; +}Protected member variables and methods (both static and non-static) - will then be wrapped with protected access in the Java proxy class.
-Note: Neither the directors option nor the allprotected mode - support types defined with protected scope. This includes any enums or - typedefs declared in the protected section of the C++ class.
-The following simple example is a class with numerous protected - members, including the constructor and destructor:
+These one dimensional arrays can then be used as if they were Java + arrays:
--%module(directors="1", allprotected="1") example - -%feature("director") ProtectedBase; - -// Ignore use of unsupported types (those defined in the protected section) -%ignore ProtectedBase::typedefs; - -%inline %{ +int[] array = new int[4]; +example.populate(array); -class ProtectedBase { -protected: - ProtectedBase() {} - virtual ~ProtectedBase() {} - virtual void virtualMethod() const {} - void nonStaticMethod(double d) const {} - static void staticMethod(int i) {} - int instanceMemberVariable; - static int staticMemberVariable; +System.out.print("array: "); +for (int i=0; i<array.length; i++) + System.out.print(array[i] + " "); - // unsupported: types defined with protected access and the methods/variables which use them - typedef int IntegerType; - IntegerType typedefs(IntegerType it) { return it; } -}; -int ProtectedBase::staticMemberVariable = 10; +example.setArray(array); -%} +int[] global_array = example.getArray(); +System.out.print("\nglobal_array: "); +for (int i=0; i<array.length; i++) + System.out.print(global_array[i] + " ");Note that the IntegerType has protected scope and the - members which use this type must be ignored as they cannot be wrapped.
-The proxy methods are protected, so the only way the protected - members can be accessed is within a class that derives from the - director class, such as the following:
+Java arrays are always passed by reference, so any changes a + function makes to the array will be seen by the calling function. Here + is the output after running this code:
--class MyProtectedBase extends ProtectedBase -{ - public MyProtectedBase() { - } - - public void accessProtected() { - virtualMethod(); - nonStaticMethod(1.2); - staticMethod(99); - - setInstanceMemberVariable(5); - int i = getInstanceMemberVariable(); - - setStaticMemberVariable(10); - i = getStaticMemberVariable(); - } -} +array: 100 101 102 103 +global_array: 100 101 102 10324.7 Common customization - features
-An earlier section presented the absolute basics of C/C++ wrapping. - If you do nothing but feed SWIG a header file, you will get an - interface that mimics the behavior described. However, sometimes this - isn't enough to produce a nice module. Certain types of functionality - might be missing or the interface to certain functions might be - awkward. This section describes some common SWIG features that are used - to improve the interface to existing C/C++ code.
-24.7.1 C/C++ helper functions
-Sometimes when you create a module, it is missing certain bits of - functionality. For example, if you had a function like this
+Note that for assigning array variables the length of the C variable + is used, so it is possible to use a Java array that is bigger than the + C code will cope with. Only the number of elements in the C array will + be used. However, if the Java array is not large enough then you are + likely to get a segmentation fault or access violation, just like you + would in C. When arrays are used in functions like populate, + the size of the C array passed to the function is determined by the + size of the Java array.
+Please be aware that the typemaps in this library are not efficient + as all the elements are copied from the Java array to a C array + whenever the array is passed to and from JNI code. There is an + alternative approach using the SWIG array library and this is covered + in the next section.
+25.8.4 Unbounded C Arrays
+Sometimes a C function expects an array to be passed as a pointer. + For example,
--typedef struct Image {...}; -void set_transform(Image *im, double m[4][4]); +int sumitems(int *first, int nitems) { + int i, sum = 0; + for (i = 0; i < nitems; i++) { + sum += first[i]; + } + return sum; +}it would be accessible from Java, but there may be no easy way to - call it. The problem here is that a type wrapper class is generated for - the two dimensional array parameter so there is no easy way to - construct and manipulate a suitable double [4][4] value. To - fix this, you can write some extra C helper functions. Just use the -%inline directive. For example:
+One of the ways to wrap this is to apply the Java array typemaps + that come in the arrays_java.i library file:
--%inline %{ -/* Note: double[4][4] is equivalent to a pointer to an array double (*)[4] */ -double (*new_mat44())[4] { - return (double (*)[4]) malloc(16*sizeof(double)); -} -void free_mat44(double (*x)[4]) { - free(x); -} -void mat44_set(double x[4][4], int i, int j, double v) { - x[i][j] = v; -} -double mat44_get(double x[4][4], int i, int j) { - return x[i][j]; -} -%} +%include "arrays_java.i" +%apply int[] {int *};From Java, you could then write code like this:
+The ANY size will ensure the typemap is applied to arrays + of all sizes. You could narrow the typemap matching rules by specifying + a particular array size. Now you can use a pure Java array and pass it + to the C code:
--Image im = new Image(); -SWIGTYPE_p_a_4__double a = example.new_mat44(); -example.mat44_set(a,0,0,1.0); -example.mat44_set(a,1,1,1.0); -example.mat44_set(a,2,2,1.0); -... -example.set_transform(im,a); -example.free_mat44(a); +int[] array = new int[10000000]; // Array of 10-million integers +for (int i=0; i<array.length; i++) { // Set some values + array[i] = i; +} +int sum = example.sumitems(array,10000); +System.out.println("Sum = " + sum);Admittedly, this is not the most elegant looking approach. However, - it works and it wasn't too hard to implement. It is possible to improve - on this using Java code, typemaps, and other customization features as - covered in later sections, but sometimes helper functions are a quick - and easy solution to difficult cases.
-24.7.2 Class extension with - %extend
-One of the more interesting features of SWIG is that it can extend - structures and classes with new methods or constructors. Here is a - simple example:
+and the sum would be displayed:
--%module example -%{ -#include "someheader.h" -%} - -struct Vector { - double x,y,z; -}; - -%extend Vector { - char *toString() { - static char tmp[1024]; - sprintf(tmp,"Vector(%g,%g,%g)", $self->x,$self->y,$self->z); - return tmp; - } - Vector(double x, double y, double z) { - Vector *v = (Vector *) malloc(sizeof(Vector)); - v->x = x; - v->y = y; - v->z = z; - return v; - } -}; +Sum = 49995000Now, in Java
+This approach is probably the most natural way to use arrays. + However, it suffers from performance problems when using large arrays + as a lot of copying of the elements occurs in transferring the array + from the Java world to the C++ world. An alternative approach to using + Java arrays for C arrays is to use an alternative SWIG library file +carrays.i. This approach can be more efficient for large arrays as + the array is accessed one element at a time. For example:
--Vector v = new Vector(2,3,4); -System.out.println(v); +%include "carrays.i" +%array_functions(int, intArray);will display
+The %array_functions(type,name) macro generates four helper + functions that can be used to create and destroy arrays and operate on + elements. In this case, the functions are as follows:
--Vector(2,3,4) +int *new_intArray(int nelements); +void delete_intArray(int *x); +int intArray_getitem(int *x, int index); +void intArray_setitem(int *x, int index, int value);%extend works with both C and C++ code. It does not modify - the underlying object in any way---the extensions only show up in the - Java interface.
-24.7.3 Exception handling with - %exception and %javaexception
-If a C or C++ function throws an error, you may want to convert that - error into a Java exception. To do this, you can use the %exception - directive. The %exception directive simply lets you rewrite - part of the generated wrapper code to include an error check. It is - detailed in full in the Exception - handling with %exception section.
-In C, a function often indicates an error by returning a status code - (a negative number or a NULL pointer perhaps). Here is a simple example - of how you might handle that:
+In Java, you would use the functions like this:
--%exception malloc { - $action - if (!result) { - jclass clazz = (*jenv)->FindClass(jenv, "java/lang/OutOfMemoryError"); - (*jenv)->ThrowNew(jenv, clazz, "Not enough memory"); - return $null; - } +SWIGTYPE_p_int array = example.new_intArray(10000000); // Array of 10-million integers +for (int i=0; i<10000; i++) { // Set some values + example.intArray_setitem(array,i,i); } -void *malloc(size_t nbytes); +int sum = example.sumitems(array,10000); +System.out.println("Sum = " + sum);In Java,
+If you replace %array_functions(int,intp) by +%array_class(int,intp), the interface is more class-like and a + couple more helper functions are available for casting between the + array and the type wrapper class.
--SWIGTYPE_p_void a = example.malloc(2000000000); +%include "carrays.i" +%array_class(int, intArray);will produce a familiar looking Java exception:
+The %array_class(type, name) macro creates wrappers for an + unbounded array object that can be passed around as a simple pointer + like int * or double *. For instance, you will be + able to do this in Java:
--Exception in thread "main" java.lang.OutOfMemoryError: Not enough memory - at exampleJNI.malloc(Native Method) - at example.malloc(example.java:16) - at runme.main(runme.java:112) +intArray array = new intArray(10000000); // Array of 10-million integers +for (int i=0; i<10000; i++) { // Set some values + array.setitem(i,i); +} +int sum = example.sumitems(array.cast(),10000); +System.out.println("Sum = " + sum);If a library provides some kind of general error handling framework, - you can also use that. For example:
+The array "object" created by %array_class() does not + encapsulate pointers inside a special array object. In fact, there is + no bounds checking or safety of any kind (just like in C). Because of + this, the arrays created by this library are extremely low-level + indeed. You can't iterate over them nor can you even query their + length. In fact, any valid memory address can be accessed if you want + (negative indices, indices beyond the end of the array, etc.). Needless + to say, this approach is not going to suit all applications. On the + other hand, this low-level approach is extremely efficient and well + suited for applications in which you need to create buffers, package + binary data, etc.
+25.8.5 Binary data vs Strings
+By default SWIG handles char * as a string but there is a + handy multi-argument typemap available as mentioned in +Passing binary data. The following simple example demonstrates using + a byte array instead of passing the default string type and length to + the wrapped function.
--%exception malloc { - $action - if (err_occurred()) { - jclass clazz = (*jenv)->FindClass(jenv, "java/lang/OutOfMemoryError"); - (*jenv)->ThrowNew(jenv, clazz, "Not enough memory"); - return $null; - } +%apply (char *STRING, size_t LENGTH) { (const char data[], size_t len) } +%inline %{ +void binaryChar1(const char data[], size_t len) { + printf("len: %d data: ", len); + for (size_t i=0; i<len; ++i) + printf("%x ", data[i]); + printf("\n"); } -void *malloc(size_t nbytes); +%}If no declaration name is given to %exception, it is - applied to all wrapper functions. The $action is a SWIG - special variable and is replaced by the C/C++ function call being - wrapped. The return $null; handles all native method return - types, namely those that have a void return and those that do not. This - is useful for typemaps that will be used in native method returning all - return types. See the section on Java - special variables for further explanation.
-C++ exceptions are also easy to handle. We can catch the C++ - exception and rethrow it as a Java exception like this:
+Calling from Java requires just the byte array to be passed in as + the multi-argument typemap being applied reduces the number of + arguments in the target language to one, from the original two:
--%exception getitem { - try { - $action - } catch (std::out_of_range &e) { - jclass clazz = jenv->FindClass("java/lang/Exception"); - jenv->ThrowNew(clazz, "Range error"); - return $null; - } -} - -class FooClass { -public: - FooClass *getitem(int index); // Might throw std::out_of_range exception - ... -}; +byte[] data = "hi\0jk".getBytes(); +example.binaryChar1(data);In the example above, java.lang.Exception is a checked - exception class and so ought to be declared in the throws clause of -getitem. Classes can be specified for adding to the throws clause - using %javaexception(classes) instead of %exception, - where classes is a string containing one or more comma - separated Java classes. The %clearjavaexception feature is the - equivalent to %clearexception and clears previously declared - exception handlers. The %nojavaexception feature is the - equivalent to %noexception and disables the exception handler. - See Clearing features - for the difference on disabling and clearing features.
+resulting in the output
--%javaexception("java.lang.Exception") getitem { - try { - $action - } catch (std::out_of_range &e) { - jclass clazz = jenv->FindClass("java/lang/Exception"); - jenv->ThrowNew(clazz, "Range error"); - return $null; - } -} - -class FooClass { -public: - FooClass *getitem(int index); // Might throw std::out_of_range exception - ... -}; +$ java runme +len: 5 data: 68 69 0 6a 6bThe generated proxy method now generates a throws clause containing -java.lang.Exception:
+25.8.6 Overriding new and delete to + allocate from Java heap
+Unlike some languages supported by SWIG, Java has a true garbage + collection subsystem. Other languages will free SWIG wrapped objects + when their reference count reaches zero. Java only schedules these + objects for finalization, which may not occur for some time. Because + SWIG objects are allocated on the C heap, Java users may find the JVM + memory use quickly exceeds the assigned limits, as memory fills with + unfinalized proxy objects. Forcing garbage collection is clearly an + undesirable solution.
+An elegant fix for C++ users is to override new and delete using the + following code (here shown included in a SWIG interface file)
--public class FooClass { - ... - public FooClass getitem(int index) throws java.lang.Exception { ... } - ... +/* File: java_heap.i */ +%module test +%{ +#include <stdexcept> +#include "jni.h" + +/** + * A stash area embedded in each allocation to hold java handles + */ +struct Jalloc { + jbyteArray jba; + jobject ref; +}; + +static JavaVM *cached_jvm = 0; + +JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *jvm, void *reserved) { + cached_jvm = jvm; + return JNI_VERSION_1_2; +} + +static JNIEnv * JNU_GetEnv() { + JNIEnv *env; + jint rc = cached_jvm->GetEnv((void **)&env, JNI_VERSION_1_2); + if (rc == JNI_EDETACHED) + throw std::runtime_error("current thread not attached"); + if (rc == JNI_EVERSION) + throw std::runtime_error("jni version not supported"); + return env; +} + +void * operator new(size_t t) { + if (cached_jvm != 0) { + JNIEnv *env = JNU_GetEnv(); + jbyteArray jba = env->NewByteArray((int) t + sizeof(Jalloc)); + if (env->ExceptionOccurred()) + throw bad_alloc(); + void *jbuffer = static_cast<void *>(env->GetByteArrayElements(jba, 0)); + if (env->ExceptionOccurred()) + throw bad_alloc(); + Jalloc *pJalloc = static_cast<Jalloc *>(jbuffer); + pJalloc->jba = jba; + /* Assign a global reference so byte array will persist until delete'ed */ + pJalloc->ref = env->NewGlobalRef(jba); + if (env->ExceptionOccurred()) + throw bad_alloc(); + return static_cast<void *>(static_cast<char *>(jbuffer) + sizeof(Jalloc)); + } + else { /* JNI_OnLoad not called, use malloc and mark as special */ + Jalloc *pJalloc = static_cast<Jalloc *>(malloc((int) t + sizeof(Jalloc))); + if (!pJalloc) + throw bad_alloc(); + pJalloc->ref = 0; + return static_cast<void *>( + static_cast<char *>(static_cast<void *>(pJalloc)) + sizeof(Jalloc)); + } +} + +void operator delete(void *v) { + if (v != 0) { + void *buffer = static_cast<void *>( static_cast<char *>(v) - sizeof(Jalloc)); + Jalloc *pJalloc = static_cast<Jalloc *>(buffer); + if (pJalloc->ref) { + JNIEnv *env = JNU_GetEnv(); + env->DeleteGlobalRef(pJalloc->ref); + env->ReleaseByteArrayElements(pJalloc->jba, static_cast<jbyte *>(buffer), 0); + } + else { + free(buffer); + } + } } +%} +...The examples above first use the C JNI calling syntax then the C++ - JNI calling syntax. The C++ calling syntax will not compile as C and - also vice versa. It is however possible to write JNI calls which will - compile under both C and C++ and is covered in the -Typemaps for both C and C++ compilation section.
-The language-independent exception.i library file can also - be used to raise exceptions. See the SWIG Library - chapter. The typemap example Handling - C++ exception specifications as Java exceptions provides further - exception handling capabilities.
-24.7.4 Method access with - %javamethodmodifiers
-A Java feature called %javamethodmodifiers can be used to - change the method modifiers from the default public. It - applies to both module class methods and proxy class methods. For - example:
+This code caches the Java environment during initialization, and + when new is called, a Java ByteArray is allocated to provide the SWIG + objects with space in the Java heap. This has the combined effect of + re-asserting the Java virtual machine's limit on memory allocation, and + puts additional pressure on the garbage collection system to run more + frequently. This code is made slightly more complicated because + allowances must be made if new is called before the JNI_OnLoad is + executed. This can happen during static class initialization, for + example.
+Unfortunately, because most Java implementations call malloc and + free, this solution will not work for C wrapped structures. However, + you are free to make functions that allocate and free memory from the + Java heap using this model and use these functions in place of malloc + and free in your own code.
+25.9 Java typemaps
+This section describes how you can modify SWIG's default wrapping + behavior for various C/C++ datatypes using the %typemap + directive. You are advised to be familiar with the material in the " +Typemaps" chapter. While not absolutely essential knowledge, this + section assumes some familiarity with the Java Native Interface (JNI). + JNI documentation can be consulted either online at +Sun's Java web site or from a good JNI book. The following two books + are recommended:
++
+- Title: 'Essential JNI: Java Native Interface.' Author: Rob Gordon. + Publisher: Prentice Hall. ISBN: 0-13-679895-0.
+- Title: 'The Java Native Interface: Programmer's Guide and + Specification.' Author: Sheng Liang. Publisher: Addison-Wesley. ISBN: + 0-201-32577-2. Also available +online at the Sun Developer Network.
+Before proceeding, it should be stressed that typemaps are not a + required part of using SWIG---the default wrapping behavior is enough + in most cases. Typemaps are only used if you want to change some aspect + of the generated code.
+25.9.1 Default + primitive type mappings
+The following table lists the default type mapping from Java to + C/C++.
++
++ C/C++ type Java type JNI type + + bool +
const bool &boolean jboolean + char +
const char &char jchar + signed char +
const signed char &byte jbyte + unsigned char +
const unsigned char &short jshort + short +
const short &short jshort + unsigned short +
const unsigned short &int jint + int +
const int &int jint + unsigned int +
const unsigned int &long jlong + long +
const long &int jint + unsigned long +
const unsigned long &long jlong + long long +
const long long &long jlong + unsigned long long +
const unsigned long long &java.math.BigInteger +jobject + float +
const float &float jfloat + double +
const double &double jdouble + char * +
char []String jstring Note that SWIG wraps the C char type as a character. + Pointers and arrays of this type are wrapped as strings. The signed + char type can be used if you want to treat char as a + signed number rather than a character. Also note that all const + references to primitive types are treated as if they are passed by + value.
+Given the following C function:
--%javamethodmodifiers protect_me() "protected"; -void protect_me(); +void func(unsigned short a, char *b, const long &c, unsigned long long d);Will produce the method in the module class with protected access.
+The module class method would be:
--protected static void protect_me() { - exampleJNI.protect_me(); -} +public static void func(int a, String b, int c, java.math.BigInteger d) {...}24.8 Tips and techniques
-Although SWIG is largely automatic, there are certain types of - wrapping problems that require additional user input. Examples include - dealing with output parameters, strings and arrays. This chapter - discusses the common techniques for solving these problems.
-24.8.1 Input and output - parameters using primitive pointers and references
-A common problem in some C programs is handling parameters passed as - simple pointers or references. For example:
+The intermediary JNI class would use the same types:
--void add(int x, int y, int *result) { - *result = x + y; -} +public final static native void func(int jarg1, String jarg2, int jarg3, + java.math.BigInteger jarg4);or perhaps
+and the JNI function would look like this:
--int sub(int *x, int *y) { - return *x-*y; -} +SWIGEXPORT void JNICALL Java_exampleJNI_func(JNIEnv *jenv, jclass jcls, + jint jarg1, jstring jarg2, jint jarg3, jobject jarg4) {...}The typemaps.i library file will help in these situations. - For example:
+The mappings for C int and C long are appropriate + for 32 bit applications which are used in the 32 bit JVMs. There is no + perfect mapping between Java and C as Java doesn't support all the + unsigned C data types. However, the mappings allow the full range of + values for each C type from Java.
+25.9.2 Default + typemaps for non-primitive types
+The previous section covered the primitive type mappings. + Non-primitive types such as classes and structs are mapped using + pointers on the C/C++ side and storing the pointer into a Java long + variable which is held by the proxy class or type wrapper class. This + applies whether the type is marshalled as a pointer, by reference or by + value. It also applies for any unknown/incomplete types which use type + wrapper classes.
+So in summary, the C/C++ pointer to non-primitive types is cast into + the 64 bit Java long type and therefore the JNI type is a +jlong. The Java type is either the proxy class or type wrapper + class.
+25.9.3 Sixty four bit JVMs
+If you are using a 64 bit JVM you may have to override the C long, + but probably not C int default mappings. Mappings will be system + dependent, for example long will need remapping on Unix LP64 systems + (long, pointer 64 bits, int 32 bits), but not on Microsoft 64 bit + Windows which will be using a P64 IL32 (pointer 64 bits and int, long + 32 bits) model. This may be automated in a future version of SWIG. Note + that the Java write once run anywhere philosophy holds true for all + pure Java code when moving to a 64 bit JVM. Unfortunately it won't of + course hold true for JNI code.
+25.9.4 What is a typemap?
+A typemap is nothing more than a code generation rule that is + attached to a specific C datatype. For example, to convert integers + from Java to C, you might define a typemap like this:
-%module example -%include "typemaps.i" -void add(int, int, int *OUTPUT); -int sub(int *INPUT, int *INPUT); +%typemap(in) int { + $1 = $input; + printf("Received an integer : %d\n", $1); +} +%inline %{ +extern int fact(int nonnegative); +%}In Java, this allows you to pass simple values. For example:
+Typemaps are always associated with some specific aspect of code + generation. In this case, the "in" method refers to the conversion of + input arguments to C/C++. The datatype int is the datatype to + which the typemap will be applied. The supplied C code is used to + convert values. In this code a number of special variables prefaced by + a $ are used. The $1 variable is a placeholder for a + local variable of type int. The $input variable + contains the Java data, the JNI jint in this case.
+When this example is compiled into a Java module, it can be used as + follows:
--int result = example.sub(7,4); -System.out.println("7 - 4 = " + result); -int[] sum = {0}; -example.add(3,4,sum); -System.out.println("3 + 4 = " + sum[0]); +System.out.println(example.fact(6));Which will display:
+and the output will be:
--7 - 4 = 3 -3 + 4 = 7 +Received an integer : 6 +720Notice how the INPUT parameters allow integer values to be - passed instead of pointers and how the OUTPUT parameter will - return the result in the first element of the integer array.
-If you don't want to use the names INPUT or OUTPUT -, use the %apply directive. For example:
+In this example, the typemap is applied to all occurrences of the +int datatype. You can refine this by supplying an optional + parameter name. For example:
-%module example -%include "typemaps.i" -%apply int *OUTPUT { int *result }; -%apply int *INPUT { int *x, int *y}; +%typemap(in) int nonnegative { + $1 = $input; + printf("Received an integer : %d\n", $1); +} -void add(int x, int y, int *result); -int sub(int *x, int *y); +%inline %{ +extern int fact(int nonnegative); +%}If a function mutates one of its parameters like this,
+In this case, the typemap code is only attached to arguments that + exactly match int nonnegative.
+The application of a typemap to specific datatypes and argument + names involves more than simple text-matching--typemaps are fully + integrated into the SWIG C++ type-system. When you define a typemap for + int, that typemap applies to int and qualified + variations such as const int. In addition, the typemap system + follows typedef declarations. For example:
--void negate(int *x) { - *x = -(*x); +%typemap(in) int nonnegative { + $1 = $input; + printf("Received an integer : %d\n", $1); } +%inline %{ +typedef int Integer; +extern int fact(Integer nonnegative); // Above typemap is applied +%}you can use INOUT like this:
+However, the matching of typedef only occurs in one + direction. If you defined a typemap for Integer, it is not + applied to arguments of type int.
+Typemaps can also be defined for groups of consecutive arguments. + For example:
--%include "typemaps.i" +%typemap(in) (char *str, int len) { ... -void negate(int *INOUT); +}; + +int count(char c, char *str, int len);In Java, the input parameter is the first element in a 1 element - array and is replaced by the output of the function. For example:
+When a multi-argument typemap is defined, the arguments are always + handled as a single Java parameter. This allows the function to be used + like this (notice how the length parameter is omitted):
--int[] neg = {3}; -example.negate(neg); -System.out.println("Negative of 3 = " + neg[0]); +int c = example.count('e',"Hello World");And no prizes for guessing the output:
+25.9.5 Typemaps for mapping + C/C++ types to Java types
+The typemaps available to the Java module include the common + typemaps listed in the main typemaps section. There are a number of + additional typemaps which are necessary for using SWIG with Java. The + most important of these implement the mapping of C/C++ types to Java + types:
+
++
++ Typemap Description + jni JNI C types. These provide the default mapping of + types from C/C++ to JNI for use in the JNI (C/C++) code. + jtype Java intermediary types. These provide the default + mapping of types from C/C++ to Java for use in the native functions in + the intermediary JNI class. The type must be the equivalent Java type + for the JNI C type specified in the "jni" typemap. + jstype Java types. These provide the default mapping of + types from C/C++ to Java for use in the Java module class, proxy + classes and type wrapper classes. + javain Conversion from jstype to jtype. These are Java + code typemaps which transform the type used in the Java module class, + proxy classes and type wrapper classes (as specified in the "jstype" + typemap) to the type used in the Java intermediary JNI class (as + specified in the "jtype" typemap). In other words the typemap provides + the conversion to the native method call parameter types. + javaout Conversion from jtype to jstype. These are Java + code typemaps which transform the type used in the Java intermediary + JNI class (as specified in the "jtype" typemap) to the Java type used + in the Java module class, proxy classes and type wrapper classes (as + specified in the "jstype" typemap). In other words the typemap provides + the conversion from the native method call return type. + javadirectorin Conversion from jtype to jstype for + director methods. These are Java code typemaps which transform the type + used in the Java intermediary JNI class (as specified in the "jtype" + typemap) to the Java type used in the Java module class, proxy classes + and type wrapper classes (as specified in the "jstype" typemap). This + typemap provides the conversion for the parameters in the director + methods when calling up from C++ to Java. See +Director typemaps. + javadirectorout Conversion from jstype to jtype for + director methods. These are Java code typemaps which transform the type + used in the Java module class, proxy classes and type wrapper classes + (as specified in the "jstype" typemap) to the type used in the Java + intermediary JNI class (as specified in the "jtype" typemap). This + typemap provides the conversion for the return type in the director + methods when returning from the C++ to Java upcall. See +Director typemaps. + directorin Conversion from C++ type to jni type for + director methods. These are C++ typemaps which convert the parameters + used in the C++ director method to the appropriate JNI intermediary + type. The conversion is done in JNI code prior to calling the Java + function from the JNI code. See +Director typemaps. + directorout Conversion from jni type to C++ type for + director methods. These are C++ typemaps which convert the JNI return + type used in the C++ director method to the appropriate C++ return + type. The conversion is done in JNI code after calling the Java + function from the JNI code. See +Director typemaps. If you are writing your own typemaps to handle a particular type, + you will normally have to write a collection of them. The default + typemaps are in "java.swg" and so might be a good place for + finding typemaps to base any new ones on.
+The "jni", "jtype" and "jstype" typemaps are usually defined + together to handle the Java to C/C++ type mapping. An "in" typemap + should be accompanied by a "javain" typemap and likewise an "out" + typemap by a "javaout" typemap. If an "in" typemap is written, a + "freearg" and "argout" typemap may also need to be written as some + types have a default "freearg" and/or "argout" typemap which may need + overriding. The "freearg" typemap sometimes releases memory allocated + by the "in" typemap. The "argout" typemap sometimes sets values in + function parameters which are passed by reference in Java.
+Note that the "in" typemap marshals the JNI type held in the "jni" + typemap to the real C/C++ type and for the opposite direction, the + "out" typemap marshals the real C/C++ type to the JNI type held in the + "jni" typemap. For +non-primitive types the "in" and "out" typemaps are responsible for + casting between the C/C++ pointer and the 64 bit jlong type. + There is no portable way to cast a pointer into a 64 bit integer type + and the approach taken by SWIG is mostly portable, but breaks C/C++ + aliasing rules. In summary, these rules state that a pointer to any + type must never be dereferenced by a pointer to any other incompatible + type. The following code snippet might aid in understand aliasing rules + better:
--Negative of 3 = -3 + short a; + short* pa = 0; + int i = 0x1234; + + a = (short)i; /* okay */ + a = *(short*)&i; /* breaks aliasing rules */These typemaps can also be applied to C++ references. The above - examples would work the same if they had been defined using references - instead of pointers. For example, the Java code to use the negate - function would be the same if it were defined either as it is above:
+An email posting, +Aliasing, pointer casts and gcc 3.3 elaborates further on the + subject. In SWIG, the "in" and "out" typemaps for pointers are + typically
--void negate(int *INOUT); + %typemap(in) struct Foo * %{ + $1 = *(struct Foo **)&$input; /* cast jlong into C ptr */ + %} + %typemap(out) struct Bar * %{ + *(struct Bar **)&$result = $1; /* cast C ptr into jlong */ + %} + struct Bar {...}; + struct Foo {...}; + struct Bar * FooBar(struct Foo *f);or using a reference:
+resulting in the following code which breaks the aliasing rules:
--void negate(int &INOUT); +SWIGEXPORT jlong JNICALL Java_exampleJNI_FooBar(JNIEnv *jenv, jclass jcls, + jlong jarg1, jobject jarg1_) { + jlong jresult = 0 ; + struct Foo *arg1 = (struct Foo *) 0 ; + struct Bar *result = 0 ; + + (void)jenv; + (void)jcls; + (void)jarg1_; + arg1 = *(struct Foo **)&jarg1; + result = (struct Bar *)FooBar(arg1); + *(struct Bar **)&jresult = result; + return jresult; +}Note: Since most Java primitive types are immutable and are passed - by value, it is not possible to perform in-place modification of a type - passed as a parameter.
-Be aware that the primary purpose of the typemaps.i file is - to support primitive datatypes. Writing a function like this
+If you are using gcc as your C compiler, you might get a + "dereferencing type-punned pointer will break strict-aliasing rules" + warning about this. Please see +Compiling a dynamic module to avoid runtime problems with these + strict aliasing rules.
+The default code generated by SWIG for the Java module comes from + the typemaps in the "java.swg" library file which implements + the Default primitive + type mappings and +Default typemaps for non-primitive types covered earlier. There are + other type mapping typemaps in the Java library. These are listed + below:
+
++
++ C Type Typemap +File Kind Java Type +Function + primitive pointers and references INPUT +typemaps.i input Java basic types Allows values + to be used for C functions taking pointers for data input. + primitive pointers and references OUTPUT +typemaps.i output Java basic type arrays Allows + values held within an array to be used for C functions taking pointers + for data output. + primitive pointers and references INOUT +typemaps.i input +
outputJava basic type arrays Allows values held + within an array to be used for C functions taking pointers for data + input and output. + string +
wstring[unnamed] std_string.i input +
outputString Use for std::string mapping to Java + String. + arrays of primitive types [unnamed] +arrays_java.i input +
outputarrays of primitive Java types Use for + mapping C arrays to Java arrays. + arrays of classes/structs/unions JAVA_ARRAYSOFCLASSES + macro arrays_java.i input +
outputarrays of proxy classes Use for mapping C + arrays to Java arrays. + arrays of enums ARRAYSOFENUMS arrays_java.i +input +
outputint[] Use for mapping C arrays to Java + arrays (typeunsafe and simple enum wrapping approaches only). + char * BYTE various.i input +byte[] Java byte array is converted to char array ++ char ** STRING_ARRAY various.i input +
outputString[] Use for mapping NULL terminated + arrays of C strings to Java String arrays + unsigned char * NIOBUFFER various.i +input +
outputjava.nio.Buffer Use for mapping directly + allocated buffers to c/c++. useful with directors and long lived memory + objects 25.9.6 Java typemap attributes
+There are a few additional typemap attributes that the Java module + supports.
+The first of these is the 'throws' attribute. The throws attribute + is optional and specified after the typemap name and contains one or + more comma separated classes for adding to the throws clause for any + methods that use that typemap. It is analogous to the +%javaexception feature's throws attribute.
--void foo(Bar *OUTPUT); +%typemap(typemapname, throws="ExceptionClass1, ExceptionClass2") type { ... }will not have the intended effect since typemaps.i does not - define an OUTPUT rule for Bar.
-24.8.2 Simple pointers
-If you must work with simple pointers such as int * or -double * another approach to using typemaps.i is to use - the cpointer.i pointer library file. For example:
+The attribute is necessary for supporting Java checked exceptions + and can be added to just about any typemap. The list of typemaps + include all the C/C++ (JNI) typemaps in the " +Typemaps" chapter and the Java specific typemaps listed in +the previous section, barring the "jni", "jtype" and "jstype" + typemaps as they could never contain code to throw an exception.
+The throws clause is generated for the proxy method as well as the + JNI method in the JNI intermediary class. If a method uses more than + one typemap and each of those typemaps have classes specified in the + throws clause, the union of the exception classes is added to the + throws clause ensuring there are no duplicate classes. See the +NaN exception example for further usage.
+The "jtype" typemap has the optional 'nopgcpp' attribute which can + be used to suppress the generation of the +premature garbage collection prevention parameter.
+The "javain" typemap has the optional 'pre', 'post' and 'pgcppname' + attributes. These are used for generating code before and after the JNI + call in the proxy class or module class. The 'pre' attribute contains + code that is generated before the JNI call and the 'post' attribute + contains code generated after the JNI call. The 'pgcppname' attribute + is used to change the premature garbage + collection prevention parameter name passed to the JNI function. + This is sometimes needed when the 'pre' typemap creates a temporary + variable which is then passed to the JNI function.
+Note that when the + 'pre' or 'post' attributes are specified and the associated type is + used in a constructor, a constructor helper function is generated. This + is necessary as the Java proxy constructor wrapper makes a call to a + support constructor using a this call. In Java the this + call must be the first statement in the constructor body. The + constructor body thus calls the helper function and the helper function + instead makes the JNI call, ensuring the 'pre' code is called before + the JNI call is made. There is a Date + marshalling example showing 'pre', 'post' and 'pgcppname' + attributes in action.
+25.9.7 Java special variables
+The standard SWIG special variables are available for use within + typemaps as described in the Typemaps documentation +, for example $1, $input,$result etc.
+The Java module uses a few additional special variables:
+$javaclassname +
+
This special variable works like the other +special variables and $javaclassname is similar to +$1_type. It expands to the class name for use in Java given a + pointer. SWIG wraps unions, structs and classes using pointers and in + this case it expands to the Java proxy class name. For example, +$javaclassname is replaced by the proxy classname Foo when + wrapping a Foo * and $&javaclassname expands to the + proxy classname when wrapping the C/C++ type Foo and +$*javaclassname expands to the proxy classname when wrapping +Foo *&. If the type does not have an associated proxy class, it + expands to the type wrapper class name, for example, +SWIGTYPE_p_unsigned_short is generated when wrapping unsigned + short *. The class name is fully qualified with the package name + when using the nspace feature.$javaclazzname +
+
This special variable works like $javaclassname, but + expands the fully qualified C++ class into the package name, if used by + the nspace feature, and the proxy class + name, mangled for use as a function name. For example, +Namespace1::Namespace2::Klass is expanded into +Namespace1_Namespace2_Klass_. This special variable is usually used + for making calls to a function in the intermediary JNI class, as they + are mangled with this prefix.$null +
Used in input typemaps to return early from JNI functions that have + either void or a non-void return type. Example:--%module example -%include "cpointer.i" - -%inline %{ -extern void add(int x, int y, int *result); +%typemap(check) int * %{ + if (error) { + SWIG_JavaThrowException(jenv, SWIG_JavaIndexOutOfBoundsException, "Array element error"); + return $null; + } %} - -%pointer_functions(int, intp); --The %pointer_functions(type,name) macro generates five - helper functions that can be used to create, destroy, copy, assign, and - dereference a pointer. In this case, the functions are as follows:
----int *new_intp(); -int *copy_intp(int *x); -void delete_intp(int *x); -void intp_assign(int *x, int value); -int intp_value(int *x); --In Java, you would use the functions like this:
----SWIGTYPE_p_int intPtr = example.new_intp(); -example.add(3,4,intPtr); -int result = example.intp_value(intPtr); -System.out.println("3 + 4 = " + result); --If you replace %pointer_functions(int,intp) by -%pointer_class(int,intp), the interface is more class-like.
----intp intPtr = new intp(); -example.add(3,4,intPtr.cast()); -int result = intPtr.value(); -System.out.println("3 + 4 = " + result);See the SWIG Library chapter for further - details.
-24.8.3 Wrapping C arrays with Java - arrays
-SWIG can wrap arrays in a more natural Java manner than the default - by using the arrays_java.i library file. Let's consider an - example:
+If the typemap gets put into a function with void as return, $null + will expand to nothing:
--%include "arrays_java.i"; -int array[4]; -void populate(int x[]) { - int i; - for (i=0; i<4; i++) - x[i] = 100 + i; +SWIGEXPORT void JNICALL Java_jnifn(...) { + if (error) { + SWIG_JavaThrowException(jenv, SWIG_JavaIndexOutOfBoundsException, "Array element error"); + return ; + } + ... }These one dimensional arrays can then be used as if they were Java - arrays:
+otherwise $null expands to NULL
--int[] array = new int[4]; -example.populate(array); - -System.out.print("array: "); -for (int i=0; i<array.length; i++) - System.out.print(array[i] + " "); - -example.setArray(array); - -int[] global_array = example.getArray(); - -System.out.print("\nglobal_array: "); -for (int i=0; i<array.length; i++) - System.out.print(global_array[i] + " "); +SWIGEXPORT jobject JNICALL Java_jnifn(...) { + if (error) { + SWIG_JavaThrowException(jenv, SWIG_JavaIndexOutOfBoundsException, "Array element error"); + return NULL; + } + ... +}Java arrays are always passed by reference, so any changes a - function makes to the array will be seen by the calling function. Here - is the output after running this code:
+$javainput, $jnicall and $owner +
+
The $javainput special variable is used in "javain" typemaps and + $jnicall and $owner are used in "javaout" typemaps. $jnicall is + analogous to $action in %exception. It is replaced by the call to the + native method in the intermediary JNI class. $owner is replaced by + either true if %newobject has been used, otherwise false +. $javainput is analogous to the $input special variable. It is replaced + by the parameter name.Here is an example:
--array: 100 101 102 103 -global_array: 100 101 102 103 +%typemap(javain) Class "Class.getCPtr($javainput)" +%typemap(javain) unsigned short "$javainput" +%typemap(javaout) Class * { + return new Class($jnicall, $owner); + } + +%inline %{ + class Class {...}; + Class * bar(Class cls, unsigned short ush) { return new Class(); }; +%}Note that for assigning array variables the length of the C variable - is used, so it is possible to use a Java array that is bigger than the - C code will cope with. Only the number of elements in the C array will - be used. However, if the Java array is not large enough then you are - likely to get a segmentation fault or access violation, just like you - would in C. When arrays are used in functions like populate, - the size of the C array passed to the function is determined by the - size of the Java array.
-Please be aware that the typemaps in this library are not efficient - as all the elements are copied from the Java array to a C array - whenever the array is passed to and from JNI code. There is an - alternative approach using the SWIG array library and this is covered - in the next section.
-24.8.4 Unbounded C Arrays
-Sometimes a C function expects an array to be passed as a pointer. - For example,
+The generated proxy code is then:
--int sumitems(int *first, int nitems) { - int i, sum = 0; - for (i = 0; i < nitems; i++) { - sum += first[i]; - } - return sum; +public static Class bar(Class cls, int ush) { + return new Class(exampleJNI.bar(Class.getCPtr(cls), cls, ush), false); }One of the ways to wrap this is to apply the Java array typemaps - that come in the arrays_java.i library file:
+Here $javainput has been replaced by cls and ush. + $jnicall has been replaced by the native method call, +exampleJNI.bar(...) and $owner has been replaced by false. + If %newobject is used by adding the following at the beginning of our + example:
--%include "arrays_java.i" -%apply int[] {int *}; +%newobject bar(Class cls, unsigned short ush);The ANY size will ensure the typemap is applied to arrays - of all sizes. You could narrow the typemap matching rules by specifying - a particular array size. Now you can use a pure Java array and pass it - to the C code:
+The generated code constructs the return type using true + indicating the proxy class Class is responsible for destroying + the C++ memory allocated for it in bar:
--int[] array = new int[10000000]; // Array of 10-million integers -for (int i=0; i<array.length; i++) { // Set some values - array[i] = i; +public static Class bar(Class cls, int ush) { + return new Class(exampleJNI.bar(Class.getCPtr(cls), cls, ush), true); } -int sum = example.sumitems(array,10000); -System.out.println("Sum = " + sum);and the sum would be displayed:
+$static +
+
This special variable expands to either static or nothing + depending on whether the class is an inner Java class or not. It is + used in the "javaclassmodifiers" typemap so that global classes can be + wrapped as Java proxy classes and nested C++ classes/enums can be + wrapped with the Java equivalent, that is, static inner proxy classes.$error, $jniinput, $javacall and $packagepath +
+
These special variables are used in the directors typemaps. See +Director specific typemaps for details.$module +
+
This special variable expands to the module name, as specified by +%module or the -module commandline option.$imclassname +
+
This special variable expands to the intermediary class name. + Usually this is the same as '$moduleJNI', unless the jniclassname + attribute is specified in the %module + directive.$javainterfacename +
This special variable is only expanded when the interface + feature is applied to a class. It works much like $javaclassname +, but instead of expanding to the proxy classname, it expands to the + value in the name attribute in the interface feature. + For example:--Sum = 49995000 +%feature("interface", name="MyInterface") MyClass; +%typemap(jstype) MyClass "$&javainterfacename" +%typemap(jstype) MyClass * "$javainterfacename"This approach is probably the most natural way to use arrays. - However, it suffers from performance problems when using large arrays - as a lot of copying of the elements occurs in transferring the array - from the Java world to the C++ world. An alternative approach to using - Java arrays for C arrays is to use an alternative SWIG library file -carrays.i. This approach can be more efficient for large arrays as - the array is accessed one element at a time. For example:
+will result in the jstype typemap expanding to +MyInterface for both MyClass and MyClass *. The + interface name is fully qualified with the package name when using the nspace feature.
+$interfacename +
+
This special variable is only expanded when the interface + feature is applied to a class. It expands to just the interface name + and is thus different to $javainterfacename in that it is not + fully qualified with the package name when using the +nspace feature.25.9.8 Typemaps for both C and + C++ compilation
+JNI calls must be written differently depending on whether the code + is being compiled as C or C++. For example C compilation requires the + pointer to a function pointer struct member syntax like
--%include "carrays.i" -%array_functions(int, intArray); +const jclass clazz = (*jenv)->FindClass(jenv, "java/lang/String");The %array_functions(type,name) macro generates four helper - functions that can be used to create and destroy arrays and operate on - elements. In this case, the functions are as follows:
+whereas C++ code compilation of the same function call is a member + function call using a class pointer like
--int *new_intArray(int nelements); -void delete_intArray(int *x); -int intArray_getitem(int *x, int index); -void intArray_setitem(int *x, int index, int value); +const jclass clazz = jenv->FindClass("java/lang/String");In Java, you would use the functions like this:
+To enable typemaps to be used for either C or C++ compilation, a set + of JCALLx macros have been defined in Lib/java/javahead.swg, where x is + the number of arguments in the C++ version of the JNI call. The above + JNI calls would be written in a typemap like this
--SWIGTYPE_p_int array = example.new_intArray(10000000); // Array of 10-million integers -for (int i=0; i<10000; i++) { // Set some values - example.intArray_setitem(array,i,i); -} -int sum = example.sumitems(array,10000); -System.out.println("Sum = " + sum); +const jclass clazz = JCALL1(FindClass, jenv, "java/lang/String");If you replace %array_functions(int,intp) by -%array_class(int,intp), the interface is more class-like and a - couple more helper functions are available for casting between the - array and the type wrapper class.
+Note that the SWIG preprocessor expands these into the appropriate C + or C++ JNI calling convention. The C calling convention is emitted by + default and the C++ calling convention is emitted when using the -c++ + SWIG commandline option. If you do not intend your code to be targeting + both C and C++ then your typemaps can use the appropriate JNI calling + convention and need not use the JCALLx macros.
+25.9.9 Java code typemaps
+Most of SWIG's typemaps are used for the generation of C/C++ code. + The typemaps in this section are used solely for the generation of Java + code. Elements of proxy classes and type wrapper classes come from the + following typemaps (the defaults).
+%typemap(javabase)
+base (extends) for Java class: empty default ++
Note that this typemap accepts a replace attribute as an + optional flag. When set to "1", it will replace/override any C++ base + classes that might have been parsed. If this flag is not specified and + there are C++ base classes, then a multiple inheritance warning is + issued and the code in the typemap is ignored. The typemap also accepts + a notderived attribute as an optional flag. When set to "1", + it will not apply to classes that are derived from a C++ base. When + used with the SWIGTYPE type, it is useful for giving a common base for + all proxy classes, that is, providing a base class that sits in between + all proxy classes and the Java base class Object for example: +%typemap(javabase, notderived="1") SWIGTYPE "CommonBase".%typemap(javabody)
+the essential support body for proxy classes (proxy + base classes only), typewrapper classes and enum classes. Default + contains extra constructors, memory ownership control member variables + (swigCMemOwn, swigCPtr), the getCPtr method + etc.+%typemap(javabody_derived)
+the essential support body for proxy classes + (derived classes only). Same as "javabody" typemap, but only used for + proxy derived classes.+%typemap(javaclassmodifiers)
+class modifiers for the Java class: default is + "public class"+%typemap(javacode)
+Java code is copied verbatim to the Java class: + empty default+%typemap(javadestruct, methodname="delete", + methodmodifiers="public synchronized") +
+destructor wrapper - the delete() method + (proxy classes only), used for all proxy classes except those which + have a base class : default calls C++ destructor (or frees C memory) + and resets swigCPtr and swigCMemOwn flags ++
+
Note that the delete() method name is configurable and is + specified by the methodname attribute. The method modifiers + are also configurable via the methodmodifiers attribute.%typemap(javadestruct_derived, methodname="delete", + methodmodifiers="public synchronized")
+destructor wrapper - the delete() method + (proxy classes only), same as "javadestruct" but only used for derived + proxy classes : default calls C++ destructor (or frees C memory) and + resets swigCPtr and swigCMemOwn flags ++
+
Note that the delete() method name is configurable and is + specified by the methodname attribute. The method modifiers + are also configurable via the methodmodifiers attribute.%typemap(javaimports)
+import statements for Java class: empty default+%typemap(javainterfaces)
+interfaces (implements) for Java class: empty + default+%typemap(javafinalize)
+the finalize() method (proxy classes + only): default calls the delete() method +Note that the default javafinalize typemap must contain the full + implementation of the finalize method. Any customization to this + typemap must still declare a java finalize method with the correct + signature. Note also that the name of the generated "delete" method may + be affected by javadestruct and javadestruct_derived + typemaps. Below shows an example modifying the finalizer, assuming the +delete method has been renamed to swig_delete.
--%include "carrays.i" -%array_class(int, intArray); +%typemap(javafinalize) SWIGTYPE %{ + protected void finalize() { + swig_delete(); // renamed to prevent conflict with existing delete method + } +]%-The %array_class(type, name) macro creates wrappers for an - unbounded array object that can be passed around as a simple pointer - like int * or double *. For instance, you will be - able to do this in Java:
+%typemap(javainterfacecode, declaration="...", cptrmethod="...") +
+++The code in this typemap is added to the body of a Java proxy class + but only when a class is marked with the interface feature. + The typemap is used in the proxy class marked with the interface + feature as well as all proxy classes derived from the marked C++ class, + as they are all generated as implementing the Java interface. The + default typemap used in the %interface family of macros + mentioned in the Java interfaces + section, where CTYPE is the C++ class macro argument, is as + follows:
-intArray array = new intArray(10000000); // Array of 10-million integers -for (int i=0; i<10000; i++) { // Set some values - array.setitem(i,i); +%typemap(javainterfacecode, + declaration=" long $interfacename_GetInterfaceCPtr();\n", + cptrmethod="$interfacename_GetInterfaceCPtr") CTYPE %{ + public long $interfacename_GetInterfaceCPtr() { + return $imclassname.$javaclazzname$interfacename_GetInterfaceCPtr(swigCPtr); + } +%} ++The special variable $interfacename is expanded into the + name specified in the interface feature.
+Compatibility Note: In SWIG-1.3.21 and earlier releases, + typemaps called "javagetcptr" and "javaptrconstructormodifiers" were + available. These are deprecated and the "javabody" typemap can be used + instead. The javainterfacecode typemap and interface feature + was introduced in SWIG-3.0.9.
+In summary the contents of the typemaps make up a proxy class like + this:
++-+[ javaimports typemap ] +[ javaclassmodifiers typemap ] javaclassname extends [ javabase typemap ] + implements [ javainterfaces typemap ] { +[ javabody or javabody_derived typemap ] +[ javafinalize typemap ] +public synchronized void delete() [ javadestruct OR javadestruct_derived typemap ] +[ javacode typemap ] +[ javainterfacecode typemap] +... proxy functions ... } -int sum = example.sumitems(array.cast(),10000); -System.out.println("Sum = " + sum);The array "object" created by %array_class() does not - encapsulate pointers inside a special array object. In fact, there is - no bounds checking or safety of any kind (just like in C). Because of - this, the arrays created by this library are extremely low-level - indeed. You can't iterate over them nor can you even query their - length. In fact, any valid memory address can be accessed if you want - (negative indices, indices beyond the end of the array, etc.). Needless - to say, this approach is not going to suit all applications. On the - other hand, this low-level approach is extremely efficient and well - suited for applications in which you need to create buffers, package - binary data, etc.
-24.8.5 Binary data vs Strings
-By default SWIG handles char * as a string but there is a - handy multi-argument typemap available as mentioned in -Passing binary data. The following simple example demonstrates using - a byte array instead of passing the default string type and length to - the wrapped function.
+Note the delete() methodname and method modifiers + are configurable, see "javadestruct" and "javadestruct_derived" + typemaps above.
+The javainterfacecode typemap is only used when bases are + marked by the interface feature and the implements + list will also then be expanded to include these Java interfaces.
+The type wrapper class is similar in construction:
--%apply (char *STRING, size_t LENGTH) { (const char data[], size_t len) } -%inline %{ -void binaryChar1(const char data[], size_t len) { - printf("len: %d data: ", len); - for (size_t i=0; i<len; ++i) - printf("%x ", data[i]); - printf("\n"); +[ javaimports typemap ] +[ javaclassmodifiers typemap ] javaclassname extends [ javabase typemap ] + implements [ javainterfaces typemap ] { +[ javabody typemap ] +[ javacode typemap ] } -%}Calling from Java requires just the byte array to be passed in as - the multi-argument typemap being applied reduces the number of - arguments in the target language to one, from the original two:
+The enum class is also similar in construction:
--byte[] data = "hi\0jk".getBytes(); -example.binaryChar1(data); +[ javaimports typemap ] +[ javaclassmodifiers typemap ] javaclassname extends [ javabase typemap ] + implements [ javainterfaces typemap ] { +... Enum values ... +[ javabody typemap ] +[ javacode typemap ] +}resulting in the output
+The "javaimports" typemap is ignored if the enum class is wrapped by + an inner Java class, that is when wrapping an enum declared within a + C++ class.
+The Java interface turned on by the interface feature is + fairly simple:
--$ java runme -len: 5 data: 68 69 0 6a 6b +[ javaimports typemap ] +public interface [ javainterfacename ] { +[ javainterfacecode:cptrmethod typemap attribute ] +... interface declarations ... +}24.8.6 Overriding new and delete - to allocate from Java heap
-Unlike some languages supported by SWIG, Java has a true garbage - collection subsystem. Other languages will free SWIG wrapped objects - when their reference count reaches zero. Java only schedules these - objects for finalization, which may not occur for some time. Because - SWIG objects are allocated on the C heap, Java users may find the JVM - memory use quickly exceeds the assigned limits, as memory fills with - unfinalized proxy objects. Forcing garbage collection is clearly an - undesirable solution.
-An elegant fix for C++ users is to override new and delete using the - following code (here shown included in a SWIG interface file)
+where javainterfacename is the name attribute in + the interface feature.
+The defaults can be overridden to tailor the generated classes. Here + is an example which will change the getCPtr method and + constructor from the default public access to protected access. If the + classes in one package are not using the classes in another package, + then these methods need not be public and removing access to these low + level implementation details, is a good thing. If you are invoking SWIG + more than once and generating the wrapped classes into different + packages in each invocation, then you cannot do this as you will then + have different packages.
+-/* File: java_heap.i */ -%module test -%{ -#include <stdexcept> -#include "jni.h" - -/** - * A stash area embedded in each allocation to hold java handles - */ -struct Jalloc { - jbyteArray jba; - jobject ref; -}; - -static JavaVM *cached_jvm = 0; +%typemap(javabody) SWIGTYPE %{ + private transient long swigCPtr; + protected transient boolean swigCMemOwn; -JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *jvm, void *reserved) { - cached_jvm = jvm; - return JNI_VERSION_1_2; -} + protected $javaclassname(long cPtr, boolean cMemoryOwn) { + swigCMemOwn = cMemoryOwn; + swigCPtr = cPtr; + } -static JNIEnv * JNU_GetEnv() { - JNIEnv *env; - jint rc = cached_jvm->GetEnv((void **)&env, JNI_VERSION_1_2); - if (rc == JNI_EDETACHED) - throw std::runtime_error("current thread not attached"); - if (rc == JNI_EVERSION) - throw std::runtime_error("jni version not supported"); - return env; -} + protected static long getCPtr($javaclassname obj) { + return (obj == null) ? 0 : obj.swigCPtr; + } +%} ++The typemap code is the same that is in "java.swg", barring + the last two method modifiers. Note that SWIGTYPE will target + all proxy classes, but not the type wrapper classes. Also the above + typemap is only used for proxy classes that are potential base classes. + To target proxy classes that are derived from a wrapped class as well, + the "javabody_derived" typemap should also be overridden.
+For the typemap to be used in all type wrapper classes, all the + different types that type wrapper classes could be used for should be + targeted:
++-+%typemap(javabody) SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) %{ + private transient long swigCPtr; -void * operator new(size_t t) { - if (cached_jvm != 0) { - JNIEnv *env = JNU_GetEnv(); - jbyteArray jba = env->NewByteArray((int) t + sizeof(Jalloc)); - if (env->ExceptionOccurred()) - throw bad_alloc(); - void *jbuffer = static_cast<void *>(env->GetByteArrayElements(jba, 0)); - if (env->ExceptionOccurred()) - throw bad_alloc(); - Jalloc *pJalloc = static_cast<Jalloc *>(jbuffer); - pJalloc->jba = jba; - /* Assign a global reference so byte array will persist until delete'ed */ - pJalloc->ref = env->NewGlobalRef(jba); - if (env->ExceptionOccurred()) - throw bad_alloc(); - return static_cast<void *>(static_cast<char *>(jbuffer) + sizeof(Jalloc)); + protected $javaclassname(long cPtr, boolean bFutureUse) { + swigCPtr = cPtr; } - else { /* JNI_OnLoad not called, use malloc and mark as special */ - Jalloc *pJalloc = static_cast<Jalloc *>(malloc((int) t + sizeof(Jalloc))); - if (!pJalloc) - throw bad_alloc(); - pJalloc->ref = 0; - return static_cast<void *>( - static_cast<char *>(static_cast<void *>(pJalloc)) + sizeof(Jalloc)); + + protected $javaclassname() { + swigCPtr = 0; } -} -void operator delete(void *v) { - if (v != 0) { - void *buffer = static_cast<void *>( static_cast<char *>(v) - sizeof(Jalloc)); - Jalloc *pJalloc = static_cast<Jalloc *>(buffer); - if (pJalloc->ref) { - JNIEnv *env = JNU_GetEnv(); - env->DeleteGlobalRef(pJalloc->ref); - env->ReleaseByteArrayElements(pJalloc->jba, static_cast<jbyte *>(buffer), 0); - } - else { - free(buffer); - } + protected static long getCPtr($javaclassname obj) { + return (obj == null) ? 0 : obj.swigCPtr; } -} %} -...This code caches the Java environment during initialization, and - when new is called, a Java ByteArray is allocated to provide the SWIG - objects with space in the Java heap. This has the combined effect of - re-asserting the Java virtual machine's limit on memory allocation, and - puts additional pressure on the garbage collection system to run more - frequently. This code is made slightly more complicated because - allowances must be made if new is called before the JNI_OnLoad is - executed. This can happen during static class initialization, for - example.
-Unfortunately, because most Java implementations call malloc and - free, this solution will not work for C wrapped structures. However, - you are free to make functions that allocate and free memory from the - Java heap using this model and use these functions in place of malloc - and free in your own code.
-24.9 Java typemaps
-This section describes how you can modify SWIG's default wrapping - behavior for various C/C++ datatypes using the %typemap - directive. You are advised to be familiar with the material in the " -Typemaps" chapter. While not absolutely essential knowledge, this - section assumes some familiarity with the Java Native Interface (JNI). - JNI documentation can be consulted either online at -Sun's Java web site or from a good JNI book. The following two books - are recommended:
--
-- Title: 'Essential JNI: Java Native Interface.' Author: Rob Gordon. - Publisher: Prentice Hall. ISBN: 0-13-679895-0.
-- Title: 'The Java Native Interface: Programmer's Guide and - Specification.' Author: Sheng Liang. Publisher: Addison-Wesley. ISBN: - 0-201-32577-2. Also available -online at the Sun Developer Network.
-Before proceeding, it should be stressed that typemaps are not a - required part of using SWIG---the default wrapping behavior is enough - in most cases. Typemaps are only used if you want to change some aspect - of the generated code.
-24.9.1 Default - primitive type mappings
-The following table lists the default type mapping from Java to - C/C++.
--
-- C/C++ type Java type JNI type - - bool -
const bool &boolean jboolean - char -
const char &char jchar - signed char -
const signed char &byte jbyte - unsigned char -
const unsigned char &short jshort - short -
const short &short jshort - unsigned short -
const unsigned short &int jint - int -
const int &int jint - unsigned int -
const unsigned int &long jlong - long -
const long &int jint - unsigned long -
const unsigned long &long jlong - long long -
const long long &long jlong - unsigned long long -
const unsigned long long &java.math.BigInteger -jobject - float -
const float &float jfloat - double -
const double &double jdouble - char * -
char []String jstring Note that SWIG wraps the C char type as a character. - Pointers and arrays of this type are wrapped as strings. The signed - char type can be used if you want to treat char as a - signed number rather than a character. Also note that all const - references to primitive types are treated as if they are passed by - value.
-Given the following C function:
+Again this is the same that is in "java.swg", barring the + method modifier for getCPtr.
+When using multiple modules or the +nspace feature it is common to invoke SWIG with a different +-package command line option for each module. However, by default + the generated code may not compile if generated classes in one package + use generated classes in another package. The visibility of the +getCPtr() and pointer constructor generated from the javabody + typemaps needs changing. The default visibility is protected + but it needs to be public for access from a different package. + Just changing 'protected' to 'public' in the typemap achieves this. Two + macros are available in java.swg to make this easier and using + them is the preferred approach over simply copying the typemaps and + modifying as this is forward compatible with any changes in the +javabody typemap in future versions of SWIG. The macros are for the + proxy and typewrapper classes and can respectively be used to to make + the method and constructor public:
++++ SWIG_JAVABODY_PROXY(public, public, SWIGTYPE) + SWIG_JAVABODY_TYPEWRAPPER(public, public, public, SWIGTYPE) ++25.9.10 Director specific typemaps +
+The Java directors feature requires the "javadirectorin", + "javadirectorout", "directorin" and the "directorout" typemaps in order + to work properly. The "javapackage" typemap is an optional typemap used + to identify the Java package path for individual SWIG generated proxy + classes used in director methods.
+%typemap(directorin)
+++The "directorin" typemap is used for converting arguments in the C++ + director class to the appropriate JNI type before the upcall to Java. + This typemap also specifies the JNI field descriptor for the type in + the "descriptor" attribute. For example, integers are converted as + follows:
++++%typemap(directorin,descriptor="I") int "$input = (jint) $1;" ++
$input
is the SWIG name of the JNI temporary variable + passed to Java in the upcall. Thedescriptor="I"
will put + anI
into the JNI field descriptor that identifies the + Java method that will be called from C++. For more about JNI field + descriptors and their importance, refer to the +JNI documentation mentioned earlier. A typemap for C character + strings is:--void func(unsigned short a, char *b, const long &c, unsigned long long d); +%typemap(directorin,descriptor="Ljava/lang/String;") char * + %{ $input = jenv->NewStringUTF($1); %}The module class method would be:
+User-defined types have the default "descriptor" attribute "
++L$packagepath/$javaclassname;
" where$packagepath
is + the package name passed from the SWIG command line and+$javaclassname
is the Java proxy class' name. If the -package + commandline option is not used to specify the package, then + '$packagepath/' will be removed from the resulting output JNI field + descriptor. Do not forget the terminating ';' for JNI field + descriptors starting with 'L'. If the ';' is left out, Java will + generate a "method not found" runtime error. Note that the+$packagepath
substitution always uses the path separator '/' when + expanded. The$javaclassname
expansion can be confusing as + it is normally expanded using the '.' separator. However,+$javaclassname
is expanded using the path separator '/' in + typemap's "descriptor" attribute as well as in the "directorthrows" + typemap.%typemap(directorout)
+++The "directorout" typemap is used for converting the JNI return type + in the C++ director class to the appropriate C++ type after the upcall + to Java. For example, integers are converted as follows:
--public static void func(int a, String b, int c, java.math.BigInteger d) {...} +%typemap(directorout) int %{ $result = (int)$input; %}The intermediary JNI class would use the same types:
+
$input
is the SWIG name of the JNI temporary variable + returned from Java after the upcall.$result
is the + resulting output. A typemap for C character strings is:-public final static native void func(int jarg1, String jarg2, int jarg3, - java.math.BigInteger jarg4); +%typemap(directorout) char * { + $1 = 0; + if ($input) { + $result = (char *)jenv->GetStringUTFChars($input, 0); + if (!$1) return $null; + } +} ++%typemap(javadirectorin)
+++Conversion from jtype to jstype for director methods. These are Java + code typemaps which transform the type used in the Java intermediary + JNI class (as specified in the "jtype" typemap) to the Java type used + in the Java module class, proxy classes and type wrapper classes (as + specified in the "jstype" typemap). This typemap provides the + conversion for the parameters in the director methods when calling up + from C++ to Java.
+For primitive types, this typemap is usually specified as:
++-+%typemap(javadirectorin) int "$jniinput"and the JNI function would look like this:
+The
+$jniinput
special variable is analogous to+$javainput
special variable. It is replaced by the input + parameter name.%typemap(javadirectorout)
+++Conversion from jstype to jtype for director methods. These are Java + code typemaps which transform the type used in the Java module class, + proxy classes and type wrapper classes (as specified in the "jstype" + typemap) to the type used in the Java intermediary JNI class (as + specified in the "jtype" typemap). This typemap provides the conversion + for the return type in the director methods when returning from the C++ + to Java upcall.
+For primitive types, this typemap is usually specified as:
--SWIGEXPORT void JNICALL Java_exampleJNI_func(JNIEnv *jenv, jclass jcls, - jint jarg1, jstring jarg2, jint jarg3, jobject jarg4) {...} +%typemap(javadirectorout) int "$javacall"The mappings for C int and C long are appropriate - for 32 bit applications which are used in the 32 bit JVMs. There is no - perfect mapping between Java and C as Java doesn't support all the - unsigned C data types. However, the mappings allow the full range of - values for each C type from Java.
-24.9.2 Default - typemaps for non-primitive types
-The previous section covered the primitive type mappings. - Non-primitive types such as classes and structs are mapped using - pointers on the C/C++ side and storing the pointer into a Java long - variable which is held by the proxy class or type wrapper class. This - applies whether the type is marshalled as a pointer, by reference or by - value. It also applies for any unknown/incomplete types which use type - wrapper classes.
-So in summary, the C/C++ pointer to non-primitive types is cast into - the 64 bit Java long type and therefore the JNI type is a -jlong. The Java type is either the proxy class or type wrapper - class.
-24.9.3 Sixty four bit JVMs
-If you are using a 64 bit JVM you may have to override the C long, - but probably not C int default mappings. Mappings will be system - dependent, for example long will need remapping on Unix LP64 systems - (long, pointer 64 bits, int 32 bits), but not on Microsoft 64 bit - Windows which will be using a P64 IL32 (pointer 64 bits and int, long - 32 bits) model. This may be automated in a future version of SWIG. Note - that the Java write once run anywhere philosophy holds true for all - pure Java code when moving to a 64 bit JVM. Unfortunately it won't of - course hold true for JNI code.
-24.9.4 What is a typemap?
-A typemap is nothing more than a code generation rule that is - attached to a specific C datatype. For example, to convert integers - from Java to C, you might define a typemap like this:
+The
+$javacall
special variable is analogous to the+$jnicall
special variable. It is replaced by the call to the + target Java method. The target method is the method in the Java proxy + class which overrides the virtual C++ method in the C++ base class.%typemap(directorthrows)
+++Conversion of Java exceptions to C++ exceptions in director method's + exception handling. This typemap is expected to test the $error + special variable for a matching Java exception and if successful + convert and throw it into a C++ exception given by the typemap's type. + The
+$error
special variable is of typejthrowable
+ and is substituted with a unique variable name in the generated code.The example below converts a Java
+java.lang.IndexOutOfBoundsException
exception to the typemap's + type, that isstd::out_of_range
:--%module example - -%typemap(in) int { - $1 = $input; - printf("Received an integer : %d\n", $1); -} -%inline %{ -extern int fact(int nonnegative); +%typemap(directorthrows) std::out_of_range %{ + if (Swig::ExceptionMatches(jenv, $error, "java/lang/IndexOutOfBoundsException")) { + throw std::out_of_range(Swig::JavaExceptionMessage(jenv, $error).message()); + } %}Typemaps are always associated with some specific aspect of code - generation. In this case, the "in" method refers to the conversion of - input arguments to C/C++. The datatype int is the datatype to - which the typemap will be applied. The supplied C code is used to - convert values. In this code a number of special variables prefaced by - a $ are used. The $1 variable is a placeholder for a - local variable of type int. The $input variable - contains the Java data, the JNI jint in this case.
-When this example is compiled into a Java module, it can be used as - follows:
+The utility function
+Swig::ExceptionMatches
and class+Swig::JavaExceptionMessage
are helpers available when using + directors and are described in the +Java Exceptions from Directors section.%typemap(javapackage)
+++The "javapackage" typemap is optional; it serves to identify a + class's Java package. This typemap should be used in conjunction with + classes that are defined outside of the current SWIG interface file. + The typemap is only used if the type is used in a director method, that + is, in a virtual method in a director class. For example:
--System.out.println(example.fact(6)); +// class Foo is handled in a different interface file: +%import "Foo.i" + +%feature("director") Example; + +%inline { + class Bar { }; + + class Example { + public: + virtual ~Example(); + virtual void ping(Foo *arg1, Bar *arg2); + }; +}and the output will be:
+Assume that the Foo class is part of the Java package + com.wombat.foo but the above interface file is part of the Java + package com.wombat.example. Without the "javapackage" typemap, + SWIG will assume that the Foo class belongs to com.wombat.example + class. The corrected interface file looks like:
--Received an integer : 6 -720 +// class Foo is handled in a different interface file: +%import "Foo.i" +%typemap("javapackage") Foo, Foo *, Foo & "com.wombat.foo"; +%feature("director") Example; + +%inline { + class Bar { }; + + class Example { + public: + virtual ~Example(); + virtual void ping(Foo *arg1, Bar *arg2); + }; +}In this example, the typemap is applied to all occurrences of the -int datatype. You can refine this by supplying an optional - parameter name. For example:
+SWIG looks up the package based on the actual type (plain + Foo, Foo pointer and Foo reference), so it is important to associate + all three types with the desired package. Practically speaking, you + should create a separate SWIG interface file, which is %import-ed into + each SWIG interface file, when you have multiple Java packages. Note + the helper macros below,
OTHER_PACKAGE_SPEC
and+ANOTHER_PACKAGE_SPEC
, which reduce the amount of extra typing. "+TYPE...
" is useful when passing templated types to the macro, + since multiargument template types appear to the SWIG preprocessor as + multiple macro arguments.--%module example +%typemap("javapackage") SWIGTYPE, SWIGTYPE *, SWIGTYPE & + "package.for.most.classes"; -%typemap(in) int nonnegative { - $1 = $input; - printf("Received an integer : %d\n", $1); -} +%define OTHER_PACKAGE_SPEC(TYPE...) +%typemap("javapackage") TYPE, TYPE *, TYPE & "package.for.other.classes"; +%enddef -%inline %{ -extern int fact(int nonnegative); -%} +%define ANOTHER_PACKAGE_SPEC(TYPE...) +%typemap("javapackage") TYPE, TYPE *, TYPE & "package.for.another.set"; +%enddef + +OTHER_PACKAGE_SPEC(Package_2_class_one) +ANOTHER_PACKAGE_SPEC(Package_3_class_two) +/* etc */In this case, the typemap code is only attached to arguments that - exactly match int nonnegative.
-The application of a typemap to specific datatypes and argument - names involves more than simple text-matching--typemaps are fully - integrated into the SWIG C++ type-system. When you define a typemap for - int, that typemap applies to int and qualified - variations such as const int. In addition, the typemap system - follows typedef declarations. For example:
+The basic strategy here is to provide a default package typemap for + the majority of the classes, only providing "javapackage" typemaps for + the exceptions.
+25.10 Typemap Examples
+This section includes a few examples of typemaps. For more examples, + you might look at the files "java.swg" and "typemaps.i +" in the SWIG library.
+25.10.1 Simpler Java enums for + enums without initializers
+The default Proper Java enums + approach to wrapping enums is somewhat verbose. This is to handle all + possible C/C++ enums, in particular enums with initializers. The + generated code can be simplified if the enum being wrapped does not + have any initializers.
+The following shows how to remove the support methods that are + generated by default and instead use the methods in the Java enum base + class java.lang.Enum and java.lang.Class for + marshalling enums between C/C++ and Java. The type used for the + typemaps below is enum SWIGTYPE which is the default type used + for all enums. The "enums.swg" file should be examined in order to see + the original overridden versions of the typemaps.
--%typemap(in) int nonnegative { - $1 = $input; - printf("Received an integer : %d\n", $1); -} +%include "enums.swg" + +%typemap(javain) enum SWIGTYPE "$javainput.ordinal()" +%typemap(javaout) enum SWIGTYPE { + return $javaclassname.class.getEnumConstants()[$jnicall]; + } +%typemap(javabody) enum SWIGTYPE "" + %inline %{ -typedef int Integer; -extern int fact(Integer nonnegative); // Above typemap is applied + enum HairType { blonde, ginger, brunette }; + void setHair(HairType h); + HairType getHair(); %}However, the matching of typedef only occurs in one - direction. If you defined a typemap for Integer, it is not - applied to arguments of type int.
-Typemaps can also be defined for groups of consecutive arguments. - For example:
+SWIG will generate the following Java enum, which is somewhat + simpler than the default:
--%typemap(in) (char *str, int len) { -... -}; - -int count(char c, char *str, int len); +public enum HairType { + blonde, + ginger, + brunette; +}When a multi-argument typemap is defined, the arguments are always - handled as a single Java parameter. This allows the function to be used - like this (notice how the length parameter is omitted):
+and the two Java proxy methods will be:
--int c = example.count('e',"Hello World"); +public static void setHair(HairType h) { + exampleJNI.setHair(h.ordinal()); +} + +public static HairType getHair() { + return HairType.class.getEnumConstants()[exampleJNI.getHair()]; +}24.9.5 Typemaps for - mapping C/C++ types to Java types
-The typemaps available to the Java module include the common - typemaps listed in the main typemaps section. There are a number of - additional typemaps which are necessary for using SWIG with Java. The - most important of these implement the mapping of C/C++ types to Java - types:
-
--
-- Typemap Description - jni JNI C types. These provide the default mapping of - types from C/C++ to JNI for use in the JNI (C/C++) code. - jtype Java intermediary types. These provide the default - mapping of types from C/C++ to Java for use in the native functions in - the intermediary JNI class. The type must be the equivalent Java type - for the JNI C type specified in the "jni" typemap. - jstype Java types. These provide the default mapping of - types from C/C++ to Java for use in the Java module class, proxy - classes and type wrapper classes. - javain Conversion from jstype to jtype. These are Java - code typemaps which transform the type used in the Java module class, - proxy classes and type wrapper classes (as specified in the "jstype" - typemap) to the type used in the Java intermediary JNI class (as - specified in the "jtype" typemap). In other words the typemap provides - the conversion to the native method call parameter types. - javaout Conversion from jtype to jstype. These are Java - code typemaps which transform the type used in the Java intermediary - JNI class (as specified in the "jtype" typemap) to the Java type used - in the Java module class, proxy classes and type wrapper classes (as - specified in the "jstype" typemap). In other words the typemap provides - the conversion from the native method call return type. - javadirectorin Conversion from jtype to jstype for - director methods. These are Java code typemaps which transform the type - used in the Java intermediary JNI class (as specified in the "jtype" - typemap) to the Java type used in the Java module class, proxy classes - and type wrapper classes (as specified in the "jstype" typemap). This - typemap provides the conversion for the parameters in the director - methods when calling up from C++ to Java. See -Director typemaps. - javadirectorout Conversion from jstype to jtype for - director methods. These are Java code typemaps which transform the type - used in the Java module class, proxy classes and type wrapper classes - (as specified in the "jstype" typemap) to the type used in the Java - intermediary JNI class (as specified in the "jtype" typemap). This - typemap provides the conversion for the return type in the director - methods when returning from the C++ to Java upcall. See -Director typemaps. - directorin Conversion from C++ type to jni type for - director methods. These are C++ typemaps which convert the parameters - used in the C++ director method to the appropriate JNI intermediary - type. The conversion is done in JNI code prior to calling the Java - function from the JNI code. See -Director typemaps. - directorout Conversion from jni type to C++ type for - director methods. These are C++ typemaps which convert the JNI return - type used in the C++ director method to the appropriate C++ return - type. The conversion is done in JNI code after calling the Java - function from the JNI code. See -Director typemaps. If you are writing your own typemaps to handle a particular type, - you will normally have to write a collection of them. The default - typemaps are in "java.swg" and so might be a good place for - finding typemaps to base any new ones on.
-The "jni", "jtype" and "jstype" typemaps are usually defined - together to handle the Java to C/C++ type mapping. An "in" typemap - should be accompanied by a "javain" typemap and likewise an "out" - typemap by a "javaout" typemap. If an "in" typemap is written, a - "freearg" and "argout" typemap may also need to be written as some - types have a default "freearg" and/or "argout" typemap which may need - overriding. The "freearg" typemap sometimes releases memory allocated - by the "in" typemap. The "argout" typemap sometimes sets values in - function parameters which are passed by reference in Java.
-Note that the "in" typemap marshals the JNI type held in the "jni" - typemap to the real C/C++ type and for the opposite direction, the - "out" typemap marshals the real C/C++ type to the JNI type held in the - "jni" typemap. For -non-primitive types the "in" and "out" typemaps are responsible for - casting between the C/C++ pointer and the 64 bit jlong type. - There is no portable way to cast a pointer into a 64 bit integer type - and the approach taken by SWIG is mostly portable, but breaks C/C++ - aliasing rules. In summary, these rules state that a pointer to any - type must never be dereferenced by a pointer to any other incompatible - type. The following code snippet might aid in understand aliasing rules - better:
+For marshalling Java enums to C/C++ enums, the ordinal + method is used to convert the Java enum into an integer value for + passing to the JNI layer, see the "javain" typemap. For marshalling + C/C++ enums to Java enums, the C/C++ enum value is cast to an integer + in the C/C++ typemaps (not shown). This integer value is then used to + index into the array of enum constants that the Java language provides. + See the getEnumConstants method in the "javaout" typemap.
+These typemaps can often be used as the default for wrapping enums + as in many cases there won't be any enum initializers. In fact a good + strategy is to always use these typemaps and to specifically handle + enums with initializers using %apply. This would be done by using the + original versions of these typemaps in "enums.swg" under another + typemap name for applying using %apply.
+25.10.2 Handling C++ exception + specifications as Java exceptions
+This example demonstrates various ways in which C++ exceptions can + be tailored and converted into Java exceptions. Let's consider a simple + file class SimpleFile and an exception class FileException + which it may throw on error:
-- short a; - short* pa = 0; - int i = 0x1234; +%include "std_string.i" // for std::string typemaps +#include <string> - a = (short)i; /* okay */ - a = *(short*)&i; /* breaks aliasing rules */ +class FileException { + std::string message; +public: + FileException(const std::string& msg) : message(msg) {} + std::string what() { + return message; + } +}; + +class SimpleFile { + std::string filename; +public: + SimpleFile(const std::string& filename) : filename(filename) {} + void open() throw(FileException) { + ... + } +};An email posting, -Aliasing, pointer casts and gcc 3.3 elaborates further on the - subject. In SWIG, the "in" and "out" typemaps for pointers are - typically
+As the open method has a C++ exception specification, SWIG + will parse this and know that the method can throw an exception. The +"throws" typemap is then used when SWIG encounters an exception + specification. The default generic "throws" typemap looks like this:
-- %typemap(in) struct Foo * %{ - $1 = *(struct Foo **)&$input; /* cast jlong into C ptr */ - %} - %typemap(out) struct Bar * %{ - *(struct Bar **)&$result = $1; /* cast C ptr into jlong */ - %} - struct Bar {...}; - struct Foo {...}; - struct Bar * FooBar(struct Foo *f); +%typemap(throws) SWIGTYPE, SWIGTYPE &, SWIGTYPE *, SWIGTYPE [ANY] %{ + SWIG_JavaThrowException(jenv, SWIG_JavaRuntimeException, + "C++ $1_type exception thrown"); + return $null; +%}resulting in the following code which breaks the aliasing rules:
+Basically SWIG will generate a C++ try catch block and the body of + the "throws" typemap constitutes the catch block. The above typemap + calls a SWIG supplied method which throws a +java.lang.RuntimeException. This exception class is a runtime + exception and therefore not a checked exception. If, however, we wanted + to throw a checked exception, say java.io.IOException, then we + could use the following typemap:
--SWIGEXPORT jlong JNICALL Java_exampleJNI_FooBar(JNIEnv *jenv, jclass jcls, - jlong jarg1, jobject jarg1_) { - jlong jresult = 0 ; - struct Foo *arg1 = (struct Foo *) 0 ; - struct Bar *result = 0 ; - - (void)jenv; - (void)jcls; - (void)jarg1_; - arg1 = *(struct Foo **)&jarg1; - result = (struct Bar *)FooBar(arg1); - *(struct Bar **)&jresult = result; - return jresult; +%typemap(throws, throws="java.io.IOException") FileException { + jclass excep = jenv->FindClass("java/io/IOException"); + if (excep) + jenv->ThrowNew(excep, $1.what().c_str()); + return $null; }If you are using gcc as your C compiler, you might get a - "dereferencing type-punned pointer will break strict-aliasing rules" - warning about this. Please see -Compiling a dynamic module to avoid runtime problems with these - strict aliasing rules.
-The default code generated by SWIG for the Java module comes from - the typemaps in the "java.swg" library file which implements - the Default primitive - type mappings and -Default typemaps for non-primitive types covered earlier. There are - other type mapping typemaps in the Java library. These are listed - below:
-
--
-- C Type Typemap -File Kind Java Type -Function - primitive pointers and references INPUT -typemaps.i input Java basic types Allows values - to be used for C functions taking pointers for data input. - primitive pointers and references OUTPUT -typemaps.i output Java basic type arrays Allows - values held within an array to be used for C functions taking pointers - for data output. - primitive pointers and references INOUT -typemaps.i input -
outputJava basic type arrays Allows values held - within an array to be used for C functions taking pointers for data - input and output. - string -
wstring[unnamed] std_string.i input -
outputString Use for std::string mapping to Java - String. - arrays of primitive types [unnamed] -arrays_java.i input -
outputarrays of primitive Java types Use for - mapping C arrays to Java arrays. - arrays of classes/structs/unions JAVA_ARRAYSOFCLASSES - macro arrays_java.i input -
outputarrays of proxy classes Use for mapping C - arrays to Java arrays. - arrays of enums ARRAYSOFENUMS arrays_java.i -input -
outputint[] Use for mapping C arrays to Java - arrays (typeunsafe and simple enum wrapping approaches only). - char * BYTE various.i input -byte[] Java byte array is converted to char array -- char ** STRING_ARRAY various.i input -
outputString[] Use for mapping NULL terminated - arrays of C strings to Java String arrays 24.9.6 Java typemap attributes
-There are a few additional typemap attributes that the Java module - supports.
-The first of these is the 'throws' attribute. The throws attribute - is optional and specified after the typemap name and contains one or - more comma separated classes for adding to the throws clause for any - methods that use that typemap. It is analogous to the -%javaexception feature's throws attribute.
+Note that this typemap uses the 'throws' +typemap attribute to ensure a throws clause is generated. The + generated proxy method then specifies the checked exception by + containing java.io.IOException in the throws clause:
--%typemap(typemapname, throws="ExceptionClass1, ExceptionClass2") type { ... } +public class SimpleFile { + ... + public void open() throws java.io.IOException { ... } +}The attribute is necessary for supporting Java checked exceptions - and can be added to just about any typemap. The list of typemaps - include all the C/C++ (JNI) typemaps in the " -Typemaps" chapter and the Java specific typemaps listed in -the previous section, barring the "jni", "jtype" and "jstype" - typemaps as they could never contain code to throw an exception.
-The throws clause is generated for the proxy method as well as the - JNI method in the JNI intermediary class. If a method uses more than - one typemap and each of those typemaps have classes specified in the - throws clause, the union of the exception classes is added to the - throws clause ensuring there are no duplicate classes. See the -NaN exception example for further usage.
-The "jtype" typemap has the optional 'nopgcpp' attribute which can - be used to suppress the generation of the -premature garbage collection prevention parameter.
-The "javain" typemap has the optional 'pre', 'post' and 'pgcppname' - attributes. These are used for generating code before and after the JNI - call in the proxy class or module class. The 'pre' attribute contains - code that is generated before the JNI call and the 'post' attribute - contains code generated after the JNI call. The 'pgcppname' attribute - is used to change the premature garbage - collection prevention parameter name passed to the JNI function. - This is sometimes needed when the 'pre' typemap creates a temporary - variable which is then passed to the JNI function.
-Note that when the - 'pre' or 'post' attributes are specified and the associated type is - used in a constructor, a constructor helper function is generated. This - is necessary as the Java proxy constructor wrapper makes a call to a - support constructor using a this call. In Java the this - call must be the first statement in the constructor body. The - constructor body thus calls the helper function and the helper function - instead makes the JNI call, ensuring the 'pre' code is called before - the JNI call is made. There is a Date - marshalling example showing 'pre', 'post' and 'pgcppname' - attributes in action.
-24.9.7 Java special variables
-The standard SWIG special variables are available for use within - typemaps as described in the Typemaps documentation -, for example $1, $input,$result etc.
-The Java module uses a few additional special variables:
-$javaclassname -
-
This special variable works like the other -special variables and $javaclassname is similar to -$1_type. It expands to the class name for use in Java given a - pointer. SWIG wraps unions, structs and classes using pointers and in - this case it expands to the Java proxy class name. For example, -$javaclassname is replaced by the proxy classname Foo when - wrapping a Foo * and $&javaclassname expands to the - proxy classname when wrapping the C/C++ type Foo and -$*javaclassname expands to the proxy classname when wrapping -Foo *&. If the type does not have an associated proxy class, it - expands to the type wrapper class name, for example, -SWIGTYPE_p_unsigned_short is generated when wrapping unsigned - short *.$javaclazzname -
-
This special variable works like $javaclassname, but - expands the fully qualified C++ class into the package name, if used by - the nspace feature, and the proxy class - name, mangled for use as a function name. For example, -Namespace1::Namespace2::Klass is expanded into -Namespace1_Namespace2_Klass_. This special variable is usually used - for making calls to a function in the intermediary JNI class, as they - are mangled with this prefix.$null -
+
Used in input typemaps to return early from JNI functions that have - either void or a non-void return type. Example:Lastly, if you don't want to map your C++ exception into one of the + standard Java exceptions, the C++ class can be wrapped and turned into + a custom Java exception class. If we go back to our example, the first + thing we must do is get SWIG to wrap FileException and ensure + that it derives from java.lang.Exception. Additionally, we + might want to override the java.lang.Exception.getMessage() + method. The typemaps to use then are as follows:
--%typemap(check) int * %{ - if (error) { - SWIG_JavaThrowException(jenv, SWIG_JavaIndexOutOfBoundsException, "Array element error"); - return $null; +%typemap(javabase) FileException "java.lang.Exception"; +%typemap(javacode) FileException %{ + public String getMessage() { + return what(); } %}If the typemap gets put into a function with void as return, $null - will expand to nothing:
+This generates:
--SWIGEXPORT void JNICALL Java_jnifn(...) { - if (error) { - SWIG_JavaThrowException(jenv, SWIG_JavaIndexOutOfBoundsException, "Array element error"); - return ; - } +public class FileException extends java.lang.Exception { ... + public String getMessage() { + return what(); + } + + public FileException(String msg) { ... } + + public String what() { + return exampleJNI.FileException_what(swigCPtr, this); + } }otherwise $null expands to NULL
+We could alternatively have used %rename to rename +what() into getMessage().
+25.10.3 NaN Exception - + exception handling for a particular type
+A Java exception can be thrown from any Java or JNI code. Therefore, + as most typemaps contain either Java or JNI code, just about any + typemap could throw an exception. The following example demonstrates + exception handling on a type by type basis by checking for 'Not a + number' (NaN) whenever a parameter of type float is wrapped.
+Consider the following C++ code:
--SWIGEXPORT jobject JNICALL Java_jnifn(...) { - if (error) { - SWIG_JavaThrowException(jenv, SWIG_JavaIndexOutOfBoundsException, "Array element error"); - return NULL; - } - ... -} +bool calculate(float first, float second);$javainput, $jnicall and $owner -
-
The $javainput special variable is used in "javain" typemaps and - $jnicall and $owner are used in "javaout" typemaps. $jnicall is - analogous to $action in %exception. It is replaced by the call to the - native method in the intermediary JNI class. $owner is replaced by - either true if %newobject has been used, otherwise false -. $javainput is analogous to the $input special variable. It is replaced - by the parameter name.Here is an example:
+To validate every float being passed to C++, we could + precede the code being wrapped by the following typemap which throws a + runtime exception whenever the float is 'Not a Number':
--%typemap(javain) Class "Class.getCPtr($javainput)" -%typemap(javain) unsigned short "$javainput" -%typemap(javaout) Class * { - return new Class($jnicall, $owner); +%module example +%typemap(javain) float "$module.CheckForNaN($javainput)" +%pragma(java) modulecode=%{ + /** Simply returns the input value unless it is not a number, + whereupon an exception is thrown. */ + static protected float CheckForNaN(float num) { + if (Float.isNaN(num)) + throw new RuntimeException("Not a number"); + return num; } - -%inline %{ - class Class {...}; - Class * bar(Class cls, unsigned short ush) { return new Class(); }; %}The generated proxy code is then:
+Note that the CheckForNaN support method has been added to + the module class using the modulecode pragma. The following + shows the generated code of interest:
--public static Class bar(Class cls, int ush) { - return new Class(exampleJNI.bar(Class.getCPtr(cls), cls, ush), false); +public class example { + ... + + /** Simply returns the input value unless it is not a number, + whereupon an exception is thrown. */ + static protected float CheckForNaN(float num) { + if (Float.isNaN(num)) + throw new RuntimeException("Not a number"); + return num; + } + + public static boolean calculate(float first, float second) { + return exampleJNI.calculate(example.CheckForNaN(first), example.CheckForNaN(second)); + } }Here $javainput has been replaced by cls and ush. - $jnicall has been replaced by the native method call, -exampleJNI.bar(...) and $owner has been replaced by false. - If %newobject is used by adding the following at the beginning of our - example:
+Note that the "javain" typemap is used for every occurrence of a +float being used as an input. Of course, we could have targeted the + typemap at a particular parameter by using float first, say, + instead of just float.
+The exception checking could alternatively have been placed into the + 'pre' attribute that the "javain" typemap supports. The "javain" + typemap above could be replaced with the following:
--%newobject bar(Class cls, unsigned short ush); +%typemap(javain, pre=" $module.CheckForNaN($javainput);") float "$javainput"The generated code constructs the return type using true - indicating the proxy class Class is responsible for destroying - the C++ memory allocated for it in bar:
+which would modify the calculate function to instead be + generated as:
--public static Class bar(Class cls, int ush) { - return new Class(exampleJNI.bar(Class.getCPtr(cls), cls, ush), true); +public class example { + ... + public static boolean calculate(float first, float second) { + example.CheckForNaN(first); + example.CheckForNaN(second); + { + return exampleJNI.calculate(first, second); + } + } }$static -
-
This special variable expands to either static or nothing - depending on whether the class is an inner Java class or not. It is - used in the "javaclassmodifiers" typemap so that global classes can be - wrapped as Java proxy classes and nested C++ classes/enums can be - wrapped with the Java equivalent, that is, static inner proxy classes.$jniinput, $javacall and $packagepath -
-
These special variables are used in the directors typemaps. See -Director specific typemaps for details.$module -
-
This special variable expands to the module name, as specified by -%module or the -module commandline option.$imclassname -
-
This special variable expands to the intermediary class name. - Usually this is the same as '$moduleJNI', unless the jniclassname - attribute is specified in the %module - directive.24.9.8 Typemaps for both C - and C++ compilation
-JNI calls must be written differently depending on whether the code - is being compiled as C or C++. For example C compilation requires the - pointer to a function pointer struct member syntax like
+See the Date marshalling example + for an example using further "javain" typemap attributes.
+If we decide that what we actually want is a checked exception + instead of a runtime exception, we can change this easily enough. The + proxy method that uses float as an input, must then add the + exception class to the throws clause. SWIG can handle this as it + supports the 'throws' typemap + attribute for specifying classes for the throws clause. Thus we can + modify the pragma and the typemap for the throws clause:
--const jclass clazz = (*jenv)->FindClass(jenv, "java/lang/String"); +%typemap(javain, throws="java.lang.Exception") float "$module.CheckForNaN($javainput)" +%pragma(java) modulecode=%{ + /** Simply returns the input value unless it is not a number, + whereupon an exception is thrown. */ + static protected float CheckForNaN(float num) throws java.lang.Exception { + if (Float.isNaN(num)) + throw new RuntimeException("Not a number"); + return num; + } +%}whereas C++ code compilation of the same function call is a member - function call using a class pointer like
+The calculate method now has a throws clause and even + though the typemap is used twice for both float first and +float second, the throws clause contains a single instance of +java.lang.Exception:
--const jclass clazz = jenv->FindClass("java/lang/String"); +public class example { + ... + + /** Simply returns the input value unless it is not a number, + whereupon an exception is thrown. */ + static protected float CheckForNaN(float num) throws java.lang.Exception { + if (Float.isNaN(num)) + throw new RuntimeException("Not a number"); + return num; + } + + public static boolean calculate(float first, float second) throws java.lang.Exception { + return exampleJNI.calculate(example.CheckForNaN(first), example.CheckForNaN(second)); + } +}To enable typemaps to be used for either C or C++ compilation, a set - of JCALLx macros have been defined in Lib/java/javahead.swg, where x is - the number of arguments in the C++ version of the JNI call. The above - JNI calls would be written in a typemap like this
+If we were a martyr to the JNI cause, we could replace the succinct + code within the "javain" typemap with a few pages of JNI code. If we + had, we would have put it in the "in" typemap which, like all JNI and + Java typemaps, also supports the 'throws' attribute.
+25.10.4 Converting Java + String arrays to char **
+A common problem in many C programs is the processing of command + line arguments, which are usually passed in an array of NULL terminated + strings. The following SWIG interface file allows a Java String array + to be used as a char ** object.
--const jclass clazz = JCALL1(FindClass, jenv, "java/lang/String"); +%module example + +/* This tells SWIG to treat char ** as a special case when used as a parameter + in a function call */ +%typemap(in) char ** (jint size) { + int i = 0; + size = (*jenv)->GetArrayLength(jenv, $input); + $1 = (char **) malloc((size+1)*sizeof(char *)); + /* make a copy of each string */ + for (i = 0; i<size; i++) { + jstring j_string = (jstring)(*jenv)->GetObjectArrayElement(jenv, $input, i); + const char * c_string = (*jenv)->GetStringUTFChars(jenv, j_string, 0); + $1[i] = malloc((strlen(c_string)+1)*sizeof(char)); + strcpy($1[i], c_string); + (*jenv)->ReleaseStringUTFChars(jenv, j_string, c_string); + (*jenv)->DeleteLocalRef(jenv, j_string); + } + $1[i] = 0; +} + +/* This cleans up the memory we malloc'd before the function call */ +%typemap(freearg) char ** { + int i; + for (i=0; i<size$argnum-1; i++) + free($1[i]); + free($1); +} + +/* This allows a C function to return a char ** as a Java String array */ +%typemap(out) char ** { + int i; + int len=0; + jstring temp_string; + const jclass clazz = (*jenv)->FindClass(jenv, "java/lang/String"); + + while ($1[len]) len++; + jresult = (*jenv)->NewObjectArray(jenv, len, clazz, NULL); + /* exception checking omitted */ + + for (i=0; i<len; i++) { + temp_string = (*jenv)->NewStringUTF(jenv, *result++); + (*jenv)->SetObjectArrayElement(jenv, jresult, i, temp_string); + (*jenv)->DeleteLocalRef(jenv, temp_string); + } +} + +/* These 3 typemaps tell SWIG what JNI and Java types to use */ +%typemap(jni) char ** "jobjectArray" +%typemap(jtype) char ** "String[]" +%typemap(jstype) char ** "String[]" + +/* These 2 typemaps handle the conversion of the jtype to jstype typemap type + and vice versa */ +%typemap(javain) char ** "$javainput" +%typemap(javaout) char ** { + return $jnicall; + } + +/* Now a few test functions */ +%inline %{ + +int print_args(char **argv) { + int i = 0; + while (argv[i]) { + printf("argv[%d] = %s\n", i, argv[i]); + i++; + } + return i; +} + +char **get_args() { + static char *values[] = { "Dave", "Mike", "Susan", "John", "Michelle", 0}; + return &values[0]; +} + +%}Note that the SWIG preprocessor expands these into the appropriate C - or C++ JNI calling convention. The C calling convention is emitted by - default and the C++ calling convention is emitted when using the -c++ - SWIG commandline option. If you do not intend your code to be targeting - both C and C++ then your typemaps can use the appropriate JNI calling - convention and need not use the JCALLx macros.
-24.9.9 Java code typemaps
-Most of SWIG's typemaps are used for the generation of C/C++ code. - The typemaps in this section are used solely for the generation of Java - code. Elements of proxy classes and type wrapper classes come from the - following typemaps (the defaults).
-%typemap(javabase)
-base (extends) for Java class: empty default --
Note that this typemap accepts a replace attribute as an - optional flag. When set to "1", it will replace/override any C++ base - classes that might have been parsed. If this flag is not specified and - there are C++ base classes, then a multiple inheritance warning is - issued and the code in the typemap is ignored. The typemap also accepts - a notderived attribute as an optional flag. When set to "1", - it will not apply to classes that are derived from a C++ base. When - used with the SWIGTYPE type, it is useful for giving a common base for - all proxy classes, that is, providing a base class that sits in between - all proxy classes and the Java base class Object for example: -%typemap(javabase, notderived="1") SWIGTYPE "CommonBase".%typemap(javabody)
-the essential support body for proxy classes (proxy - base classes only), typewrapper classes and enum classes. Default - contains extra constructors, memory ownership control member variables - (swigCMemOwn, swigCPtr), the getCPtr method - etc.-%typemap(javabody_derived)
-the essential support body for proxy classes - (derived classes only). Same as "javabody" typemap, but only used for - proxy derived classes.-%typemap(javaclassmodifiers)
-class modifiers for the Java class: default is - "public class"-%typemap(javacode)
-Java code is copied verbatim to the Java class: - empty default-%typemap(javadestruct, methodname="delete", - methodmodifiers="public synchronized") -
-destructor wrapper - the delete() method - (proxy classes only), used for all proxy classes except those which - have a base class : default calls C++ destructor (or frees C memory) - and resets swigCPtr and swigCMemOwn flags --
-
Note that the delete() method name is configurable and is - specified by the methodname attribute. The method modifiers - are also configurable via the methodmodifiers attribute.%typemap(javadestruct_derived, methodname="delete", - methodmodifiers="public synchronized")
-destructor wrapper - the delete() method - (proxy classes only), same as "javadestruct" but only used for derived - proxy classes : default calls C++ destructor (or frees C memory) and - resets swigCPtr and swigCMemOwn flags --
-
Note that the delete() method name is configurable and is - specified by the methodname attribute. The method modifiers - are also configurable via the methodmodifiers attribute.%typemap(javaimports)
-import statements for Java class: empty default-%typemap(javainterfaces)
-interfaces (implements) for Java class: empty - default-%typemap(javafinalize)
-the finalize() method (proxy classes - only): default calls the delete() method --Note that the default javafinalize typemap must contain the full - implementation of the finalize method. Any customization to this - typemap must still declare a java finalize method with the correct - signature. Note also that the name of the generated "delete" method may - be affected by javadestruct and javadestruct_derived - typemaps. Below shows an example modifying the finalizer, assuming the -delete method has been renamed to swig_delete.
+Note that the 'C' JNI calling convention is used. Checking for any + thrown exceptions after JNI function calls has been omitted. When this + module is compiled, our wrapped C functions can be used by the + following Java program:
-%typemap(javafinalize) SWIGTYPE %{ - protected void finalize() { - swig_delete(); // renamed to prevent conflict with existing delete method - } -]% +// File runme.java + +public class runme { + + static { + try { + System.loadLibrary("example"); + } catch (UnsatisfiedLinkError e) { + System.err.println("Native code library failed to load. " + e); + System.exit(1); + } + } + + public static void main(String argv[]) { + String animals[] = {"Cat","Dog","Cow","Goat"}; + example.print_args(animals); + String args[] = example.get_args(); + for (int i=0; i<args.length; i++) + System.out.println(i + ":" + args[i]); + } +}-Compatibility Note: In SWIG-1.3.21 and earlier releases, - typemaps called "javagetcptr" and "javaptrconstructormodifiers" were - available. These are deprecated and the "javabody" typemap can be used - instead.
-In summary the contents of the typemaps make up a proxy class like - this:
+ +When compiled and run we get:
+-[ javaimports typemap ] -[ javaclassmodifiers typemap ] javaclassname extends [ javabase typemap ] - implements [ javainterfaces typemap ] { -[ javabody or javabody_derived typemap ] -[ javafinalize typemap ] -public synchronized void delete() [ javadestruct OR javadestruct_derived typemap ] -[ javacode typemap ] -... proxy functions ... +$ java runme +argv[0] = Cat +argv[1] = Dog +argv[2] = Cow +argv[3] = Goat +0:Dave +1:Mike +2:Susan +3:John +4:Michelle ++In the example, a few different typemaps are used. The "in" typemap + is used to receive an input argument and convert it to a C array. Since + dynamic memory allocation is used to allocate memory for the array, the + "freearg" typemap is used to later release this memory after the + execution of the C function. The "out" typemap is used for function + return values. Lastly the "jni", "jtype" and "jstype" typemaps are also + required to specify what Java types to use.
+25.10.5 Expanding a Java object + to multiple arguments
+Suppose that you had a collection of C functions with arguments such + as the following:
++++int foo(int argc, char **argv); ++In the previous example, a typemap was written to pass a Java String + array as the char **argv. This allows the function to be used + from Java as follows:
++++example.foo(4, new String[]{"red", "green", "blue", "white"}); ++Although this works, it's a little awkward to specify the argument + count. To fix this, a multi-argument typemap can be defined. This is + not very difficult--you only have to make slight modifications to the + previous example's typemaps:
++-+%typemap(in) (int argc, char **argv) { + int i = 0; + $1 = (*jenv)->GetArrayLength(jenv, $input); + $2 = (char **) malloc(($1+1)*sizeof(char *)); + /* make a copy of each string */ + for (i = 0; i<$1; i++) { + jstring j_string = (jstring)(*jenv)->GetObjectArrayElement(jenv, $input, i); + const char * c_string = (*jenv)->GetStringUTFChars(jenv, j_string, 0); + $2[i] = malloc((strlen(c_string)+1)*sizeof(char)); + strcpy($2[i], c_string); + (*jenv)->ReleaseStringUTFChars(jenv, j_string, c_string); + (*jenv)->DeleteLocalRef(jenv, j_string); + } + $2[i] = 0; +} + +%typemap(freearg) (int argc, char **argv) { + int i; + for (i=0; i<$1-1; i++) + free($2[i]); + free($2); } + +%typemap(jni) (int argc, char **argv) "jobjectArray" +%typemap(jtype) (int argc, char **argv) "String[]" +%typemap(jstype) (int argc, char **argv) "String[]" + +%typemap(javain) (int argc, char **argv) "$javainput"Note the delete() methodname and method modifiers - are configurable, see "javadestruct" and "javadestruct_derived" - typemaps above.
-The type wrapper class is similar in construction:
+When writing a multiple-argument typemap, each of the types is + referenced by a variable such as $1 or $2. The + typemap code simply fills in the appropriate values from the supplied + Java parameter.
+With the above typemap in place, you will find it no longer + necessary to supply the argument count. This is automatically set by + the typemap code. For example:
--[ javaimports typemap ] -[ javaclassmodifiers typemap ] javaclassname extends [ javabase typemap ] - implements [ javainterfaces typemap ] { -[ javabody typemap ] -[ javacode typemap ] -} +example.foo(new String[]{"red", "green", "blue", "white"});The enum class is also similar in construction:
+25.10.6 Using + typemaps to return arguments
+A common problem in some C programs is that values may be returned + in function parameters rather than in the return value of a function. + The typemaps.i file defines INPUT, OUTPUT and INOUT typemaps + which can be used to solve some instances of this problem. This library + file uses an array as a means of moving data to and from Java when + wrapping a C function that takes non const pointers or non const + references as parameters.
+Now we are going to outline an alternative approach to using arrays + for C pointers. The INOUT typemap uses a double[] array for + receiving and returning the double* parameters. In this + approach we are able to use a Java class myDouble instead of +double[] arrays where the C pointer double* is required.
+Here is our example function:
--[ javaimports typemap ] -[ javaclassmodifiers typemap ] javaclassname extends [ javabase typemap ] - implements [ javainterfaces typemap ] { -... Enum values ... -[ javabody typemap ] -[ javacode typemap ] -} +/* Returns a status value and two values in out1 and out2 */ +int spam(double a, double b, double *out1, double *out2);The "javaimports" typemap is ignored if the enum class is wrapped by - an inner Java class, that is when wrapping an enum declared within a - C++ class.
-The defaults can be overridden to tailor these classes. Here is an - example which will change the getCPtr method and constructor - from the default public access to protected access. If the classes in - one package are not using the classes in another package, then these - methods need not be public and removing access to these low level - implementation details, is a good thing. If you are invoking SWIG more - than once and generating the wrapped classes into different packages in - each invocation, then you cannot do this as you will then have - different packages.
+If we define a structure MyDouble containing a double + member variable and use some typemaps we can solve this problem. For + example we could put the following through SWIG:
--%typemap(javabody) SWIGTYPE %{ - private long swigCPtr; - protected boolean swigCMemOwn; +%module example - protected $javaclassname(long cPtr, boolean cMemoryOwn) { - swigCMemOwn = cMemoryOwn; - swigCPtr = cPtr; - } +/* Define a new structure to use instead of double * */ +%inline %{ +typedef struct { + double value; +} MyDouble; +%} - protected static long getCPtr($javaclassname obj) { - return (obj == null) ? 0 : obj.swigCPtr; - } + +%{ +/* Returns a status value and two values in out1 and out2 */ +int spam(double a, double b, double *out1, double *out2) { + int status = 1; + *out1 = a*10.0; + *out2 = b*100.0; + return status; +} %} + +/* +This typemap will make any double * function parameters with name OUTVALUE take an +argument of MyDouble instead of double *. This will +allow the calling function to read the double * value after returning from the function. +*/ +%typemap(in) double *OUTVALUE { + jclass clazz = jenv->FindClass("MyDouble"); + jfieldID fid = jenv->GetFieldID(clazz, "swigCPtr", "J"); + jlong cPtr = jenv->GetLongField($input, fid); + MyDouble *pMyDouble = NULL; + *(MyDouble **)&pMyDouble = *(MyDouble **)&cPtr; + $1 = &pMyDouble->value; +} + +%typemap(jtype) double *OUTVALUE "MyDouble" +%typemap(jstype) double *OUTVALUE "MyDouble" +%typemap(jni) double *OUTVALUE "jobject" + +%typemap(javain) double *OUTVALUE "$javainput" + +/* Now we apply the typemap to the named variables */ +%apply double *OUTVALUE { double *out1, double *out2 }; +int spam(double a, double b, double *out1, double *out2);The typemap code is the same that is in "java.swg", barring - the last two method modifiers. Note that SWIGTYPE will target - all proxy classes, but not the type wrapper classes. Also the above - typemap is only used for proxy classes that are potential base classes. - To target proxy classes that are derived from a wrapped class as well, - the "javabody_derived" typemap should also be overridden.
-For the typemap to be used in all type wrapper classes, all the - different types that type wrapper classes could be used for should be - targeted:
+Note that the C++ JNI calling convention has been used this time and + so must be compiled as C++ and the -c++ commandline must be passed to + SWIG. JNI error checking has been omitted for clarity.
+What the typemaps do are make the named double* function + parameters use our new MyDouble wrapper structure. The "in" + typemap takes this structure, gets the C++ pointer to it, takes the +double value member variable and passes it to the C++ spam + function. In Java, when the function returns, we use the SWIG created +getValue() function to get the output value. The following Java + program demonstrates this:
--%typemap(javabody) SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) %{ - private long swigCPtr; +// File: runme.java - protected $javaclassname(long cPtr, boolean bFutureUse) { - swigCPtr = cPtr; - } +public class runme { - protected $javaclassname() { - swigCPtr = 0; + static { + try { + System.loadLibrary("example"); + } catch (UnsatisfiedLinkError e) { + System.err.println("Native code library failed to load. " + e); + System.exit(1); + } } - protected static long getCPtr($javaclassname obj) { - return (obj == null) ? 0 : obj.swigCPtr; + public static void main(String argv[]) { + MyDouble out1 = new MyDouble(); + MyDouble out2 = new MyDouble(); + int ret = example.spam(1.2, 3.4, out1, out2); + System.out.println(ret + " " + out1.getValue() + " " + out2.getValue()); } -%} +}Again this is the same that is in "java.swg", barring the - method modifier for getCPtr.
-When using multiple modules or the -nspace feature it is common to invoke SWIG with a different --package command line option for each module. However, by default - the generated code may not compile if generated classes in one package - use generated classes in another package. The visibility of the -getCPtr() and pointer constructor generated from the javabody - typemaps needs changing. The default visibility is protected - but it needs to be public for access from a different package. - Just changing 'protected' to 'public' in the typemap achieves this. Two - macros are available in java.swg to make this easier and using - them is the preferred approach over simply copying the typemaps and - modifying as this is forward compatible with any changes in the -javabody typemap in future versions of SWIG. The macros are for the - proxy and typewrapper classes and can respectively be used to to make - the method and constructor public:
+When compiled and run we get:
-- SWIG_JAVABODY_PROXY(public, public, SWIGTYPE) - SWIG_JAVABODY_TYPEWRAPPER(public, public, public, SWIGTYPE) +$ java runme +1 12.0 340.024.9.10 Director specific - typemaps
-The Java directors feature requires the "javadirectorin", - "javadirectorout", "directorin" and the "directorout" typemaps in order - to work properly. The "javapackage" typemap is an optional typemap used - to identify the Java package path for individual SWIG generated proxy - classes used in director methods.
-%typemap(directorin)
---The "directorin" typemap is used for converting arguments in the C++ - director class to the appropriate JNI type before the upcall to Java. - This typemap also specifies the JNI field descriptor for the type in - the "descriptor" attribute. For example, integers are converted as - follows:
+25.10.7 Adding Java downcasts to + polymorphic return types
+SWIG support for polymorphism works in that the appropriate virtual + function is called. However, the default generated code does not allow + for downcasting. Let's examine this with the following code:
--%typemap(directorin,descriptor="I") int "$input = (jint) $1;" +%include "std_string.i" + +#include <iostream> +using namespace std; +class Vehicle { +public: + virtual void start() = 0; +... +}; + +class Ambulance : public Vehicle { + string vol; +public: + Ambulance(string volume) : vol(volume) {} + virtual void start() { + cout << "Ambulance started" << endl; + } + void sound_siren() { + cout << vol << " siren sounded!" << endl; + } +... +}; + +Vehicle *vehicle_factory() { + return new Ambulance("Very loud"); +}+
$input
is the SWIG name of the JNI temporary variable - passed to Java in the upcall. Thedescriptor="I"
will put - anI
into the JNI field descriptor that identifies the - Java method that will be called from C++. For more about JNI field - descriptors and their importance, refer to the -JNI documentation mentioned earlier. A typemap for C character - strings is:If we execute the following Java code:
--%typemap(directorin,descriptor="Ljava/lang/String;") char * - %{ $input = jenv->NewStringUTF($1); %} +Vehicle vehicle = example.vehicle_factory(); +vehicle.start(); + +Ambulance ambulance = (Ambulance)vehicle; +ambulance.sound_siren();User-defined types have the default "descriptor" attribute "
--L$packagepath/$javaclassname;
" where$packagepath
is - the package name passed from the SWIG command line and-$javaclassname
is the Java proxy class' name. If the -package - commandline option is not used to specify the package, then - '$packagepath/' will be removed from the resulting output JNI field - descriptor. Do not forget the terminating ';' for JNI field - descriptors starting with 'L'. If the ';' is left out, Java will - generate a "method not found" runtime error.%typemap(directorout)
---The "directorout" typemap is used for converting the JNI return type - in the C++ director class to the appropriate C++ type after the upcall - to Java. For example, integers are converted as follows:
+We get:
--%typemap(directorout) int %{ $result = (int)$input; %} +Ambulance started +java.lang.ClassCastException + at runme.main(runme.java:16)+
$input
is the SWIG name of the JNI temporary variable - returned from Java after the upcall.$result
is the - resulting output. A typemap for C character strings is:Even though we know from examination of the C++ code that +vehicle_factory returns an object of type Ambulance, we + are not able to use this knowledge to perform the downcast in Java. + This occurs because the runtime type information is not completely + passed from C++ to Java when returning the type from +vehicle_factory(). Usually this is not a problem as virtual + functions do work by default, such as in the case of start(). + There are a few solutions to getting downcasts to work.
+The first is not to use a Java cast but a call to C++ to make the + cast. Add this to your code:
-%typemap(directorout) char * { - $1 = 0; - if ($input) { - $result = (char *)jenv->GetStringUTFChars($input, 0); - if (!$1) return $null; - } +%exception Ambulance::dynamic_cast(Vehicle *vehicle) { + $action + if (!result) { + jclass excep = jenv->FindClass("java/lang/ClassCastException"); + if (excep) { + jenv->ThrowNew(excep, "dynamic_cast exception"); + } + } } +%extend Ambulance { + static Ambulance *dynamic_cast(Vehicle *vehicle) { + return dynamic_cast<Ambulance *>(vehicle); + } +};-%typemap(javadirectorin)
--+Conversion from jtype to jstype for director methods. These are Java - code typemaps which transform the type used in the Java intermediary - JNI class (as specified in the "jtype" typemap) to the Java type used - in the Java module class, proxy classes and type wrapper classes (as - specified in the "jstype" typemap). This typemap provides the - conversion for the parameters in the director methods when calling up - from C++ to Java.
-For primitive types, this typemap is usually specified as:
+It would then be used from Java like this
--%typemap(javadirectorin) int "$jniinput" +Ambulance ambulance = Ambulance.dynamic_cast(vehicle); +ambulance.sound_siren();The
- -$jniinput
special variable is analogous to-$javainput
special variable. It is replaced by the input - parameter name.%typemap(javadirectorout)
---Conversion from jstype to jtype for director methods. These are Java - code typemaps which transform the type used in the Java module class, - proxy classes and type wrapper classes (as specified in the "jstype" - typemap) to the type used in the Java intermediary JNI class (as - specified in the "jtype" typemap). This typemap provides the conversion - for the return type in the director methods when returning from the C++ - to Java upcall.
-For primitive types, this typemap is usually specified as:
+Should vehicle not be of type ambulance then a + Java ClassCastException is thrown. The next solution is a + purer solution in that Java downcasts can be performed on the types. + Add the following before the definition of vehicle_factory:
--%typemap(javadirectorout) int "$javacall" +%typemap(out) Vehicle * { + Ambulance *downcast = dynamic_cast<Ambulance *>($1); + *(Ambulance **)&$result = downcast; +} + +%typemap(javaout) Vehicle * { + return new Ambulance($jnicall, $owner); + }The
-$javacall
special variable is analogous to the-$jnicall
special variable. It is replaced by the call to the - target Java method. The target method is the method in the Java proxy - class which overrides the virtual C++ method in the C++ base class.%typemap(javapackage)
---The "javapackage" typemap is optional; it serves to identify a - class's Java package. This typemap should be used in conjunction with - classes that are defined outside of the current SWIG interface file. - The typemap is only used if the type is used in a director method, that - is, in a virtual method in a director class. For example:
+Here we are using our knowledge that vehicle_factory always + returns type Ambulance so that the Java proxy is created as a + type Ambulance. If vehicle_factory can manufacture + any type of Vehicle and we want to be able to downcast using + Java casts for any of these types, then a different approach is needed. + Consider expanding our example with a new Vehicle type and a more + flexible factory function:
--// class Foo is handled in a different interface file: -%import "Foo.i" - -%feature("director") Example; - -%inline { - class Bar { }; - - class Example { - public: - virtual ~Example(); - virtual void ping(Foo *arg1, Bar *arg2); - }; +class FireEngine : public Vehicle { +public: + FireEngine() {} + virtual void start() { + cout << "FireEngine started" << endl; + } + void roll_out_hose() { + cout << "Hose rolled out" << endl; + } + ... +}; +Vehicle *vehicle_factory(int vehicle_number) { + if (vehicle_number == 0) + return new Ambulance("Very loud"); + else + return new FireEngine(); }Assume that the Foo class is part of the Java package - com.wombat.foo but the above interface file is part of the Java - package com.wombat.example. Without the "javapackage" typemap, - SWIG will assume that the Foo class belongs to com.wombat.example - class. The corrected interface file looks like:
+To be able to downcast with this sort of Java code:
--// class Foo is handled in a different interface file: -%import "Foo.i" -%typemap("javapackage") Foo, Foo *, Foo & "com.wombat.foo"; -%feature("director") Example; - -%inline { - class Bar { }; - - class Example { - public: - virtual ~Example(); - virtual void ping(Foo *arg1, Bar *arg2); - }; -} +FireEngine fireengine = (FireEngine)example.vehicle_factory(1); +fireengine.roll_out_hose(); +Ambulance ambulance = (Ambulance)example.vehicle_factory(0); +ambulance.sound_siren();SWIG looks up the package based on the actual type (plain - Foo, Foo pointer and Foo reference), so it is important to associate - all three types with the desired package. Practically speaking, you - should create a separate SWIG interface file, which is %import-ed into - each SWIG interface file, when you have multiple Java packages. Note - the helper macros below,
+OTHER_PACKAGE_SPEC
and-ANOTHER_PACKAGE_SPEC
, which reduce the amount of extra typing. "-TYPE...
" is useful when passing templated types to the macro, - since multiargument template types appear to the SWIG preprocessor as - multiple macro arguments.the following typemaps targeted at the vehicle_factory + function will achieve this. Note that in this case, the Java class is + constructed using JNI code rather than passing a pointer across the JNI + boundary in a Java long for construction in Java code.
--%typemap("javapackage") SWIGTYPE, SWIGTYPE *, SWIGTYPE & - "package.for.most.classes"; - -%define OTHER_PACKAGE_SPEC(TYPE...) -%typemap("javapackage") TYPE, TYPE *, TYPE & "package.for.other.classes"; -%enddef +%typemap(jni) Vehicle *vehicle_factory "jobject" +%typemap(jtype) Vehicle *vehicle_factory "Vehicle" +%typemap(jstype) Vehicle *vehicle_factory "Vehicle" +%typemap(javaout) Vehicle *vehicle_factory { + return $jnicall; + } -%define ANOTHER_PACKAGE_SPEC(TYPE...) -%typemap("javapackage") TYPE, TYPE *, TYPE & "package.for.another.set"; -%enddef +%typemap(out) Vehicle *vehicle_factory { + Ambulance *ambulance = dynamic_cast<Ambulance *>($1); + FireEngine *fireengine = dynamic_cast<FireEngine *>($1); + if (ambulance) { + // call the Ambulance(long cPtr, boolean cMemoryOwn) constructor + jclass clazz = jenv->FindClass("Ambulance"); + if (clazz) { + jmethodID mid = jenv->GetMethodID(clazz, "<init>", "(JZ)V"); + if (mid) { + jlong cptr = 0; + *(Ambulance **)&cptr = ambulance; + $result = jenv->NewObject(clazz, mid, cptr, false); + } + } + } else if (fireengine) { + // call the FireEngine(long cPtr, boolean cMemoryOwn) constructor + jclass clazz = jenv->FindClass("FireEngine"); + if (clazz) { + jmethodID mid = jenv->GetMethodID(clazz, "<init>", "(JZ)V"); + if (mid) { + jlong cptr = 0; + *(FireEngine **)&cptr = fireengine; + $result = jenv->NewObject(clazz, mid, cptr, false); + } + } + } + else { + cout << "Unexpected type " << endl; + } -OTHER_PACKAGE_SPEC(Package_2_class_one) -ANOTHER_PACKAGE_SPEC(Package_3_class_two) -/* etc */ + if (!$result) + cout << "Failed to create new java object" << endl; +}The basic strategy here is to provide a default package typemap for - the majority of the classes, only providing "javapackage" typemaps for - the exceptions.
-24.10 Typemap Examples
-This section includes a few examples of typemaps. For more examples, - you might look at the files "java.swg" and "typemaps.i -" in the SWIG library.
-24.10.1 Simpler Java enums - for enums without initializers
-The default Proper Java enums - approach to wrapping enums is somewhat verbose. This is to handle all - possible C/C++ enums, in particular enums with initializers. The - generated code can be simplified if the enum being wrapped does not - have any initializers.
-The following shows how to remove the support methods that are - generated by default and instead use the methods in the Java enum base - class java.lang.Enum and java.lang.Class for - marshalling enums between C/C++ and Java. The type used for the - typemaps below is enum SWIGTYPE which is the default type used - for all enums. The "enums.swg" file should be examined in order to see - the original overridden versions of the typemaps.
---%include "enums.swg" - -%typemap(javain) enum SWIGTYPE "$javainput.ordinal()" -%typemap(javaout) enum SWIGTYPE { - return $javaclassname.class.getEnumConstants()[$jnicall]; +Better error handling would need to be added into this code. There + are other solutions to this problem, but this last example demonstrates + some more involved JNI code. SWIG usually generates code which + constructs the proxy classes using Java code as it is easier to handle + error conditions and is faster. Note that the JNI code above uses a + number of string lookups to call a constructor, whereas this would not + occur using byte compiled Java code.
+25.10.8 Adding an equals method + to the Java classes
+When a pointer is returned from a JNI function, it is wrapped using + a new Java proxy class or type wrapper class. Even when the pointers + are the same, it will not be possible to know that the two Java classes + containing those pointers are actually the same object. It is common in + Java to use the equals() method to check whether two objects + are equivalent. The equals() method is usually accompanied by + a hashCode() method in order to fulfill the requirement that + the hash code is equal for equal objects. Pure Java code methods like + these can be easily added:
++-+%typemap(javacode) SWIGTYPE %{ + public boolean equals(Object obj) { + boolean equal = false; + if (obj instanceof $javaclassname) + equal = ((($javaclassname)obj).swigCPtr == this.swigCPtr); + return equal; + } + public int hashCode() { + return (int)getPointer(); } -%typemap(javabody) enum SWIGTYPE "" - -%inline %{ - enum HairType { blonde, ginger, brunette }; - void setHair(HairType h); - HairType getHair(); %} + +class Foo { }; +Foo* returnFoo(Foo *foo) { return foo; }SWIG will generate the following Java enum, which is somewhat - simpler than the default:
+The following would display false without the javacode + typemap above. With the typemap defining the equals method the + result is true.
--public enum HairType { - blonde, - ginger, - brunette; -} +Foo foo1 = new Foo(); +Foo foo2 = example.returnFoo(foo1); +System.out.println("foo1? " + foo1.equals(foo2));and the two Java proxy methods will be:
+25.10.9 Void pointers and a common Java + base class
+One might wonder why the common code that SWIG emits for the proxy + and type wrapper classes is not pushed into a base class. The reason is + that although swigCPtr could be put into a common base class + for all classes wrapping C structures, it would not work for C++ + classes involved in an inheritance chain. Each class derived from a + base needs a separate swigCPtr because C++ compilers sometimes + use a different pointer value when casting a derived class to a base. + Additionally as Java only supports single inheritance, it would not be + possible to derive wrapped classes from your own pure Java classes if + the base class has been 'used up' by SWIG. However, you may want to + move some of the common code into a base class. Here is an example + which uses a common base class for all proxy classes and type wrapper + classes:
--public static void setHair(HairType h) { - exampleJNI.setHair(h.ordinal()); -} +%typemap(javabase) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], + SWIGTYPE (CLASS::*) "SWIG" -public static HairType getHair() { - return HairType.class.getEnumConstants()[exampleJNI.getHair()]; -} +%typemap(javacode) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], + SWIGTYPE (CLASS::*) %{ + protected long getPointer() { + return swigCPtr; + } +%}For marshalling Java enums to C/C++ enums, the ordinal - method is used to convert the Java enum into an integer value for - passing to the JNI layer, see the "javain" typemap. For marshalling - C/C++ enums to Java enums, the C/C++ enum value is cast to an integer - in the C/C++ typemaps (not shown). This integer value is then used to - index into the array of enum constants that the Java language provides. - See the getEnumConstants method in the "javaout" typemap.
-These typemaps can often be used as the default for wrapping enums - as in many cases there won't be any enum initializers. In fact a good - strategy is to always use these typemaps and to specifically handle - enums with initializers using %apply. This would be done by using the - original versions of these typemaps in "enums.swg" under another - typemap name for applying using %apply.
-24.10.2 Handling C++ exception - specifications as Java exceptions
-This example demonstrates various ways in which C++ exceptions can - be tailored and converted into Java exceptions. Let's consider a simple - file class SimpleFile and an exception class FileException - which it may throw on error:
+Define new base class called SWIG:
--%include "std_string.i" // for std::string typemaps -#include <string> +public abstract class SWIG { + protected abstract long getPointer(); -class FileException { - std::string message; -public: - FileException(const std::string& msg) : message(msg) {} - std::string what() { - return message; + public boolean equals(Object obj) { + boolean equal = false; + if (obj instanceof SWIG) + equal = (((SWIG)obj).getPointer() == this.getPointer()); + return equal; } -}; - -class SimpleFile { - std::string filename; -public: - SimpleFile(const std::string& filename) : filename(filename) {} - void open() throw(FileException) { - ... + + SWIGTYPE_p_void getVoidPointer() { + return new SWIGTYPE_p_void(getPointer(), false); } -}; +}As the open method has a C++ exception specification, SWIG - will parse this and know that the method can throw an exception. The -"throws" typemap is then used when SWIG encounters an exception - specification. The default generic "throws" typemap looks like this:
+This example contains some useful functionality which you may want + in your code.
++
+- It has an equals() method. Unlike the previous example, + the method code isn't replicated in all classes.
+- It also has a function which effectively implements a cast from the + type of the proxy/type wrapper class to a void pointer. This is + necessary for passing a proxy class or a type wrapper class to a + function that takes a void pointer.
+25.10.10 Struct pointer to + pointer
+Pointers to pointers are often used as output parameters in C + factory type functions. These are a bit more tricky to handle. Consider + the following situation where a Butler can be hired and fired:
--%typemap(throws) SWIGTYPE, SWIGTYPE &, SWIGTYPE *, SWIGTYPE [ANY] %{ - SWIG_JavaThrowException(jenv, SWIG_JavaRuntimeException, - "C++ $1_type exception thrown"); - return $null; -%} +typedef struct { + int hoursAvailable; + char *greeting; +} Butler; + +// Note: HireButler will allocate the memory +// The caller must free the memory by calling FireButler()!! +extern int HireButler(Butler **ppButler); +extern void FireButler(Butler *pButler);Basically SWIG will generate a C++ try catch block and the body of - the "throws" typemap constitutes the catch block. The above typemap - calls a SWIG supplied method which throws a -java.lang.RuntimeException. This exception class is a runtime - exception and therefore not a checked exception. If, however, we wanted - to throw a checked exception, say java.io.IOException, then we - could use the following typemap:
+C code implementation:
--%typemap(throws, throws="java.io.IOException") FileException { - jclass excep = jenv->FindClass("java/io/IOException"); - if (excep) - jenv->ThrowNew(excep, $1.what().c_str()); - return $null; +int HireButler(Butler **ppButler) { + Butler *pButler = (Butler *)malloc(sizeof(Butler)); + pButler->hoursAvailable = 24; + pButler->greeting = (char *)malloc(32); + strcpy(pButler->greeting, "At your service Sir"); + *ppButler = pButler; + return 1; +} +void FireButler(Butler *pButler) { + free(pButler->greeting); + free(pButler); }Note that this typemap uses the 'throws' -typemap attribute to ensure a throws clause is generated. The - generated proxy method then specifies the checked exception by - containing java.io.IOException in the throws clause:
+Let's take two approaches to wrapping this code. The first is to + provide a functional interface, much like the original C interface. The + following Java code shows how we intend the code to be used:
--public class SimpleFile { - ... - public void open() throws java.io.IOException { ... } -} + Butler jeeves = new Butler(); + example.HireButler(jeeves); + System.out.println("Greeting: " + jeeves.getGreeting()); + System.out.println("Availability: " + jeeves.getHoursAvailable() + " hours per day"); + example.FireButler(jeeves);Lastly, if you don't want to map your C++ exception into one of the - standard Java exceptions, the C++ class can be wrapped and turned into - a custom Java exception class. If we go back to our example, the first - thing we must do is get SWIG to wrap FileException and ensure - that it derives from java.lang.Exception. Additionally, we - might want to override the java.lang.Exception.getMessage() - method. The typemaps to use then are as follows:
-+Resulting in the following output when run:
+--%typemap(javabase) FileException "java.lang.Exception"; -%typemap(javacode) FileException %{ - public String getMessage() { - return what(); - } -%} +Greeting: At your service Sir +Availability: 24 hours per dayThis generates:
+Note the usage is very much like it would be used if we were writing + C code, that is, explicit memory management is needed. No C memory is + allocated in the construction of the Butler proxy class and + the proxy class will not destroy the underlying C memory when it is + collected. A number of typemaps and features are needed to implement + this approach. The following interface file code should be placed + before SWIG parses the above C code.
--public class FileException extends java.lang.Exception { - ... - public String getMessage() { - return what(); - } +%module example - public FileException(String msg) { ... } +// Do not generate the default proxy constructor or destructor +%nodefaultctor Butler; +%nodefaultdtor Butler; - public String what() { - return exampleJNI.FileException_what(swigCPtr, this); +// Add in pure Java code proxy constructor +%typemap(javacode) Butler %{ + /** This constructor creates the proxy which initially does not create nor own any C memory */ + public Butler() { + this(0, false); } +%} + +// Type typemaps for marshalling Butler ** +%typemap(jni) Butler ** "jobject" +%typemap(jtype) Butler ** "Butler" +%typemap(jstype) Butler ** "Butler" + +// Typemaps for Butler ** as a parameter output type +%typemap(in) Butler ** (Butler *ppButler = 0) %{ + $1 = &ppButler; +%} +%typemap(argout) Butler ** { + // Give Java proxy the C pointer (of newly created object) + jclass clazz = (*jenv)->FindClass(jenv, "Butler"); + jfieldID fid = (*jenv)->GetFieldID(jenv, clazz, "swigCPtr", "J"); + jlong cPtr = 0; + *(Butler **)&cPtr = *$1; + (*jenv)->SetLongField(jenv, $input, fid, cPtr); } +%typemap(javain) Butler ** "$javainput"We could alternatively have used %rename to rename -what() into getMessage().
-24.10.3 NaN Exception - - exception handling for a particular type
-A Java exception can be thrown from any Java or JNI code. Therefore, - as most typemaps contain either Java or JNI code, just about any - typemap could throw an exception. The following example demonstrates - exception handling on a type by type basis by checking for 'Not a - number' (NaN) whenever a parameter of type float is wrapped.
-Consider the following C++ code:
----bool calculate(float first, float second); --To validate every float being passed to C++, we could - precede the code being wrapped by the following typemap which throws a - runtime exception whenever the float is 'Not a Number':
+Note that the JNI code sets the proxy's swigCPtr member + variable to point to the newly created object. The swigCMemOwn + remains unchanged (at false), so that the proxy does not own the + memory.
+Note: The old %nodefault directive disabled the default constructor + and destructor at the same time. This is unsafe in most of the cases, + and you can use the explicit %nodefaultctor and %nodefaultdtor + directives to achieve the same result if needed.
+The second approach offers a more object oriented interface to the + Java user. We do this by making the Java proxy class's constructor call + the HireButler() method to create the underlying C object. + Additionally we get the proxy to take ownership of the memory so that + the finalizer will call the FireButler() function. The proxy + class will thus take ownership of the memory and clean it up when no + longer needed. We will also prevent the user from being able to + explicitly call the HireButler() and FireButler() + functions. Usage from Java will simply be:
--%module example -%typemap(javain) float "$module.CheckForNaN($javainput)" -%pragma(java) modulecode=%{ - /** Simply returns the input value unless it is not a number, - whereupon an exception is thrown. */ - static protected float CheckForNaN(float num) { - if (Float.isNaN(num)) - throw new RuntimeException("Not a number"); - return num; - } -%} +Butler jeeves = new Butler(); +System.out.println("Greeting: " + jeeves.getGreeting()); +System.out.println("Availability: " + jeeves.getHoursAvailable() + " hours per day");Note that the CheckForNaN support method has been added to - the module class using the modulecode pragma. The following - shows the generated code of interest:
+Note that the Butler class is used just like any other Java class + and no extra coding by the user needs to be written to clear up the + underlying C memory as the finalizer will be called by the garbage + collector which in turn will call the FireButler() function. + To implement this, we use the above interface file code but remove the +javacode typemap and add the following:
--public class example { - ... - - /** Simply returns the input value unless it is not a number, - whereupon an exception is thrown. */ - static protected float CheckForNaN(float num) { - if (Float.isNaN(num)) - throw new RuntimeException("Not a number"); - return num; - } +// Don't expose the memory allocation/de-allocation functions +%ignore FireButler(Butler *pButler); +%ignore HireButler(Butler **ppButler); - public static boolean calculate(float first, float second) { - return exampleJNI.calculate(example.CheckForNaN(first), example.CheckForNaN(second)); +// Add in a custom proxy constructor and destructor +%extend Butler { + Butler() { + Butler *pButler = 0; + HireButler(&pButler); + return pButler; } + ~Butler() { + FireButler($self); + } }Note that the "javain" typemap is used for every occurrence of a -float being used as an input. Of course, we could have targeted the - typemap at a particular parameter by using float first, say, - instead of just float.
-The exception checking could alternatively have been placed into the - 'pre' attribute that the "javain" typemap supports. The "javain" - typemap above could be replaced with the following:
----%typemap(javain, pre=" $module.CheckForNaN($javainput);") float "$javainput" --which would modify the calculate function to instead be - generated as:
+Note that the code in %extend is using a C++ type + constructor and destructor, yet the generated code will still compile + as C code, see Adding member + functions to C structures. The C functional interface has been + completely morphed into an object-oriented interface and the Butler + class would behave much like any pure Java class and feel more natural + to Java users.
+25.10.11 Memory + management when returning references to member variables
+This example shows how to prevent premature garbage collection of + objects when the underlying C++ class returns a pointer or reference to + a member variable.
+Consider the following C++ code:
--public class example { - ... - public static boolean calculate(float first, float second) { - example.CheckForNaN(first); - example.CheckForNaN(second); - { - return exampleJNI.calculate(first, second); - } - } -} +struct Wheel { + int size; + Wheel(int sz) : size(sz) {} +}; + +class Bike { + Wheel wheel; +public: + Bike(int val) : wheel(val) {} + Wheel& getWheel() { return wheel; } +};See the Date marshalling example - for an example using further "javain" typemap attributes.
-If we decide that what we actually want is a checked exception - instead of a runtime exception, we can change this easily enough. The - proxy method that uses float as an input, must then add the - exception class to the throws clause. SWIG can handle this as it - supports the 'throws' typemap - attribute for specifying classes for the throws clause. Thus we can - modify the pragma and the typemap for the throws clause:
+and the following usage from Java after running the code through + SWIG:
--%typemap(javain, throws="java.lang.Exception") float "$module.CheckForNaN($javainput)" -%pragma(java) modulecode=%{ - /** Simply returns the input value unless it is not a number, - whereupon an exception is thrown. */ - static protected float CheckForNaN(float num) throws java.lang.Exception { - if (Float.isNaN(num)) - throw new RuntimeException("Not a number"); - return num; - } -%} + Wheel wheel = new Bike(10).getWheel(); + System.out.println("wheel size: " + wheel.getSize()); + // Simulate a garbage collection + System.gc(); + System.runFinalization(); + System.out.println("wheel size: " + wheel.getSize());The calculate method now has a throws clause and even - though the typemap is used twice for both float first and -float second, the throws clause contains a single instance of -java.lang.Exception:
-++Don't be surprised that if the resulting output gives strange + results such as...
+--public class example { - ... - - /** Simply returns the input value unless it is not a number, - whereupon an exception is thrown. */ - static protected float CheckForNaN(float num) throws java.lang.Exception { - if (Float.isNaN(num)) - throw new RuntimeException("Not a number"); - return num; - } - - public static boolean calculate(float first, float second) throws java.lang.Exception { - return exampleJNI.calculate(example.CheckForNaN(first), example.CheckForNaN(second)); - } -} +wheel size: 10 +wheel size: 135019664If we were a martyr to the JNI cause, we could replace the succinct - code within the "javain" typemap with a few pages of JNI code. If we - had, we would have put it in the "in" typemap which, like all JNI and - Java typemaps, also supports the 'throws' attribute.
-24.10.4 Converting - Java String arrays to char **
-A common problem in many C programs is the processing of command - line arguments, which are usually passed in an array of NULL terminated - strings. The following SWIG interface file allows a Java String array - to be used as a char ** object.
+What has happened here is the garbage collector has collected the +Bike instance as it doesn't think it is needed any more. The proxy + instance, wheel, contains a reference to memory that was + deleted when the Bike instance was collected. In order to + prevent the garbage collector from collecting the Bike + instance a reference to the Bike must be added to the +wheel instance. You can do this by adding the reference when the +getWheel() method is called using the following typemaps.
--%module example - -/* This tells SWIG to treat char ** as a special case when used as a parameter - in a function call */ -%typemap(in) char ** (jint size) { - int i = 0; - size = (*jenv)->GetArrayLength(jenv, $input); - $1 = (char **) malloc((size+1)*sizeof(char *)); - /* make a copy of each string */ - for (i = 0; i<size; i++) { - jstring j_string = (jstring)(*jenv)->GetObjectArrayElement(jenv, $input, i); - const char * c_string = (*jenv)->GetStringUTFChars(jenv, j_string, 0); - $1[i] = malloc((strlen(c_string)+1)*sizeof(char)); - strcpy($1[i], c_string); - (*jenv)->ReleaseStringUTFChars(jenv, j_string, c_string); - (*jenv)->DeleteLocalRef(jenv, j_string); - } - $1[i] = 0; -} - -/* This cleans up the memory we malloc'd before the function call */ -%typemap(freearg) char ** { - int i; - for (i=0; i<size$argnum-1; i++) - free($1[i]); - free($1); -} - -/* This allows a C function to return a char ** as a Java String array */ -%typemap(out) char ** { - int i; - int len=0; - jstring temp_string; - const jclass clazz = (*jenv)->FindClass(jenv, "java/lang/String"); - - while ($1[len]) len++; - jresult = (*jenv)->NewObjectArray(jenv, len, clazz, NULL); - /* exception checking omitted */ - - for (i=0; i<len; i++) { - temp_string = (*jenv)->NewStringUTF(jenv, *result++); - (*jenv)->SetObjectArrayElement(jenv, jresult, i, temp_string); - (*jenv)->DeleteLocalRef(jenv, temp_string); - } -} - -/* These 3 typemaps tell SWIG what JNI and Java types to use */ -%typemap(jni) char ** "jobjectArray" -%typemap(jtype) char ** "String[]" -%typemap(jstype) char ** "String[]" - -/* These 2 typemaps handle the conversion of the jtype to jstype typemap type - and vice versa */ -%typemap(javain) char ** "$javainput" -%typemap(javaout) char ** { - return $jnicall; - } - -/* Now a few test functions */ -%inline %{ - -int print_args(char **argv) { - int i = 0; - while (argv[i]) { - printf("argv[%d] = %s\n", i, argv[i]); - i++; - } - return i; -} - -char **get_args() { - static char *values[] = { "Dave", "Mike", "Susan", "John", "Michelle", 0}; - return &values[0]; -} - +%typemap(javacode) Wheel %{ + // Ensure that the GC doesn't collect any Bike instance set from Java + private Bike bikeReference; + protected void addReference(Bike bike) { + bikeReference = bike; + } %} + +// Add a Java reference to prevent premature garbage collection and resulting use +// of dangling C++ pointer. Intended for methods that return pointers or +// references to a member variable. +%typemap(javaout) Wheel& getWheel { + long cPtr = $jnicall; + $javaclassname ret = null; + if (cPtr != 0) { + ret = new $javaclassname(cPtr, $owner); + ret.addReference(this); + } + return ret; + }Note that the 'C' JNI calling convention is used. Checking for any - thrown exceptions after JNI function calls has been omitted. When this - module is compiled, our wrapped C functions can be used by the - following Java program:
+The code in the first typemap gets added to the Wheel proxy + class. The code in the second typemap constitutes the bulk of the code + in the generated getWheel() function:
--// File runme.java - -public class runme { - - static { - try { - System.loadLibrary("example"); - } catch (UnsatisfiedLinkError e) { - System.err.println("Native code library failed to load. " + e); - System.exit(1); - } +public class Wheel { + ... + // Ensure that the GC doesn't collect any bike set from Java + private Bike bikeReference; + protected void addReference(Bike bike) { + bikeReference = bike; } +} - public static void main(String argv[]) { - String animals[] = {"Cat","Dog","Cow","Goat"}; - example.print_args(animals); - String args[] = example.get_args(); - for (int i=0; i<args.length; i++) - System.out.println(i + ":" + args[i]); +public class Bike { + ... + public Wheel getWheel() { + long cPtr = exampleJNI.Bike_getWheel(swigCPtr, this); + Wheel ret = null; + if (cPtr != 0) { + ret = new Wheel(cPtr, false); + ret.addReference(this); + } + return ret; } }When compiled and run we get:
+Note the addReference call.
+25.10.12 Memory management + for objects passed to the C++ layer
+Managing memory can be tricky when using C++ and Java proxy classes. + The previous example shows one such case and this example looks at + memory management for a class passed to a C++ method which expects the + object to remain in scope after the function has returned. Consider the + following two C++ classes:
--$ java runme -argv[0] = Cat -argv[1] = Dog -argv[2] = Cow -argv[3] = Goat -0:Dave -1:Mike -2:Susan -3:John -4:Michelle +struct Element { + int value; + Element(int val) : value(val) {} +}; +class Container { + Element* element; +public: + Container() : element(0) {} + void setElement(Element* e) { element = e; } + Element* getElement() { return element; } +};In the example, a few different typemaps are used. The "in" typemap - is used to receive an input argument and convert it to a C array. Since - dynamic memory allocation is used to allocate memory for the array, the - "freearg" typemap is used to later release this memory after the - execution of the C function. The "out" typemap is used for function - return values. Lastly the "jni", "jtype" and "jstype" typemaps are also - required to specify what Java types to use.
-24.10.5 Expanding a Java - object to multiple arguments
-Suppose that you had a collection of C functions with arguments such - as the following:
+and usage from C++
--int foo(int argc, char **argv); + Container container; + Element element(20); + container.setElement(&element); + cout << "element.value: " << container.getElement()->value << endl;In the previous example, a typemap was written to pass a Java String - array as the char **argv. This allows the function to be used - from Java as follows:
+and more or less equivalent usage from Java
--example.foo(4, new String[]{"red", "green", "blue", "white"}); + Container container = new Container(); + container.setElement(new Element(20)); + System.out.println("element value: " + container.getElement().getValue());Although this works, it's a little awkward to specify the argument - count. To fix this, a multi-argument typemap can be defined. This is - not very difficult--you only have to make slight modifications to the - previous example's typemaps:
+The C++ code will always print out 20, but the value printed out may + not be this in the Java equivalent code. In order to understand why, + consider a garbage collection occuring...
--%typemap(in) (int argc, char **argv) { - int i = 0; - $1 = (*jenv)->GetArrayLength(jenv, $input); - $2 = (char **) malloc(($1+1)*sizeof(char *)); - /* make a copy of each string */ - for (i = 0; i<$1; i++) { - jstring j_string = (jstring)(*jenv)->GetObjectArrayElement(jenv, $input, i); - const char * c_string = (*jenv)->GetStringUTFChars(jenv, j_string, 0); - $2[i] = malloc((strlen(c_string)+1)*sizeof(char)); - strcpy($2[i], c_string); - (*jenv)->ReleaseStringUTFChars(jenv, j_string, c_string); - (*jenv)->DeleteLocalRef(jenv, j_string); - } - $2[i] = 0; -} - -%typemap(freearg) (int argc, char **argv) { - int i; - for (i=0; i<$1-1; i++) - free($2[i]); - free($2); -} - -%typemap(jni) (int argc, char **argv) "jobjectArray" -%typemap(jtype) (int argc, char **argv) "String[]" -%typemap(jstype) (int argc, char **argv) "String[]" - -%typemap(javain) (int argc, char **argv) "$javainput" + Container container = new Container(); + container.setElement(new Element(20)); + // Simulate a garbage collection + System.gc(); + System.runFinalization(); + System.out.println("element value: " + container.getElement().getValue());When writing a multiple-argument typemap, each of the types is - referenced by a variable such as $1 or $2. The - typemap code simply fills in the appropriate values from the supplied - Java parameter.
-With the above typemap in place, you will find it no longer - necessary to supply the argument count. This is automatically set by - the typemap code. For example:
+The temporary element created with new Element(20) could + get garbage collected which ultimately means the container + variable is holding a dangling pointer, thereby printing out any old + random value instead of the expected value of 20. One solution is to + add in the appropriate references in the Java layer...
--example.foo(new String[]{"red", "green", "blue", "white"}); +public class Container { + + ... + + // Ensure that the GC doesn't collect any Element set from Java + // as the underlying C++ class stores a shallow copy + private Element elementReference; + private long getCPtrAndAddReference(Element element) { + elementReference = element; + return Element.getCPtr(element); + } + + public void setElement(Element e) { + exampleJNI.Container_setElement(swigCPtr, this, getCPtrAndAddReference(e), e); + } +}24.10.6 Using - typemaps to return arguments
-A common problem in some C programs is that values may be returned - in function parameters rather than in the return value of a function. - The typemaps.i file defines INPUT, OUTPUT and INOUT typemaps - which can be used to solve some instances of this problem. This library - file uses an array as a means of moving data to and from Java when - wrapping a C function that takes non const pointers or non const - references as parameters.
-Now we are going to outline an alternative approach to using arrays - for C pointers. The INOUT typemap uses a double[] array for - receiving and returning the double* parameters. In this - approach we are able to use a Java class myDouble instead of -double[] arrays where the C pointer double* is required.
-Here is our example function:
+The following typemaps will generate the desired code. The 'javain' + typemap matches the input parameter type for the setElement + method. The 'javacode' typemap simply adds in the specified code into + the Java proxy class.
--/* Returns a status value and two values in out1 and out2 */ -int spam(double a, double b, double *out1, double *out2); +%typemap(javain) Element *e "getCPtrAndAddReference($javainput)" + +%typemap(javacode) Container %{ + // Ensure that the GC doesn't collect any element set from Java + // as the underlying C++ class stores a shallow copy + private Element elementReference; + private long getCPtrAndAddReference(Element element) { + elementReference = element; + return Element.getCPtr(element); + } +%}If we define a structure MyDouble containing a double - member variable and use some typemaps we can solve this problem. For - example we could put the following through SWIG:
+25.10.13 Date marshalling using the + javain typemap and associated attributes
+The NaN Exception example + is a simple example of the "javain" typemap and its 'pre' attribute. + This example demonstrates how a C++ date class, say CDate, can + be mapped onto the standard Java date class, +java.util.GregorianCalendar by using the 'pre', 'post' and + 'pgcppname' attributes of the "javain" typemap. The idea is that the +GregorianCalendar is used wherever the C++ API uses a CDate +. Let's assume the code being wrapped is as follows:
--%module example - -/* Define a new structure to use instead of double * */ -%inline %{ -typedef struct { - double value; -} MyDouble; -%} - - -%{ -/* Returns a status value and two values in out1 and out2 */ -int spam(double a, double b, double *out1, double *out2) { - int status = 1; - *out1 = a*10.0; - *out2 = b*100.0; - return status; +class CDate { +public: + CDate(int year, int month, int day); + int getYear(); + int getMonth(); + int getDay(); + ... +}; +struct Action { + static int doSomething(const CDate &dateIn, CDate &dateOut); + Action(const CDate &date, CDate &dateOut); }; -%} - -/* -This typemap will make any double * function parameters with name OUTVALUE take an -argument of MyDouble instead of double *. This will -allow the calling function to read the double * value after returning from the function. -*/ -%typemap(in) double *OUTVALUE { - jclass clazz = jenv->FindClass("MyDouble"); - jfieldID fid = jenv->GetFieldID(clazz, "swigCPtr", "J"); - jlong cPtr = jenv->GetLongField($input, fid); - MyDouble *pMyDouble = NULL; - *(MyDouble **)&pMyDouble = *(MyDouble **)&cPtr; - $1 = &pMyDouble->value; -} - -%typemap(jtype) double *OUTVALUE "MyDouble" -%typemap(jstype) double *OUTVALUE "MyDouble" -%typemap(jni) double *OUTVALUE "jobject" - -%typemap(javain) double *OUTVALUE "$javainput" - -/* Now we apply the typemap to the named variables */ -%apply double *OUTVALUE { double *out1, double *out2 }; -int spam(double a, double b, double *out1, double *out2);Note that the C++ JNI calling convention has been used this time and - so must be compiled as C++ and the -c++ commandline must be passed to - SWIG. JNI error checking has been omitted for clarity.
-What the typemaps do are make the named double* function - parameters use our new MyDouble wrapper structure. The "in" - typemap takes this structure, gets the C++ pointer to it, takes the -double value member variable and passes it to the C++ spam - function. In Java, when the function returns, we use the SWIG created -getValue() function to get the output value. The following Java - program demonstrates this:
+Note that dateIn is const and therefore read only and +dateOut is a non-const output type.
+First let's look at the code that is generated by default, where the + Java proxy class CDate is used in the proxy interface:
--// File: runme.java - -public class runme { - - static { - try { - System.loadLibrary("example"); - } catch (UnsatisfiedLinkError e) { - System.err.println("Native code library failed to load. " + e); - System.exit(1); - } +public class Action { + ... + public static int doSomething(CDate dateIn, CDate dateOut) { + return exampleJNI.Action_doSomething(CDate.getCPtr(dateIn), dateIn, + CDate.getCPtr(dateOut), dateOut); } - public static void main(String argv[]) { - MyDouble out1 = new MyDouble(); - MyDouble out2 = new MyDouble(); - int ret = example.spam(1.2, 3.4, out1, out2); - System.out.println(ret + " " + out1.getValue() + " " + out2.getValue()); + public Action(CDate date, CDate dateOut) { + this(exampleJNI.new_Action(CDate.getCPtr(date), date, + CDate.getCPtr(dateOut), dateOut), true); } }When compiled and run we get:
+The CDate & and const CDate & Java code is + generated from the following two default typemaps:
--$ java runme -1 12.0 340.0 +%typemap(jstype) SWIGTYPE & "$javaclassname" +%typemap(javain) SWIGTYPE & "$javaclassname.getCPtr($javainput)"24.10.7 Adding Java downcasts to - polymorphic return types
-SWIG support for polymorphism works in that the appropriate virtual - function is called. However, the default generated code does not allow - for downcasting. Let's examine this with the following code:
+where '$javaclassname' is translated into the proxy class name, +CDate and '$javainput' is translated into the name of the + parameter, eg dateIn. From Java, the intention is then to call + into a modifed API with something like:
+-%include "std_string.i" +java.util.GregorianCalendar calendarIn = + new java.util.GregorianCalendar(2011, java.util.Calendar.APRIL, 13, 0, 0, 0); +java.util.GregorianCalendar calendarOut = new java.util.GregorianCalendar(); -#include <iostream> -using namespace std; -class Vehicle { -public: - virtual void start() = 0; -... -}; +// Note in calls below, calendarIn remains unchanged and calendarOut +// is set to a new value by the C++ call +Action.doSomething(calendarIn, calendarOut); +Action action = new Action(calendarIn, calendarOut); ++To achieve this mapping, we need to alter the default code + generation slightly so that at the Java layer, a GregorianCalendar + is converted into a CDate. The JNI intermediary layer will + still take a pointer to the underlying CDate class. The + typemaps to achieve this are shown below.
++++%typemap(jstype) const CDate& "java.util.GregorianCalendar" +%typemap(javain, + pre=" CDate temp$javainput = new CDate($javainput.get(java.util.Calendar.YEAR), " + "$javainput.get(java.util.Calendar.MONTH), $javainput.get(java.util.Calendar.DATE));", + pgcppname="temp$javainput") const CDate & + "$javaclassname.getCPtr(temp$javainput)" -class Ambulance : public Vehicle { - string vol; -public: - Ambulance(string volume) : vol(volume) {} - virtual void start() { - cout << "Ambulance started" << endl; +%typemap(jstype) CDate& "java.util.Calendar" +%typemap(javain, + pre=" CDate temp$javainput = new CDate($javainput.get(java.util.Calendar.YEAR), " + "$javainput.get(java.util.Calendar.MONTH), $javainput.get(java.util.Calendar.DATE));", + post=" $javainput.set(temp$javainput.getYear(), temp$javainput.getMonth(), " + "temp$javainput.getDay(), 0, 0, 0);", + pgcppname="temp$javainput") CDate & + "$javaclassname.getCPtr(temp$javainput)" ++The resulting generated proxy code in the Action class + follows:
++-+public class Action { + ... + public static int doSomething(java.util.GregorianCalendar dateIn, + java.util.Calendar dateOut) { + CDate tempdateIn = new CDate(dateIn.get(java.util.Calendar.YEAR), + dateIn.get(java.util.Calendar.MONTH), + dateIn.get(java.util.Calendar.DATE)); + CDate tempdateOut = new CDate(dateOut.get(java.util.Calendar.YEAR), + dateOut.get(java.util.Calendar.MONTH), + dateOut.get(java.util.Calendar.DATE)); + try { + return exampleJNI.Action_doSomething(CDate.getCPtr(tempdateIn), tempdateIn, + CDate.getCPtr(tempdateOut), tempdateOut); + } finally { + dateOut.set(tempdateOut.getYear(), tempdateOut.getMonth(), tempdateOut.getDay(), 0, 0, 0); } - void sound_siren() { - cout << vol << " siren sounded!" << endl; + } + + static private long SwigConstructAction(java.util.GregorianCalendar date, + java.util.Calendar dateOut) { + CDate tempdate = new CDate(date.get(java.util.Calendar.YEAR), + date.get(java.util.Calendar.MONTH), + date.get(java.util.Calendar.DATE)); + CDate tempdateOut = new CDate(dateOut.get(java.util.Calendar.YEAR), + dateOut.get(java.util.Calendar.MONTH), + dateOut.get(java.util.Calendar.DATE)); + try { + return exampleJNI.new_Action(CDate.getCPtr(tempdate), tempdate, + CDate.getCPtr(tempdateOut), tempdateOut); + } finally { + dateOut.set(tempdateOut.getYear(), tempdateOut.getMonth(), tempdateOut.getDay(), 0, 0, 0); } -... -}; + } -Vehicle *vehicle_factory() { - return new Ambulance("Very loud"); + public Action(java.util.GregorianCalendar date, java.util.Calendar dateOut) { + this(Action.SwigConstructAction(date, dateOut), true); + } }If we execute the following Java code:
+A few things to note:
++
+- The "javatype" typemap has changed the parameter type to +java.util.GregorianCalendar or java.util.Calendar instead + of the default generated CDate proxy.
+- The code in the 'pre' attribute appears before the JNI call ( +exampleJNI.new_Action / exampleJNI.Action_doSomething).
+- The code in the 'post' attribute appears after the JNI call.
+- A try .. finally block is generated with the JNI call in the try + block and 'post' code in the finally block. The alternative of just + using a temporary variable for the return value from the JNI call and + the 'post' code being generated before the return statement is not + possible given that the JNI call is in one line and comes from the + "javaout" typemap.
+- The temporary variables in the "javain" typemaps are called +temp$javain, where "$javain" is replaced with the parameter name. + "$javain" is used to mangle the variable name so that more than one +CDate & type can be used as a parameter in a method, otherwise two + or more local variables with the same name would be generated.
+- The use of the "javain" typemap causes a constructor helper + function (SwigConstructAction) to be generated. This allows + Java code to be called before the JNI call and is required as the Java + compiler won't compile code inserted before the 'this' call.
+- The 'pgcppname' attribute is used to modify the object being passed + as the premature garbage collection prevention + parameter (the 2nd and 4th parameters in the JNI calls).
+25.11 Living with Java Directors
+This section is intended to address frequently asked questions and + frequently encountered problems when using Java directors.
++
- When my program starts up, it complains that method_foo + cannot be found in a Java method called swig_module_init. How do + I fix this? +
+Open up the C++ wrapper source code file and look for
++"method_foo"
(include the double quotes, they are important!) + Look at the JNI field descriptor and make sure that each class that + occurs in the descriptor has the correct package name in front of it. + If the package name is incorrect, put a "javapackage" typemap in your + SWIG interface file.- I'm compiling my code and I'm using templates. I provided a + javapackage typemap, but SWIG doesn't generate the right JNI field + descriptor. +
Use the template's renamed name as the argument to the "javapackage" + typemap:
--Vehicle vehicle = example.vehicle_factory(); -vehicle.start(); - -Ambulance ambulance = (Ambulance)vehicle; -ambulance.sound_siren(); +%typemap(javapackage) std::vector<int> "your.package.here" +%template(VectorOfInt) std::vector<int>;-We get:
++ +When I pass class pointers or references through a C++ upcall and + I try to type cast them, Java complains with a ClassCastException. What + am I doing wrong?
+Normally, a non-director generated Java proxy class creates + temporary Java objects as follows:
--Ambulance started -java.lang.ClassCastException - at runme.main(runme.java:16) +public static void MyClass_method_upcall(MyClass self, long jarg1) +{ + Foo darg1 = new Foo(jarg1, false); + + self.method_upcall(darg1); +}Even though we know from examination of the C++ code that -vehicle_factory returns an object of type Ambulance, we - are not able to use this knowledge to perform the downcast in Java. - This occurs because the runtime type information is not completely - passed from C++ to Java when returning the type from -vehicle_factory(). Usually this is not a problem as virtual - functions do work by default, such as in the case of start(). - There are a few solutions to getting downcasts to work.
-The first is not to use a Java cast but a call to C++ to make the - cast. Add this to your code:
---%exception Ambulance::dynamic_cast(Vehicle *vehicle) { - $action - if (!result) { - jclass excep = jenv->FindClass("java/lang/ClassCastException"); - if (excep) { - jenv->ThrowNew(excep, "dynamic_cast exception"); - } - } +Unfortunately, this loses the Java type information that is part of + the underlying Foo director proxy class's Java object pointer causing + the type cast to fail. The SWIG Java module's director code attempts to + correct the problem, but only for director-enabled classes, + since the director class retains a global reference to its Java object. + Thus, for director-enabled classes and only for director-enabled + classes, the generated proxy Java code looks something like:
++-+public static void MyClass_method_upcall(MyClass self, long jarg1, + Foo jarg1_object) +{ + Foo darg1 = (jarg1_object != null ? jarg1_object : new Foo(jarg1, false)); + + self.method_upcall(darg1); } -%extend Ambulance { - static Ambulance *dynamic_cast(Vehicle *vehicle) { - return dynamic_cast<Ambulance *>(vehicle); - } -};It would then be used from Java like this
+When you import a SWIG interface file containing class definitions, + the classes you want to be director-enabled must be have the
++feature("director")
enabled for type symmetry to work. This + applies even when the class being wrapped isn't a director-enabled + class but takes parameters that are director-enabled classes.The current "type symmetry" design will work for simple C++ + inheritance, but will most likely fail for anything more complicated + such as tree or diamond C++ inheritance hierarchies. Those who are + interested in challenging problems are more than welcome to hack the
++Java::Java_director_declaration
method in+Source/Modules/java.cxx
.If all else fails, you can use the downcastXXXXX() method to attempt + to recover the director class's Java object pointer. For the Java Foo + proxy class, the Foo director class's java object pointer can be + accessed through the javaObjectFoo() method. The generated method's + signature is:
--Ambulance ambulance = Ambulance.dynamic_cast(vehicle); -ambulance.sound_siren(); + public static Foo javaObjectFoo(Foo obj);Should vehicle not be of type ambulance then a - Java ClassCastException is thrown. The next solution is a - purer solution in that Java downcasts can be performed on the types. - Add the following before the definition of vehicle_factory:
+From your code, this method is invoked as follows:
--%typemap(out) Vehicle * { - Ambulance *downcast = dynamic_cast<Ambulance *>($1); - *(Ambulance **)&$result = downcast; -} - -%typemap(javaout) Vehicle * { - return new Ambulance($jnicall, $owner); +public class MyClassDerived { + public void method_upcall(Foo foo_object) + { + FooDerived derived = (foo_object != null ? + (FooDerived) Foo.downcastFoo(foo_object) : null); + /* rest of your code here */ } +}Here we are using our knowledge that vehicle_factory always - returns type Ambulance so that the Java proxy is created as a - type Ambulance. If vehicle_factory can manufacture - any type of Vehicle and we want to be able to downcast using - Java casts for any of these types, then a different approach is needed. - Consider expanding our example with a new Vehicle type and a more - flexible factory function:
+An good approach for managing downcasting is placing a static method + in each derived class that performs the downcast from the superclass, + e.g.,
--class FireEngine : public Vehicle { -public: - FireEngine() {} - virtual void start() { - cout << "FireEngine started" << endl; +public class FooDerived extends Foo { + /* ... */ + public static FooDerived downcastFooDerived(Foo foo_object) + { + try { + return (foo_object != null ? (FooDerived) Foo.downcastFoo(foo_object); } - void roll_out_hose() { - cout << "Hose rolled out" << endl; + + catch (ClassCastException exc) { + // Wasn't a FooDerived object, some other subclass of Foo + return null; } - ... -}; -Vehicle *vehicle_factory(int vehicle_number) { - if (vehicle_number == 0) - return new Ambulance("Very loud"); - else - return new FireEngine(); + } }To be able to downcast with this sort of Java code:
+Then change the code in MyClassDerived as follows:
--FireEngine fireengine = (FireEngine)example.vehicle_factory(1); -fireengine.roll_out_hose(); -Ambulance ambulance = (Ambulance)example.vehicle_factory(0); -ambulance.sound_siren(); +public class MyClassDerived extends MyClass { + /* ... */ + public void method_upcall(Foo foo_object) + { + FooDerived derived = FooDerived.downcastFooDerived(foo_object); + /* rest of your code here */ + } +}-the following typemaps targeted at the vehicle_factory - function will achieve this. Note that in this case, the Java class is - constructed using JNI code rather than passing a pointer across the JNI - boundary in a Java long for construction in Java code.
++ + +Why isn't the proxy class declared abstract? Why aren't the + director upcall methods in the proxy class declared abstract?
+Declaring the proxy class and its methods abstract would break the + JNI argument marshalling and SWIG's downcall functionality (going from + Java to C++.) Create an abstract Java subclass that inherits from the + director-enabled class instead. Using the previous Foo class example:
--%typemap(jni) Vehicle *vehicle_factory "jobject" -%typemap(jtype) Vehicle *vehicle_factory "Vehicle" -%typemap(jstype) Vehicle *vehicle_factory "Vehicle" -%typemap(javaout) Vehicle *vehicle_factory { - return $jnicall; - } +public abstract class UserVisibleFoo extends Foo { + /** Make sure user overrides this method, it's where the upcall + * happens. + */ + public abstract void method_upcall(Foo foo_object); -%typemap(out) Vehicle *vehicle_factory { - Ambulance *ambulance = dynamic_cast<Ambulance *>($1); - FireEngine *fireengine = dynamic_cast<FireEngine *>($1); - if (ambulance) { - // call the Ambulance(long cPtr, boolean cMemoryOwn) constructor - jclass clazz = jenv->FindClass("Ambulance"); - if (clazz) { - jmethodID mid = jenv->GetMethodID(clazz, "<init>", "(JZ)V"); - if (mid) { - jlong cptr = 0; - *(Ambulance **)&cptr = ambulance; - $result = jenv->NewObject(clazz, mid, cptr, false); - } - } - } else if (fireengine) { - // call the FireEngine(long cPtr, boolean cMemoryOwn) constructor - jclass clazz = jenv->FindClass("FireEngine"); - if (clazz) { - jmethodID mid = jenv->GetMethodID(clazz, "<init>", "(JZ)V"); - if (mid) { - jlong cptr = 0; - *(FireEngine **)&cptr = fireengine; - $result = jenv->NewObject(clazz, mid, cptr, false); - } - } - } - else { - cout << "Unexpected type " << endl; + /// Downcast from Foo to UserVisibleFoo + public static UserVisibleFoo downcastUserVisibleFoo(Foo foo_object) + { + try { + return (foo_object != null ? (FooDerived) Foo.downcastFoo(foo_object) : null); } - if (!$result) - cout << "Failed to create new java object" << endl; + catch (ClassCastException exc) { + // Wasn't a FooDerived object, some other subclass of Foo + return null; + } + } }Better error handling would need to be added into this code. There - are other solutions to this problem, but this last example demonstrates - some more involved JNI code. SWIG usually generates code which - constructs the proxy classes using Java code as it is easier to handle - error conditions and is faster. Note that the JNI code above uses a - number of string lookups to call a constructor, whereas this would not - occur using byte compiled Java code.
-24.10.8 Adding an equals - method to the Java classes
-When a pointer is returned from a JNI function, it is wrapped using - a new Java proxy class or type wrapper class. Even when the pointers - are the same, it will not be possible to know that the two Java classes - containing those pointers are actually the same object. It is common in - Java to use the equals() method to check whether two objects - are equivalent. The equals() method is usually accompanied by - a hashCode() method in order to fulfill the requirement that - the hash code is equal for equal objects. Pure Java code methods like - these can be easily added:
+This doesn't prevent the user from creating subclasses derived from + Foo, however, UserVisibleFoo provides the safety net that reminds the + user to override the
+method_upcall()
method.25.12 Odds and ends
+25.12.1 JavaDoc comments
+The SWIG documentation system is currently deprecated. When it is + resurrected JavaDoc comments will be fully supported. If you can't wait + for the full documentation system a couple of workarounds are + available. The %javamethodmodifiers feature can be used for + adding proxy class method comments and module class method comments. + The "javaimports" typemap can be hijacked for adding in proxy class + JavaDoc comments. The jniclassimports or +jniclassclassmodifiers pragmas can also be used for adding + intermediary JNI class comments and likewise the moduleimports + or moduleclassmodifiers pragmas for the module class. Here is + an example adding in a proxy class and method comment:
--%typemap(javacode) SWIGTYPE %{ - public boolean equals(Object obj) { - boolean equal = false; - if (obj instanceof $javaclassname) - equal = ((($javaclassname)obj).swigCPtr == this.swigCPtr); - return equal; - } - public int hashCode() { - return (int)getPointer(); - } -%} +%javamethodmodifiers Barmy::lose_marbles() " + /** + * Calling this method will make you mad. + * Use with <b>utmost</b> caution. + */ + public"; -class Foo { }; -Foo* returnFoo(Foo *foo) { return foo; } +%typemap(javaimports) Barmy " +/** The crazy class. Use as a last resort. */" + +class Barmy { +public: + void lose_marbles() {} +};The following would display false without the javacode - typemap above. With the typemap defining the equals method the - result is true.
+Note the "public" added at the end of the %javamethodmodifiers + as this is the default for this feature. The generated proxy class with + JavaDoc comments is then as follows:
--Foo foo1 = new Foo(); -Foo foo2 = example.returnFoo(foo1); -System.out.println("foo1? " + foo1.equals(foo2)); +/** The crazy class. Use as a last resort. */ +public class Barmy { +... + /** + * Calling this method will make you mad. + * Use with <b>utmost</b> caution. + */ + public void lose_marbles() { + ... + } +... +}24.10.9 Void pointers and a common - Java base class
-One might wonder why the common code that SWIG emits for the proxy - and type wrapper classes is not pushed into a base class. The reason is - that although swigCPtr could be put into a common base class - for all classes wrapping C structures, it would not work for C++ - classes involved in an inheritance chain. Each class derived from a - base needs a separate swigCPtr because C++ compilers sometimes - use a different pointer value when casting a derived class to a base. - Additionally as Java only supports single inheritance, it would not be - possible to derive wrapped classes from your own pure Java classes if - the base class has been 'used up' by SWIG. However, you may want to - move some of the common code into a base class. Here is an example - which uses a common base class for all proxy classes and type wrapper - classes:
+25.12.2 Functional interface + without proxy classes
+It is possible to run SWIG in a mode that does not produce proxy + classes by using the -noproxy commandline option. The interface is + rather primitive when wrapping structures or classes and is accessed + through function calls to the module class. All the functions in the + module class are wrapped by functions with identical names as those in + the intermediary JNI class.
+Consider the example we looked at when examining proxy classes:
--%typemap(javabase) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], - SWIGTYPE (CLASS::*) "SWIG" - -%typemap(javacode) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], - SWIGTYPE (CLASS::*) %{ - protected long getPointer() { - return swigCPtr; - } -%} +class Foo { +public: + int x; + int spam(int num, Foo* foo); +};Define new base class called SWIG:
+When using -noproxy, type wrapper classes are generated + instead of proxy classes. Access to all the functions and variables is + through a C like set of functions where the first parameter passed is + the pointer to the class, that is an instance of a type wrapper class. + Here is what the module class looks like:
--public abstract class SWIG { - protected abstract long getPointer(); - - public boolean equals(Object obj) { - boolean equal = false; - if (obj instanceof SWIG) - equal = (((SWIG)obj).getPointer() == this.getPointer()); - return equal; - } - - SWIGTYPE_p_void getVoidPointer() { - return new SWIGTYPE_p_void(getPointer(), false); - } +public class example { + public static void Foo_x_get(SWIGTYPE_p_Foo self, int x) {...} + public static int Foo_x_get(SWIGTYPE_p_Foo self) {...} + public static int Foo_spam(SWIGTYPE_p_Foo self, int num, SWIGTYPE_p_Foo foo) {...} + public static SWIGTYPE_p_Foo new_Foo() {...} + public static void delete_Foo(SWIGTYPE_p_Foo self) {...} }This example contains some useful functionality which you may want - in your code.
--
-- It has an equals() method. Unlike the previous example, - the method code isn't replicated in all classes.
-- It also has a function which effectively implements a cast from the - type of the proxy/type wrapper class to a void pointer. This is - necessary for passing a proxy class or a type wrapper class to a - function that takes a void pointer.
-24.10.10 Struct pointer to - pointer
-Pointers to pointers are often used as output parameters in C - factory type functions. These are a bit more tricky to handle. Consider - the following situation where a Butler can be hired and fired:
+This approach is not nearly as natural as using proxy classes as the + functions need to be used like this:
--typedef struct { - int hoursAvailable; - char *greeting; -} Butler; - -// Note: HireButler will allocate the memory -// The caller must free the memory by calling FireButler()!! -extern int HireButler(Butler **ppButler); -extern void FireButler(Butler *pButler); +SWIGTYPE_p_Foo foo = example.new_Foo(); +example.Foo_x_set(foo, 10); +int var = example.Foo_x_get(foo); +example.Foo_spam(foo, 20, foo); +example.delete_Foo(foo);C code implementation:
+Unlike proxy classes, there is no attempt at tracking memory. All + destructors have to be called manually for example the +delete_Foo(foo) call above.
+25.12.3 Using your own JNI + functions
+You may have some hand written JNI functions that you want to use in + addition to the SWIG generated JNI functions. Adding these to your SWIG + generated package is possible using the %native directive. If + you don't want SWIG to wrap your JNI function then of course you can + simply use the %ignore directive. However, if you want SWIG to + generate just the Java code for a JNI function then use the %native + directive. The C types for the parameters and return type must be + specified in place of the JNI types and the function name must be the + native method name. For example:
--int HireButler(Butler **ppButler) { - Butler *pButler = (Butler *)malloc(sizeof(Butler)); - pButler->hoursAvailable = 24; - pButler->greeting = (char *)malloc(32); - strcpy(pButler->greeting, "At your service Sir"); - *ppButler = pButler; - return 1; -} -void FireButler(Butler *pButler) { - free(pButler->greeting); - free(pButler); -} +%native (HandRolled) void HandRolled(int, char *); +%{ +JNIEXPORT void JNICALL Java_packageName_moduleName_HandRolled(JNIEnv *, jclass, + jlong, jstring); +%}Let's take two approaches to wrapping this code. The first is to - provide a functional interface, much like the original C interface. The - following Java code shows how we intend the code to be used:
+No C JNI function will be generated and the +Java_packageName_moduleName_HandRolled function will be accessible + using the SWIG generated Java native method call in the intermediary + JNI class which will look like this:
-- Butler jeeves = new Butler(); - example.HireButler(jeeves); - System.out.println("Greeting: " + jeeves.getGreeting()); - System.out.println("Availability: " + jeeves.getHoursAvailable() + " hours per day"); - example.FireButler(jeeves); + public final static native void HandRolled(int jarg1, String jarg2);Resulting in the following output when run:
-+and as usual this function is wrapped by another which for a global + C function would appear in the module class:
+--Greeting: At your service Sir -Availability: 24 hours per day + public static void HandRolled(int arg0, String arg1) { + exampleJNI.HandRolled(arg0, arg1); + }Note the usage is very much like it would be used if we were writing - C code, that is, explicit memory management is needed. No C memory is - allocated in the construction of the Butler proxy class and - the proxy class will not destroy the underlying C memory when it is - collected. A number of typemaps and features are needed to implement - this approach. The following interface file code should be placed - before SWIG parses the above C code.
+The packageName and moduleName must of course be + correct else you will get linker errors when the JVM dynamically loads + the JNI function. You may have to add in some "jtype", "jstype", + "javain" and "javaout" typemaps when wrapping some JNI types. Here the + default typemaps work for int and char *.
+In summary the %native directive is telling SWIG to + generate the Java code to access the JNI C code, but not the JNI C + function itself. This directive is only really useful if you want to + mix your own hand crafted JNI code and the SWIG generated code into one + Java class or package.
+25.12.4 Performance concerns and hints +
+If you're directly manipulating huge arrays of complex objects from + Java, performance may suffer greatly when using the array functions in +arrays_java.i. Try and minimise the expensive JNI calls to C/C++ + functions, perhaps by using temporary Java variables instead of + accessing the information directly from the C/C++ object.
+Java classes without any finalizers generally speed up code + execution as there is less for the garbage collector to do. Finalizer + generation can be stopped by using an empty javafinalize + typemap:
--%module example - -// Do not generate the default proxy constructor or destructor -%nodefaultctor Butler; -%nodefaultdtor Butler; - -// Add in pure Java code proxy constructor -%typemap(javacode) Butler %{ - /** This constructor creates the proxy which initially does not create nor own any C memory */ - public Butler() { - this(0, false); - } -%} - -// Type typemaps for marshalling Butler ** -%typemap(jni) Butler ** "jobject" -%typemap(jtype) Butler ** "Butler" -%typemap(jstype) Butler ** "Butler" - -// Typemaps for Butler ** as a parameter output type -%typemap(in) Butler ** (Butler *ppButler = 0) %{ - $1 = &ppButler; -%} -%typemap(argout) Butler ** { - // Give Java proxy the C pointer (of newly created object) - jclass clazz = (*jenv)->FindClass(jenv, "Butler"); - jfieldID fid = (*jenv)->GetFieldID(jenv, clazz, "swigCPtr", "J"); - jlong cPtr = 0; - *(Butler **)&cPtr = *$1; - (*jenv)->SetLongField(jenv, $input, fid, cPtr); -} -%typemap(javain) Butler ** "$javainput" +%typemap(javafinalize) SWIGTYPE ""Note that the JNI code sets the proxy's swigCPtr member - variable to point to the newly created object. The swigCMemOwn - remains unchanged (at false), so that the proxy does not own the - memory.
-Note: The old %nodefault directive disabled the default constructor - and destructor at the same time. This is unsafe in most of the cases, - and you can use the explicit %nodefaultctor and %nodefaultdtor - directives to achieve the same result if needed.
-The second approach offers a more object oriented interface to the - Java user. We do this by making the Java proxy class's constructor call - the HireButler() method to create the underlying C object. - Additionally we get the proxy to take ownership of the memory so that - the finalizer will call the FireButler() function. The proxy - class will thus take ownership of the memory and clean it up when no - longer needed. We will also prevent the user from being able to - explicitly call the HireButler() and FireButler() - functions. Usage from Java will simply be:
+However, you will have to be careful about memory management and + make sure that you code in a call to the delete() member + function. This method normally calls the C++ destructor or free() + for C code.
+25.12.5 Debugging
+The generated code can be debugged using both a Java debugger and a + C++ debugger using the usual debugging techniques. Breakpoints can be + set in either Java or C++ code and so both can be debugged + simultaneously. Most debuggers do not understand both Java and C++, + with one noteable exception of Sun Studio, where it is possible to step + from Java code into a JNI method within one environment.
+Alternatively, debugging can involve placing debug printout + statements in the JNI layer using the %exception directive. + See the special + variables for %exception section. Many of the default typemaps can + also be overridden and modified for adding in extra logging/debug + display information.
+The -Xcheck:jni and -Xcheck:nabounds Java + executable options are useful for debugging to make sure the JNI code + is behaving. The -verbose:jni and -verbose:gc are also useful options + for monitoring code behaviour.
+25.13 Java Examples
+The directory Examples/java has a number of further examples. Take a + look at these if you want to see some of the techniques described in + action. The Examples/index.html file in the parent directory contains + the SWIG Examples Documentation and is a useful starting point. If your + SWIG installation went well Unix users should be able to type make + in each example directory, then java main to see them running. + For the benefit of Windows users, there are also Visual C++ project + files in a couple of the Windows Examples +. There are also many regression tests in the Examples/test-suite + directory. Many of these have runtime tests in the java subdirectory.
+
+26 SWIG and Javascript
+ + +++ ++
+- Overview
+- Preliminaries + +
+- Integration + +
+- Examples + +
+- Implementation + +
+This chapter describes SWIG's support of Javascript. It does not + cover SWIG basics, but only information that is specific to this + module.
+26.1 Overview
+Javascript is a prototype-based scripting language that is dynamic, + weakly typed and has first-class functions. Its arguably the most + popular language for web development. Javascript has gone beyond being + a browser-based scripting language and with +node.js, it is also used as a backend development language.
+Native Javascript extensions can be used for applications that embed + a web-browser view or that embed a Javascript engine (such as + node.js). Extending a general purpose web-browser is not possible + as this would be a severe security issue.
+SWIG Javascript currently supports JavascriptCore, + the Javascript engine used by
+Safari/Webkit
, and +v8, which is used byChromium
and+node.js
.WebKit is a modern browser + implementation available as open-source which can be embedded into an + application. With +node-webkit there is a platform which uses Google's
+Chromium
+ as Web-Browser widget andnode.js
for javascript + extensions.26.2 Preliminaries
+26.2.1 Running SWIG
+Suppose that you defined a SWIG module such as the following:
--Butler jeeves = new Butler(); -System.out.println("Greeting: " + jeeves.getGreeting()); -System.out.println("Availability: " + jeeves.getHoursAvailable() + " hours per day"); -+%module example +%{ +#include "example.h" +%} +int gcd(int x, int y); +extern double Foo;Note that the Butler class is used just like any other Java class - and no extra coding by the user needs to be written to clear up the - underlying C memory as the finalizer will be called by the garbage - collector which in turn will call the FireButler() function. - To implement this, we use the above interface file code but remove the -javacode typemap and add the following:
-+To build a Javascript module, run SWIG using the
+-javascript
+ option and a desired target engine-jsc
,-v8
, + or-node
. The generator fornode
is + essentially delegating to thev8
generator and adds some + necessary preprocessor definitions.--// Don't expose the memory allocation/de-allocation functions -%ignore FireButler(Butler *pButler); -%ignore HireButler(Butler **ppButler); - -// Add in a custom proxy constructor and destructor -%extend Butler { - Butler() { - Butler *pButler = 0; - HireButler(&pButler); - return pButler; - } - ~Butler() { - FireButler($self); - } -} -+$ swig -javascript -jsc example.iNote that the code in %extend is using a C++ type - constructor and destructor, yet the generated code will still compile - as C code, see Adding member - functions to C structures. The C functional interface has been - completely morphed into an object-oriented interface and the Butler - class would behave much like any pure Java class and feel more natural - to Java users.
-24.10.11 - Memory management when returning references to member variables
-This example shows how to prevent premature garbage collection of - objects when the underlying C++ class returns a pointer or reference to - a member variable.
-Consider the following C++ code:
+If building a C++ extension, add the -c++ option:
++++$ swig -c++ -javascript -jsc example.i+The V8 code that SWIG generates should work with most versions from + 3.11.10 up to 3.29.14 and later.
+The API headers for V8 >= 4.3.0 define constants which SWIG can use + to determine the V8 version it is compiling for. For versions < 4.3.0, + you need to specify the V8 version when running SWIG. This is specified + as a hex constant, but the constant is read as pairs of decimal digits, + so for V8 3.25.30 use constant 0x032530. This scheme can't represent + components > 99, but this constant is only useful for V8 < 4.3.0, and + no V8 versions from that era had a component > 99. For example:
++++$ swig -c++ -javascript -v8 -DV8_VERSION=0x032530 example.i+If you're targetting V8 >= 4.3.0, you would just run swig like so:
++++$ swig -c++ -javascript -v8 example.i+This creates a C/C++ source file
+example_wrap.c
or+example_wrap.cxx
. The generated C source file contains the + low-level wrappers that need to be compiled and linked with the rest of + your C/C++ application to create an extension module.The name of the wrapper file is derived from the name of the input + file. For example, if the input file is
example.i
, the + name of the wrapper file isexample_wrap.c
. To change + this, you can use the -o option. The wrapped module will export one + function which must be called to register the module with the + Javascript interpreter. For example, if your module is named+example
the corresponding initializer for JavascriptCore would be--struct Wheel { - int size; - Wheel(int sz) : size(sz) {} -}; - -class Bike { - Wheel wheel; -public: - Bike(int val) : wheel(val) {} - Wheel& getWheel() { return wheel; } -}; -+bool example_initialize(JSGlobalContextRef context, JSObjectRef *exports)and the following usage from Java after running the code through - SWIG:
+and for v8:
-- Wheel wheel = new Bike(10).getWheel(); - System.out.println("wheel size: " + wheel.getSize()); - // Simulate a garbage collection - System.gc(); - System.runFinalization(); - System.out.println("wheel size: " + wheel.getSize()); -+void example_initialize(v8::Handle<v8::Object> exports)Don't be surprised that if the resulting output gives strange - results such as...
+Note: be aware that
+v8
has a C++ API, and thus, + the generated modules must be compiled as C++.26.2.2 Running Tests and + Examples
+The configuration for tests and examples currently supports Linux and + Mac only and not MinGW (Windows) yet.
+The default interpreter is
+node.js
as it is available on + all platforms and convenient to use.Running the examples with JavascriptCore requires
+libjavascriptcoregtk-1.0
to be installed, e.g., under Ubuntu with--wheel size: 10 -wheel size: 135019664 -+$ sudo apt-get install libjavascriptcoregtk-1.0-devWhat has happened here is the garbage collector has collected the -Bike instance as it doesn't think it is needed any more. The proxy - instance, wheel, contains a reference to memory that was - deleted when the Bike instance was collected. In order to - prevent the garbage collector from collecting the Bike - instance a reference to the Bike must be added to the -wheel instance. You can do this by adding the reference when the -getWheel() method is called using the following typemaps.
-+Running with
+V8
requireslibv8
:--%typemap(javacode) Wheel %{ - // Ensure that the GC doesn't collect any Bike instance set from Java - private Bike bikeReference; - protected void addReference(Bike bike) { - bikeReference = bike; - } -%} - -// Add a Java reference to prevent premature garbage collection and resulting use -// of dangling C++ pointer. Intended for methods that return pointers or -// references to a member variable. -%typemap(javaout) Wheel& getWheel { - long cPtr = $jnicall; - $javaclassname ret = null; - if (cPtr != 0) { - ret = new $javaclassname(cPtr, $owner); - ret.addReference(this); - } - return ret; - } -+$ sudo apt-get install libv8-devThe code in the first typemap gets added to the Wheel proxy - class. The code in the second typemap constitutes the bulk of the code - in the generated getWheel() function:
+Examples can be run using
++++$ make check-javascript-examples ENGINE=jsc++
ENGINE
can benode
,jsc
, or+v8
.The test-suite can be run using
++++$ make check-javascript-test-suite ENGINE=jsc+You can specify a specific
+V8
version for running the + examples and tests+++$ make check-javascript-examples V8_VERSION=0x032530 ENGINE=v8+26.2.3 Known Issues
+At the moment, the Javascript generators pass all tests + syntactically, i.e., the generated source code compiles. However, there + are still remaining runtime issues.
++
+- +
+Default optional arguments do not work for all targeted interpreters
+- +
+Multiple output arguments do not work for JSC
+- +
+C89 incompatibily: the JSC generator might still generate C89 + violating code
+- +
++
long long
is not supported- +
++
%native
is not supported- +
+Javascript callbacks are not supported
+- +
++
instanceOf
does not work under JSCThe primary development environment has been Linux (Ubuntu 12.04). + Windows and Mac OS X have been tested sporadically. Therefore, the + generators might have more issues on those platforms. Please report + back any problem you observe to help us improving this module quickly.
+26.3 Integration
+This chapter gives a short introduction how to use a native + Javascript extension: as a
+node.js
module, and as an + extension for an embedded Webkit.26.3.1 Creating node.js + Extensions
+To install
+node.js
you can download an installer from + their +web-site for Mac OS X and Windows. For Linux you can either build + the source yourself and runsudo checkinstall
or keep to + the (probably stone-age) packaged version. For Ubuntu there is a +PPA available.+++$ sudo add-apt-repository ppa:chris-lea/node.js +$ sudo apt-get update +$ sudo apt-get install nodejs+As
+v8
is written in C++ and comes as a C++ library it is + crucial to compile your module using the same compiler flags as used + for building v8. To make things easier,node.js
provides a + build tool callednode-gyp
.You have to install it using
+npm
:+++$ sudo npm install -g node-gyp++
node-gyp
expects a configuration file named+binding.gyp
which is basically in JSON format and conforms to the + same format that is used with Google's build-toolgyp
.
binding.gyp
:--public class Wheel { - ... - // Ensure that the GC doesn't collect any bike set from Java - private Bike bikeReference; - protected void addReference(Bike bike) { - bikeReference = bike; - } -} - -public class Bike { - ... - public Wheel getWheel() { - long cPtr = exampleJNI.Bike_getWheel(swigCPtr, this); - Wheel ret = null; - if (cPtr != 0) { - ret = new Wheel(cPtr, false); - ret.addReference(this); +{ + "targets": [ + { + "target_name": "example", + "sources": [ "example.cxx", "example_wrap.cxx" ] } - return ret; - } -} -+ ] +}Note the addReference call.
-24.10.12 Memory - management for objects passed to the C++ layer
-Managing memory can be tricky when using C++ and Java proxy classes. - The previous example shows one such case and this example looks at - memory management for a class passed to a C++ method which expects the - object to remain in scope after the function has returned. Consider the - following two C++ classes:
-+First create the wrapper using SWIG:
+--struct Element { - int value; - Element(int val) : value(val) {} -}; -class Container { - Element* element; -public: - Container() : element(0) {} - void setElement(Element* e) { element = e; } - Element* getElement() { return element; } -}; -+$ swig -javascript -node -c++ example.iand usage from C++
-+Then run
+node-gyp build
to actually create the module:-- Container container; - Element element(20); - container.setElement(&element); - cout << "element.value: " << container.getElement()->value << endl; -+$ node-gyp buildand more or less equivalent usage from Java
+This will create a
build
folder containing the native + module. To use the extension you need to 'require' it in your + Javascript source file:-- Container container = new Container(); - container.setElement(new Element(20)); - System.out.println("element value: " + container.getElement().getValue()); -+require("./build/Release/example")The C++ code will always print out 20, but the value printed out may - not be this in the Java equivalent code. In order to understand why, - consider a garbage collection occuring...
-+A more detailed explanation is given in the +Examples section.
+26.3.1.1 Troubleshooting
++
+- 'module' object has no attribute 'script_main'
+This error happens when
+gyp
is installed as a + distribution package. It seems to be outdated. Removing it resolves the + problem.-- Container container = new Container(); - container.setElement(new Element(20)); - // Simulate a garbage collection - System.gc(); - System.runFinalization(); - System.out.println("element value: " + container.getElement().getValue()); -+$ sudo apt-get remove gypThe temporary element created with new Element(20) could - get garbage collected which ultimately means the container - variable is holding a dangling pointer, thereby printing out any old - random value instead of the expected value of 20. One solution is to - add in the appropriate references in the Java layer...
+26.3.2 Embedded Webkit
+Webkit is pre-installed on Mac OS X and available as a library for + GTK.
+26.3.2.1 Mac OS X
+There is general information about programming with WebKit on +Apple Developer Documentation. Details about
+Cocoa
+ programming are not covered here.An integration of a native extension 'example' would look like this:
--public class Container { +#import "appDelegate.h" - ... +extern bool example_initialize(JSGlobalContextRef context, JSObjectRef* exports); - // Ensure that the GC doesn't collect any Element set from Java - // as the underlying C++ class stores a shallow copy - private Element elementReference; - private long getCPtrAndAddReference(Element element) { - elementReference = element; - return Element.getCPtr(element); - } - public void setElement(Element e) { - exampleJNI.Container_setElement(swigCPtr, this, getCPtrAndAddReference(e), e); +@implementation ExampleAppDelegate + +@synthesize webView; + +- (void)addGlobalObject:(JSContextRef) context:(NSString *)objectName:(JSObjectRef) theObject { + JSObjectRef global = JSContextGetGlobalObject(context); + JSStringRef objectJSName = JSStringCreateWithCFString( (CFStringRef) objectName ) + if ( objectJSName != NULL ) { + JSObjectSetProperty(context, global, objectJSName, theObject, kJSPropertyAttributeReadOnly, NULL); + JSStringRelease( objectJSName ); } } -+ +- (void)applicationDidFinishLaunching:(NSNotification *)aNotification { + + // Start a webview with the bundled index.html file + NSString *path = [[NSBundle mainBundle] bundlePath]; + NSString *url = [NSString stringWithFormat: @"file://%@/Contents/Assets/index.html", path]; + + WebFrame *webframe = [webView mainFrame]; + JSGlobalContextRef context = [webframe globalContext]; + + JSObjectRef example; + example_initialize(context, &example); + [self addGlobalObject:context:@"example":example] + + JSObjectSetProperty(context, global, JSStringRef propertyName, example, JSPropertyAttributes attributes, NULL); + + [ [webView mainFrame] loadRequest: + [NSURLRequest requestWithURL: [NSURL URLWithString:url] ] + ]; +} + +@endThe following typemaps will generate the desired code. The 'javain' - typemap matches the input parameter type for the setElement - method. The 'javacode' typemap simply adds in the specified code into - the Java proxy class.
+26.3.2.2 GTK
+There is general information about programming GTK at +GTK documentation and in the +GTK tutorial, and for Webkit there is a +Webkit GTK+ API Reference.
+An integration of a native extension 'example' would look like this:
--%typemap(javain) Element *e "getCPtrAndAddReference($javainput)" +#include <gtk/gtk.h> +#include <webkit/webkit.h> -%typemap(javacode) Container %{ - // Ensure that the GC doesn't collect any element set from Java - // as the underlying C++ class stores a shallow copy - private Element elementReference; - private long getCPtrAndAddReference(Element element) { - elementReference = element; - return Element.getCPtr(element); - } -%} -+extern bool example_initialize(JSGlobalContextRef context); + +int main(int argc, char* argv[]) +{ + // Initialize GTK+ + gtk_init(&argc, &argv); + + ... + + // Create a browser instance + WebKitWebView *webView = WEBKIT_WEB_VIEW(webkit_web_view_new()); + WebFrame *webframe = webkit_web_view_get_main_frame(webView); + JSGlobalContextRef context = webkit_web_frame_get_global_context(webFrame); + JSObjectRef global = JSContextGetGlobalObject(context); + + JSObjectRef exampleModule; + example_initialize(context, &exampleModule); + JSStringRef jsName = JSStringCreateWithUTF8CString("example"); + JSObjectSetProperty(context, global, jsName, exampleModule, kJSPropertyAttributeReadOnly, NULL); + JSStringRelease(jsName); + + ... + + // Load a web page into the browser instance + webkit_web_view_load_uri(webView, "http://www.webkitgtk.org/"); + + ... + + // Run the main GTK+ event loop + gtk_main(); + + return 0; +}24.10.13 Date marshalling using - the javain typemap and associated attributes
-The NaN Exception example - is a simple example of the "javain" typemap and its 'pre' attribute. - This example demonstrates how a C++ date class, say CDate, can - be mapped onto the standard Java date class, -java.util.GregorianCalendar by using the 'pre', 'post' and - 'pgcppname' attributes of the "javain" typemap. The idea is that the -GregorianCalendar is used wherever the C++ API uses a CDate -. Let's assume the code being wrapped is as follows:
+26.3.3 Creating + Applications with node-webkit
+To get started with
+node-webkit
there is a very + informative set of +wiki pages.Similar to
+node.js
,node-webkit
is started + from command line within anode.js
project directory. + Native extensions are created in the very same way as fornode.js
+, except that a customizedgyp
derivate has to be used: +nw-gyp.A simple example would have the following structure:
--class CDate { -public: - CDate(int year, int month, int day); - int getYear(); - int getMonth(); - int getDay(); - ... -}; -struct Action { - static int doSomething(const CDate &dateIn, CDate &dateOut); - Action(const CDate &date, CDate &dateOut); -}; +- package.json +- app.html +- app.js +- node_modules + / example + ... (as known from node.js)Note that dateIn is const and therefore read only and -dateOut is a non-const output type.
-First let's look at the code that is generated by default, where the - Java proxy class CDate is used in the proxy interface:
+The configuration file essentially conforms to
+node.js
+ syntax. It has some extras to configurenode-webkit
. See + the +Manifest specification for more details.
package.json
:--public class Action { - ... - public static int doSomething(CDate dateIn, CDate dateOut) { - return exampleJNI.Action_doSomething(CDate.getCPtr(dateIn), dateIn, - CDate.getCPtr(dateOut), dateOut); - } - - public Action(CDate date, CDate dateOut) { - this(exampleJNI.new_Action(CDate.getCPtr(date), date, - CDate.getCPtr(dateOut), dateOut), true); +{ + "name": "example", + "main": "app.html", + "window": { + "show": true, + "width": 800, + "height": 600 } -} -+}The CDate & and const CDate & Java code is - generated from the following two default typemaps:
+The
+'main'
property ofpackage.json
+ specifies a web-page to be rendered in the main window.+
app.html
:+++<html> + <head> + <script src="app.js"></script> + </head> + <body> + <div> + The greatest common divisor of + <span id="x"></span> and + <span id="y"></span> is + <span id="z"></span>. + </div> + </body> +</html>+As known from
+node.js
one can userequire
+ to load javascript modules. Additionally,node-webkit
+ provides an API that allows to manipulate the window's menu, open new + windows, and many more things.+
app.js
:++window.onload = function() { + var example = require("example"); + var x = 18; + var y = 24; + var z = example.gcd(x,y); + document.querySelector('#x').innerHTML = x; + document.querySelector('#y').innerHTML = y; + document.querySelector('#z').innerHTML = z; +};+26.4 Examples
+Some basic examples are shown here in more detail.
+26.4.1 Simple
+The common example
simple
looks like this:--%typemap(jstype) SWIGTYPE & "$javaclassname" -%typemap(javain) SWIGTYPE & "$javaclassname.getCPtr($javainput)" -+/* File : example.i */ +%module example + +%inline %{ +extern int gcd(int x, int y); +extern double Foo; +%}where '$javaclassname' is translated into the proxy class name, -CDate and '$javainput' is translated into the name of the - parameter, eg dateIn. From Java, the intention is then to call - into a modifed API with something like:
+To make this available as a node extension a
binding.gyp
+ has to be created:--java.util.GregorianCalendar calendarIn = - new java.util.GregorianCalendar(2011, java.util.Calendar.APRIL, 13, 0, 0, 0); -java.util.GregorianCalendar calendarOut = new java.util.GregorianCalendar(); - -// Note in calls below, calendarIn remains unchanged and calendarOut -// is set to a new value by the C++ call -Action.doSomething(calendarIn, calendarOut); -Action action = new Action(calendarIn, calendarOut); -+{ + "targets": [ + { + "target_name": "example", + "sources": [ "example.cxx", "example_wrap.cxx" ] + } + ] +}To achieve this mapping, we need to alter the default code - generation slightly so that at the Java layer, a GregorianCalendar - is converted into a CDate. The JNI intermediary layer will - still take a pointer to the underlying CDate class. The - typemaps to achieve this are shown below.
+Then
+node-gyp
is used to build the extension:+++$ node-gyp configure build+From a 'nodejs` application the extension would be used like this:
--%typemap(jstype) const CDate& "java.util.GregorianCalendar" -%typemap(javain, - pre=" CDate temp$javainput = new CDate($javainput.get(java.util.Calendar.YEAR), " - "$javainput.get(java.util.Calendar.MONTH), $javainput.get(java.util.Calendar.DATE));", - pgcppname="temp$javainput") const CDate & - "$javaclassname.getCPtr(temp$javainput)" +// import the extension via require +var example = require("./build/Release/example"); -%typemap(jstype) CDate& "java.util.Calendar" -%typemap(javain, - pre=" CDate temp$javainput = new CDate($javainput.get(java.util.Calendar.YEAR), " - "$javainput.get(java.util.Calendar.MONTH), $javainput.get(java.util.Calendar.DATE));", - post=" $javainput.set(temp$javainput.getYear(), temp$javainput.getMonth(), " - "temp$javainput.getDay(), 0, 0, 0);", - pgcppname="temp$javainput") CDate & - "$javaclassname.getCPtr(temp$javainput)" -+// calling the global method +var x = 42; +var y = 105; +var g = example.gcd(x,y); + +// Accessing the global variable +var f = example.Foo; +example.Foo = 3.1415926;The resulting generated proxy code in the Action class - follows:
+First the module
+example
is loaded from the previously + built extension. Global methods and variables are available in the + scope of the module.Note: ECMAScript 5, the currently implemented Javascript + standard, does not have modules.
+node.js
and other + implementations provide this mechanism defined by the +CommonJS group. For browsers this is provided by +Browserify, for instance.26.4.2 Class
+The common example
class
defines three classes,+Shape
,Circle
, andSquare
:--public class Action { - ... - public static int doSomething(java.util.GregorianCalendar dateIn, - java.util.Calendar dateOut) { - CDate tempdateIn = new CDate(dateIn.get(java.util.Calendar.YEAR), - dateIn.get(java.util.Calendar.MONTH), - dateIn.get(java.util.Calendar.DATE)); - CDate tempdateOut = new CDate(dateOut.get(java.util.Calendar.YEAR), - dateOut.get(java.util.Calendar.MONTH), - dateOut.get(java.util.Calendar.DATE)); - try { - return exampleJNI.Action_doSomething(CDate.getCPtr(tempdateIn), tempdateIn, - CDate.getCPtr(tempdateOut), tempdateOut); - } finally { - dateOut.set(tempdateOut.getYear(), tempdateOut.getMonth(), tempdateOut.getDay(), 0, 0, 0); - } +class Shape { +public: + Shape() { + nshapes++; } - - static private long SwigConstructAction(java.util.GregorianCalendar date, - java.util.Calendar dateOut) { - CDate tempdate = new CDate(date.get(java.util.Calendar.YEAR), - date.get(java.util.Calendar.MONTH), - date.get(java.util.Calendar.DATE)); - CDate tempdateOut = new CDate(dateOut.get(java.util.Calendar.YEAR), - dateOut.get(java.util.Calendar.MONTH), - dateOut.get(java.util.Calendar.DATE)); - try { - return exampleJNI.new_Action(CDate.getCPtr(tempdate), tempdate, - CDate.getCPtr(tempdateOut), tempdateOut); - } finally { - dateOut.set(tempdateOut.getYear(), tempdateOut.getMonth(), tempdateOut.getDay(), 0, 0, 0); - } + virtual ~Shape() { + nshapes--; } + double x, y; + void move(double dx, double dy); + virtual double area(void) = 0; + virtual double perimeter(void) = 0; + static int nshapes; +}; - public Action(java.util.GregorianCalendar date, java.util.Calendar dateOut) { - this(Action.SwigConstructAction(date, dateOut), true); - } -} -+class Circle : public Shape { +private: + double radius; +public: + Circle(double r) : radius(r) { } + virtual double area(void); + virtual double perimeter(void); +}; + +class Square : public Shape { +private: + double width; +public: + Square(double w) : width(w) { } + virtual double area(void); + virtual double perimeter(void); +};A few things to note:
--
-- The "javatype" typemap has changed the parameter type to -java.util.GregorianCalendar or java.util.Calendar instead - of the default generated CDate proxy.
-- The code in the 'pre' attribute appears before the JNI call ( -exampleJNI.new_Action / exampleJNI.Action_doSomething).
-- The code in the 'post' attribute appears after the JNI call.
-- A try .. finally block is generated with the JNI call in the try - block and 'post' code in the finally block. The alternative of just - using a temporary variable for the return value from the JNI call and - the 'post' code being generated before the return statement is not - possible given that the JNI call is in one line and comes from the - "javaout" typemap.
-- The temporary variables in the "javain" typemaps are called -temp$javain, where "$javain" is replaced with the parameter name. - "$javain" is used to mangle the variable name so that more than one -CDate & type can be used as a parameter in a method, otherwise two - or more local variables with the same name would be generated.
-- The use of the "javain" typemap causes a constructor helper - function (SwigConstructAction) to be generated. This allows - Java code to be called before the JNI call and is required as the Java - compiler won't compile code inserted before the 'this' call.
-- The 'pgcppname' attribute is used to modify the object being passed - as the premature garbage collection prevention - parameter (the 2nd and 4th parameters in the JNI calls).
-24.11 Living with Java Directors
-This section is intended to address frequently asked questions and - frequently encountered problems when using Java directors.
--
-- When my program starts up, it complains that method_foo - cannot be found in a Java method called swig_module_init. How do - I fix this? -
-Open up the C++ wrapper source code file and look for
--"method_foo"
(include the double quotes, they are important!) - Look at the JNI field descriptor and make sure that each class that - occurs in the descriptor has the correct package name in front of it. - If the package name is incorrect, put a "javapackage" typemap in your - SWIG interface file.- I'm compiling my code and I'm using templates. I provided a - javapackage typemap, but SWIG doesn't generate the right JNI field - descriptor. -
-Use the template's renamed name as the argument to the "javapackage" - typemap:
---%typemap(javapackage) std::vector<int> "your.package.here" -%template(VectorOfInt) std::vector<int>; --- -
-When I pass class pointers or references through a C++ upcall and - I try to type cast them, Java complains with a ClassCastException. What - am I doing wrong?
-Normally, a non-director generated Java proxy class creates - temporary Java objects as follows:
++
Circle
andSquare
inherit fromShape
+.Shape
has a static variablenshapes
, a + functionmove
that can't be overridden (non-virtual), and + two abstract functionsarea
andperimeter
+ (pure virtual) that must be overridden by the sub-classes.A
+nodejs
extension is built the same way as for the+simple
example.In Javascript it can be used as follows:
--public static void MyClass_method_upcall(MyClass self, long jarg1) -{ - Foo darg1 = new Foo(jarg1, false); +var example = require("./build/Release/example"); - self.method_upcall(darg1); -} --Unfortunately, this loses the Java type information that is part of - the underlying Foo director proxy class's Java object pointer causing - the type cast to fail. The SWIG Java module's director code attempts to - correct the problem, but only for director-enabled classes, - since the director class retains a global reference to its Java object. - Thus, for director-enabled classes and only for director-enabled - classes, the generated proxy Java code looks something like:
-+// local aliases for convenience +var Shape = example.Shape; +var Circle = example.Circle; +var Square = example.Square; + +// creating new instances using the 'new' operator +var c = new Circle(10); +var s = new Square(10); + +// accessing a static member +Shape.nshapes; + +// accessing member variables +c.x = 20; +c.y = 30; +s.x = -10; +s.y = 5; + +// calling some methods +c.area(); +c.perimeter(); +s.area(); +s.perimeter(); + +// instantiation of Shape is not permitted +new Shape(); ++Running these commands in an interactive node shell results in the + following output:
++-public static void MyClass_method_upcall(MyClass self, long jarg1, - Foo jarg1_object) -{ - Foo darg1 = (jarg1_object != null ? jarg1_object : new Foo(jarg1, false)); +$ node -i +& var example = require("./build/Release/example"); +undefined +& var Shape = example.Shape; +undefined +& var Circle = example.Circle; +undefined +& var Square = example.Square; +undefined +& var c = new Circle(10); +undefined +& var s = new Square(10); +undefined +& Shape.nshapes; +2 +& c.x = 20; +20 +& c.y = 30; +30 +& s.x = -10; +-10 +& s.y = 5; +5 +& c.area(); +314.1592653589793 +& c.perimeter(); +62.83185307179586 +& s.area(); +100 +& s.perimeter(); +40 +& c.move(40, 40) +undefined +& c.x +60 +& c.y +70 +& new Shape() +Error: Class Shape can not be instantiated +at repl:1:2 +at REPLServer.self.eval (repl.js:110:21) +at Interface.<anonymous> (repl.js:239:12) +at Interface.EventEmitter.emit (events.js:95:17) +at Interface._onLine (readline.js:202:10) +at Interface._line (readline.js:531:8) +at Interface._ttyWrite (readline.js:760:14) +at ReadStream.onkeypress (readline.js:99:10) +at ReadStream.EventEmitter.emit (events.js:98:17) +at emitKey (readline.js:1095:12)+Note: In ECMAScript 5 there is no concept for classes. + Instead each function can be used as a constructor function which is + executed by the 'new' operator. Furthermore, during construction the + key property
+prototype
of the constructor function is used + to attach a prototype instance to the created object. A prototype is + essentially an object itself that is the first-class delegate of a + class used whenever the access to a property of an object fails. The + very same prototype instance is shared among all instances of one type. + Prototypal inheritance is explained in more detail on in +Inheritance and the prototype chain, for instance.26.5 Implementation
+The Javascript Module implementation has taken a very different + approach compared to other language modules in order to support + different Javascript interpreters.
+26.5.1 Source Code
+The Javascript module is implemented in
++Source/Modules/javascript.cxx
. It dispatches the code generation + to aJSEmitter
instance,V8Emitter
or+JSCEmitter
. Additionally there are some helpers:Template
+, for templated code generation, andJSEmitterState
, which + is used to manage state information during AST traversal. This rough + map shall make it easier to find a way through this huge source file:+-+// module wide defines + +#define NAME "name" +... - self.method_upcall(darg1); -} -+// ############################### +// # Helper class declarations + +class JSEmitterState { ... }; + +class Template { ... }; + +// ############################### +// # JSEmitter declaration + +class JSEmitter { ... }; + +// Emitter factory declarations + +JSEmitter *swig_javascript_create_JSCEmitter(); +JSEmitter *swig_javascript_create_V8Emitter(); + +// ############################### +// # Javascript module + +// Javascript module declaration + +class JAVASCRIPT:public Language { ... }; + +// Javascript module implementation + +int JAVASCRIPT::functionWrapper(Node *n) { ... } +... + +// Module factory implementation + +static Language *new_swig_javascript() { ... } + +extern "C" Language *swig_javascript(void) { ... } + +// ############################### +// # JSEmitter base implementation + +JSEmitter::JSEmitter() { ... } + +Template JSEmitter::getTemplate(const String *name) { ... } +... + +// ############################### +// # JSCEmitter + +// JSCEmitter declaration + +class JSCEmitter: public JSEmitter { ... }; + +// JSCEmitter implementation + +JSCEmitter::JSCEmitter() { ... } + +void JSCEmitter::marshalInputArgs(Node *n, ParmList *parms, Wrapper *wrapper, MarshallingMode mode, bool is_member, bool is_static) { ... } +... + +// JSCEmitter factory + +JSEmitter *swig_javascript_create_JSCEmitter() { ... } + + +// ############################### +// # V8Emitter + +// V8Emitter declaration + +class V8Emitter: public JSEmitter { ... }; + +// V8Emitter implementation + +V8Emitter::V8Emitter() { ... } + +int V8Emitter::initialize(Node *n) { ... } + +// V8Emitter factory + +JSEmitter *swig_javascript_create_V8Emitter() { ... } + + +// ############################### +// # Helper implementation (JSEmitterState, Template) + +JSEmitterState::JSEmitterState() { ... } +... + +Template::Template(const String *code_) { ... } +...When you import a SWIG interface file containing class definitions, - the classes you want to be director-enabled must be have the
--feature("director")
enabled for type symmetry to work. This - applies even when the class being wrapped isn't a director-enabled - class but takes parameters that are director-enabled classes.The current "type symmetry" design will work for simple C++ - inheritance, but will most likely fail for anything more complicated - such as tree or diamond C++ inheritance hierarchies. Those who are - interested in challenging problems are more than welcome to hack the
--Java::Java_director_declaration
method in-Source/Modules/java.cxx
.If all else fails, you can use the downcastXXXXX() method to attempt - to recover the director class's Java object pointer. For the Java Foo - proxy class, the Foo director class's java object pointer can be - accessed through the javaObjectFoo() method. The generated method's - signature is:
-++26.5.2 Code Templates
+All generated code is created on the basis of code templates. The + templates for JavascriptCore can be found in
++Lib/javascript/jsc/javascriptcode.swg
, for v8 in+Lib/javascript/v8/javascriptcode.swg
.To track the originating code template for generated code you can run
+-- public static Foo javaObjectFoo(Foo obj); -+$ swig -javascript -jsc -debug-codetemplatesFrom your code, this method is invoked as follows:
+which wraps generated code with a descriptive comment
--public class MyClassDerived { - public void method_upcall(Foo foo_object) - { - FooDerived derived = (foo_object != null ? - (FooDerived) Foo.downcastFoo(foo_object) : null); - /* rest of your code here */ - } -} -+/* begin fragment("template_name") */ + +...generated code ... + +/* end fragment("template_name") */An good approach for managing downcasting is placing a static method - in each derived class that performs the downcast from the superclass, - e.g.,
+The Template class is used like this:
--public class FooDerived extends Foo { - /* ... */ - public static FooDerived downcastFooDerived(Foo foo_object) - { - try { - return (foo_object != null ? (FooDerived) Foo.downcastFoo(foo_object); - } - - catch (ClassCastException exc) { - // Wasn't a FooDerived object, some other subclass of Foo - return null; - } - } -} -+Template t_register = getTemplate("jsv8_register_static_variable"); +t_register.replace("$jsparent", state.clazz(NAME_MANGLED)) + .replace("$jsname", state.variable(NAME)) + .replace("$jsgetter", state.variable(GETTER)) + .replace("$jssetter", state.variable(SETTER)) + .trim(). + print(f_init_static_wrappers);Then change the code in MyClassDerived as follows:
+A code template is registered with the JSEmitter via
+fragment(name, "template")
, e.g.,--public class MyClassDerived extends MyClass { - /* ... */ - public void method_upcall(Foo foo_object) - { - FooDerived derived = FooDerived.downcastFooDerived(foo_object); - /* rest of your code here */ - } -} --- -
Why isn't the proxy class declared abstract? Why aren't the - director upcall methods in the proxy class declared abstract?
-Declaring the proxy class and its methods abstract would break the - JNI argument marshalling and SWIG's downcall functionality (going from - Java to C++.) Create an abstract Java subclass that inherits from the - director-enabled class instead. Using the previous Foo class example:
+%fragment ("jsc_variable_declaration", "templates") +%{ + {"$jsname", $jsgetter, $jssetter, kJSPropertyAttributeNone}, +%} ++
Template
creates a copy of that string and+Template::replace
uses Swig'sReplaceall
to replace + variables in the template.Template::trim
can be used to + eliminate leading and trailing whitespaces.Template::print
+ is used to write the final template string to a SwigDOH
+ (based onPrintv
). All methods allow chaining.26.5.3 Emitter
+The Javascript module delegates code generation to a
JSEmitter
+ instance. The following extract shows the essential interface:--public abstract class UserVisibleFoo extends Foo { - /** Make sure user overrides this method, it's where the upcall - * happens. +class JSEmitter { + ... + + /** + * Opens output files and temporary output DOHs. */ - public abstract void method_upcall(Foo foo_object); + virtual int initialize(Node *n); - /// Downcast from Foo to UserVisibleFoo - public static UserVisibleFoo downcastUserVisibleFoo(Foo foo_object) - { - try { - return (foo_object != null ? (FooDerived) Foo.downcastFoo(foo_object) : null); - } + /** + * Writes all collected code into the output file(s). + */ + virtual int dump(Node *n) = 0; - catch (ClassCastException exc) { - // Wasn't a FooDerived object, some other subclass of Foo - return null; - } + /** + * Cleans up all open output DOHs. + */ + virtual int close() = 0; + + ... + + /** + * Invoked at the beginning of the classHandler. + */ + virtual int enterClass(Node *); + + /** + * Invoked at the end of the classHandler. + */ + virtual int exitClass(Node *) { + return SWIG_OK; } -} --This doesn't prevent the user from creating subclasses derived from - Foo, however, UserVisibleFoo provides the safety net that reminds the - user to override the
-method_upcall()
method.24.12 Odds and ends
-24.12.1 JavaDoc comments
-The SWIG documentation system is currently deprecated. When it is - resurrected JavaDoc comments will be fully supported. If you can't wait - for the full documentation system a couple of workarounds are - available. The %javamethodmodifiers feature can be used for - adding proxy class method comments and module class method comments. - The "javaimports" typemap can be hijacked for adding in proxy class - JavaDoc comments. The jniclassimports or -jniclassclassmodifiers pragmas can also be used for adding - intermediary JNI class comments and likewise the moduleimports - or moduleclassmodifiers pragmas for the module class. Here is - an example adding in a proxy class and method comment:
----%javamethodmodifiers Barmy::lose_marbles() " + /** - * Calling this method will make you mad. - * Use with <b>utmost</b> caution. - */ - public"; + * Invoked at the beginning of the variableHandler. + */ + virtual int enterVariable(Node *); -%typemap(javaimports) Barmy " -/** The crazy class. Use as a last resort. */" + /** + * Invoked at the end of the variableHandler. + */ + virtual int exitVariable(Node *) { + return SWIG_OK; + } -class Barmy { -public: - void lose_marbles() {} -}; --Note the "public" added at the end of the %javamethodmodifiers - as this is the default for this feature. The generated proxy class with - JavaDoc comments is then as follows:
----/** The crazy class. Use as a last resort. */ -public class Barmy { -... /** - * Calling this method will make you mad. - * Use with <b>utmost</b> caution. - */ - public void lose_marbles() { - ... + * Invoked at the beginning of the functionHandler. + */ + virtual int enterFunction(Node *); + + /** + * Invoked at the end of the functionHandler. + */ + virtual int exitFunction(Node *) { + return SWIG_OK; } -... -} --24.12.2 Functional interface - without proxy classes
-It is possible to run SWIG in a mode that does not produce proxy - classes by using the -noproxy commandline option. The interface is - rather primitive when wrapping structures or classes and is accessed - through function calls to the module class. All the functions in the - module class are wrapped by functions with identical names as those in - the intermediary JNI class.
-Consider the example we looked at when examining proxy classes:
----class Foo { -public: - int x; - int spam(int num, Foo* foo); -}; -+ + /** + * Invoked by functionWrapper callback after call to Language::functionWrapper. + */ + virtual int emitWrapperFunction(Node *n); + + /** + * Invoked from constantWrapper after call to Language::constantWrapper. + **/ + virtual int emitConstant(Node *n); + + /** + * Registers a given code snippet for a given key name. + * + * This method is called by the fragmentDirective handler + * of the JAVASCRIPT language module. + **/ + int registerTemplate(const String *name, const String *code); + + /** + * Retrieve the code template registered for a given name. + */ + Template getTemplate(const String *name); + + State &getState(); + + ... + +}When using -noproxy, type wrapper classes are generated - instead of proxy classes. Access to all the functions and variables is - through a C like set of functions where the first parameter passed is - the pointer to the class, that is an instance of a type wrapper class. - Here is what the module class looks like:
+The module calls
initialize
,dump
, and+close
from within thetop
method:--public class example { - public static void Foo_x_get(SWIGTYPE_p_Foo self, int x) {...} - public static int Foo_x_get(SWIGTYPE_p_Foo self) {...} - public static int Foo_spam(SWIGTYPE_p_Foo self, int num, SWIGTYPE_p_Foo foo) {...} - public static SWIGTYPE_p_Foo new_Foo() {...} - public static void delete_Foo(SWIGTYPE_p_Foo self) {...} -} -+int JAVASCRIPT::top(Node *n) { + emitter->initialize(n); + + Language::top(n); + + emitter->dump(n); + emitter->close(); + + return SWIG_OK; +}This approach is not nearly as natural as using proxy classes as the - functions need to be used like this:
+The methods
enterClass
andexitClass
are + called from within theclassHandler
method:--SWIGTYPE_p_Foo foo = example.new_Foo(); -example.Foo_x_set(foo, 10); -int var = example.Foo_x_get(foo); -example.Foo_spam(foo, 20, foo); -example.delete_Foo(foo); -+int JAVASCRIPT::classHandler(Node *n) { + + emitter->enterClass(n); + Language::classHandler(n); + emitter->exitClass(n); + + return SWIG_OK; +}Unlike proxy classes, there is no attempt at tracking memory. All - destructors have to be called manually for example the -delete_Foo(foo) call above.
-24.12.3 Using your own - JNI functions
-You may have some hand written JNI functions that you want to use in - addition to the SWIG generated JNI functions. Adding these to your SWIG - generated package is possible using the %native directive. If - you don't want SWIG to wrap your JNI function then of course you can - simply use the %ignore directive. However, if you want SWIG to - generate just the Java code for a JNI function then use the %native - directive. The C types for the parameters and return type must be - specified in place of the JNI types and the function name must be the - native method name. For example:
+In
+enterClass
the emitter stores state information that + is necessary when processing class members. InexitClass
+ the wrapper code for the whole class is generated.26.5.4 Emitter states
+For storing information during the AST traversal the emitter provides + a
JSEmitterState
with different slots to store data + representing the scopes global, class, function, and variable.--%native (HandRolled) void HandRolled(int, char *); -%{ -JNIEXPORT void JNICALL Java_packageName_moduleName_HandRolled(JNIEnv *, jclass, - jlong, jstring); -%} -+class JSEmitterState { + +public: + + JSEmitterState(); + + ~JSEmitterState(); + + DOH *global(); + + DOH *global(const char* key, DOH *initial = 0); + + DOH *clazz(bool reset = false); + + DOH *clazz(const char* key, DOH *initial = 0); + + DOH *function(bool reset = false); + + DOH *function(const char* key, DOH *initial = 0); + + DOH *variable(bool reset = false); + + DOH *variable(const char* key, DOH *initial = 0); + + static int IsSet(DOH *val); + + ... +};No C JNI function will be generated and the -Java_packageName_moduleName_HandRolled function will be accessible - using the SWIG generated Java native method call in the intermediary - JNI class which will look like this:
+When entering a scope, such as in
enterClass
, the + corresponding state is reset and new data is stored:-- public final static native void HandRolled(int jarg1, String jarg2); -+state.clazz(RESET); +state.clazz(NAME, Getattr(n, "sym:name"));and as usual this function is wrapped by another which for a global - C function would appear in the module class:
+State information can be retrieved using
+state.clazz(NAME)
+ or withGetattr
onstate.clazz()
which + actually returns aHash
instance.26.5.5 Handling Exceptions in + JavascriptCore
+Applications with an embedded JavascriptCore should be able to + present detailed exception messages that occur in the Javascript + engine. Below is an example derived from code provided by Brian Barnes + on how these exception details can be extracted.
-- public static void HandRolled(int arg0, String arg1) { - exampleJNI.HandRolled(arg0, arg1); +void script_exception_to_string(JSContextRef js_context,JSValueRef exception_value_ref,char* return_error_string, int return_error_string_max_length) +{ + JSObjectRef exception_object; + JSValueRef value_ref; + JSStringRef jsstring_property_name = NULL; + JSValueRef temporary_exception = NULL; + JSStringRef js_return_string = NULL; + size_t bytes_needed; + char* c_result_string = NULL; + exception_object = JSValueToObject(js_context, exception_value_ref, NULL); + + /* source url */ + strcpy(return_error_string,"["); + jsstring_property_name = JSStringCreateWithUTF8CString("sourceURL"); + value_ref = JSObjectGetProperty(js_context, exception_object, jsstring_property_name, &temporary_exception); + JSStringRelease(jsstring_property_name); + js_return_string = JSValueToStringCopy(js_context, value_ref, NULL); + bytes_needed = JSStringGetMaximumUTF8CStringSize(js_return_string); + c_result_string = (char*)calloc(bytes_needed, sizeof(char)); + JSStringGetUTF8CString(js_return_string, c_result_string, bytes_needed); + JSStringRelease(js_return_string); + strncat(return_error_string, c_result_string, return_error_string_max_length-1); + free(c_result_string); + + strncat(return_error_string, ":", return_error_string_max_length-1); + + /* line number */ + + jsstring_property_name = JSStringCreateWithUTF8CString("line"); + value_ref = JSObjectGetProperty(js_context, exception_object, jsstring_property_name, &temporary_exception); + JSStringRelease(jsstring_property_name); + js_return_string = JSValueToStringCopy(js_context, value_ref, NULL); + bytes_needed = JSStringGetMaximumUTF8CStringSize(js_return_string); + c_result_string = (char*)calloc(bytes_needed, sizeof(char)); + JSStringGetUTF8CString(js_return_string, c_result_string, bytes_needed); + JSStringRelease(js_return_string); + strncat(return_error_string, c_result_string, return_error_string_max_length-1); + free(c_result_string); + + strncat(return_error_string, "]", return_error_string_max_length-1); + + /* error message */ + + jsstring_property_name = JSStringCreateWithUTF8CString("message"); + value_ref = JSObjectGetProperty(js_context, exception_object, jsstring_property_name, &temporary_exception); + JSStringRelease(jsstring_property_name); + if(NULL == value_ref) + { + strncat(return_error_string, "Unknown Error", return_error_string_max_length-1); } -+ else + { + js_return_string = JSValueToStringCopy(js_context, value_ref, NULL); + bytes_needed = JSStringGetMaximumUTF8CStringSize(js_return_string); + c_result_string = (char*)calloc(bytes_needed, sizeof(char)); + JSStringGetUTF8CString(js_return_string, c_result_string, bytes_needed); + JSStringRelease(js_return_string); + strncat(return_error_string, c_result_string, return_error_string_max_length-1); + free(c_result_string); + } +}The packageName and moduleName must of course be - correct else you will get linker errors when the JVM dynamically loads - the JNI function. You may have to add in some "jtype", "jstype", - "javain" and "javaout" typemaps when wrapping some JNI types. Here the - default typemaps work for int and char *.
-In summary the %native directive is telling SWIG to - generate the Java code to access the JNI C code, but not the JNI C - function itself. This directive is only really useful if you want to - mix your own hand crafted JNI code and the SWIG generated code into one - Java class or package.
-24.12.4 Performance concerns and - hints
-If you're directly manipulating huge arrays of complex objects from - Java, performance may suffer greatly when using the array functions in -arrays_java.i. Try and minimise the expensive JNI calls to C/C++ - functions, perhaps by using temporary Java variables instead of - accessing the information directly from the C/C++ object.
-Java classes without any finalizers generally speed up code - execution as there is less for the garbage collector to do. Finalizer - generation can be stopped by using an empty javafinalize - typemap:
+It would be used in the following way:
--%typemap(javafinalize) SWIGTYPE "" --However, you will have to be careful about memory management and - make sure that you code in a call to the delete() member - function. This method normally calls the C++ destructor or free() - for C code.
-24.12.5 Debugging
-The generated code can be debugged using both a Java debugger and a - C++ debugger using the usual debugging techniques. Breakpoints can be - set in either Java or C++ code and so both can be debugged - simultaneously. Most debuggers do not understand both Java and C++, - with one noteable exception of Sun Studio, where it is possible to step - from Java code into a JNI method within one environment.
-Alternatively, debugging can involve placing debug printout - statements in the JNI layer using the %exception directive. - See the special - variables for %exception section. Many of the default typemaps can - also be overidden and modified for adding in extra logging/debug - display information.
-The -Xcheck:jni and -Xcheck:nabounds Java - executable options are useful for debugging to make sure the JNI code - is behaving. The -verbose:jni and -verbose:gc are also useful options - for monitoring code behaviour.
-24.13 Java Examples
-The directory Examples/java has a number of further examples. Take a - look at these if you want to see some of the techniques described in - action. The Examples/index.html file in the parent directory contains - the SWIG Examples Documentation and is a useful starting point. If your - SWIG installation went well Unix users should be able to type make - in each example directory, then java main to see them running. - For the benefit of Windows users, there are also Visual C++ project - files in a couple of the Windows Examples -. There are also many regression tests in the Examples/test-suite - directory. Many of these have runtime tests in the java subdirectory.
-
-25 SWIG and Common Lisp
+if(js_exception) +{ + char return_error_string[256]; + script_exception_to_string(js_context, js_exception, return_error_string, 256); + printf("Compile error is %s", return_error_string); +} +
+27 SWIG and Common Lisp
@@ -32709,11 +36644,11 @@ arrays_java.i. Try and minimise the expensive JNI calls to C/C++ foreign function interfaces. SWIG currently supports only the Allegro Common Lisp, Common Foreign Function Interface(CFFI), CLisp and UFFI foreign function interfaces. -25.1 Allegro Common Lisp
+27.1 Allegro Common Lisp
Allegro Common Lisp support in SWIG has been updated to include support for both C and C++. You can read about the interface here
-25.2 Common Foreign Function Interface(CFFI)
+27.2 Common Foreign Function Interface(CFFI)
CFFI, the Common Foreign Function Interface, is a portable foreign function interface for ANSI Common Lisp systems, similar in spirit to UFFI. Unlike UFFI, CFFI requires only a small set of low-level @@ -32731,7 +36666,7 @@ swig -cffi -module module-name file-name
But a better was of using all the power of SWIG is to write SWIG interface files. Below we will explain how to write interface files and the various things which you can do with them.
-25.2.1 Additional Commandline Options
+27.2.1 Additional Commandline Options
The following table list the additional commandline options available for the CLISP module. They can also be seen by using:
@@ -32754,9 +36689,9 @@ swig -cffi -help wrappers. These macros, functions may still be used by generated wrapper code.25.2.2 Generating CFFI bindings
+27.2.2 Generating CFFI bindings
As we mentioned earlier the ideal way to use SWIG is to use interface - files. To illustrate the use of it, lets assume that we have a file + files. To illustrate the use of it, let's assume that we have a file named test.h with the following C code:#define y 5 @@ -32849,19 +36784,19 @@ enum color { RED, BLUE, GREEN}; (cl:defconstant x (cl:ash 5 -1)) (cffi:defcstruct bar - (p :short) - (q :short) - (a :char) - (b :char) - (z :pointer) - (n :pointer)) + (p :short) + (q :short) + (a :char) + (b :char) + (z :pointer) + (n :pointer)) (cffi:defcvar ("my_struct" my_struct) :pointer) (cffi:defcstruct foo - (a :int) - (b :pointer)) + (a :int) + (b :pointer)) (cffi:defcfun ("pointer_func" pointer_func) :int (ClosureFun :pointer) @@ -32877,9 +36812,9 @@ enum color { RED, BLUE, GREEN}; (array :pointer)) (cffi:defcenum color - :RED - :BLUE - :GREEN) + :RED + :BLUE + :GREEN)The SWIG wrapper code refers to the special code which SWIG @@ -32907,9 +36842,11 @@ feature directive. Let's edit the interface file such that the C %feature("export"); %feature("inline") lispsort_double; - %feature("intern_function", "my-lispify") lispsort_double; +%feature("export", package="'some-other-package") lispsort_double; + %rename func123 renamed_cool_func; + %ignore "pointer_func"; %include "test.h" @@ -32929,11 +36866,13 @@ feature directive. Let's edit the interface file such that the C %feature("intern_function", "my-lispify") lispsort_double;, here we are using an additional feature which allows us to use our lispify function.
-The export feature allows us to export the symbols. The - inline feature declaims the declared function as inline. The - rename directive allows us to change the name(it is useful when - generating C wrapper code for handling overloaded functions). The - ignore directive ignores a certain declaration.
+The export feature allows us to export the symbols. If the + package argument is given, then the symbol will be exported to the + specified Lisp package. The inline feature declaims the declared + function as inline. The rename directive allows us to change the + name(it is useful when generating C wrapper code for handling + overloaded functions). The ignore directive ignores a certain + declaration.
There are several other things which are possible, to see some example of usage of SWIG look at the Lispbuilder and wxCL projects. The generated code with 'noswig-lisp' option is:
@@ -32948,12 +36887,12 @@ feature directive. Let's edit the interface file such that the C (cl:export '#.(swig-lispify "x" 'constant)) (cffi:defcstruct #.(swig-lispify "bar" 'classname) - (#.(swig-lispify "p" 'slotname) :short) - (#.(swig-lispify "q" 'slotname) :short) - (#.(swig-lispify "a" 'slotname) :char) - (#.(swig-lispify "b" 'slotname) :char) - (#.(swig-lispify "z" 'slotname) :pointer) - (#.(swig-lispify "n" 'slotname) :pointer)) + (#.(swig-lispify "p" 'slotname) :short) + (#.(swig-lispify "q" 'slotname) :short) + (#.(swig-lispify "a" 'slotname) :char) + (#.(swig-lispify "b" 'slotname) :char) + (#.(swig-lispify "z" 'slotname) :pointer) + (#.(swig-lispify "n" 'slotname) :pointer)) (cl:export '#.(swig-lispify "bar" 'classname)) @@ -32975,8 +36914,8 @@ feature directive. Let's edit the interface file such that the C (cl:export '#.(swig-lispify "my_struct" 'variable)) (cffi:defcstruct #.(swig-lispify "foo" 'classname) - (#.(swig-lispify "a" 'slotname) :int) - (#.(swig-lispify "b" 'slotname) :pointer)) + (#.(swig-lispify "a" 'slotname) :int) + (#.(swig-lispify "b" 'slotname) :pointer)) (cl:export '#.(swig-lispify "foo" 'classname)) @@ -32997,18 +36936,18 @@ feature directive. Let's edit the interface file such that the C (n :int) (array :pointer)) -(cl:export '#.(my-lispify "lispsort_double" 'function)) +(cl:export '#.(my-lispify "lispsort_double" 'function) 'some-other-package) (cffi:defcenum #.(swig-lispify "color" 'enumname) - #.(swig-lispify "RED" 'enumvalue :keyword) - #.(swig-lispify "BLUE" 'enumvalue :keyword) - #.(swig-lispify "GREEN" 'enumvalue :keyword)) + #.(swig-lispify "RED" 'enumvalue :keyword) + #.(swig-lispify "BLUE" 'enumvalue :keyword) + #.(swig-lispify "GREEN" 'enumvalue :keyword)) (cl:export '#.(swig-lispify "color" 'enumname))25.2.3 Generating CFFI bindings for C++ code
+27.2.3 Generating CFFI bindings for C++ code
This feature to SWIG (for CFFI) is very new and still far from complete. Pitch in with your patches, bug reports and feature requests to improve it.
@@ -33175,8 +37114,8 @@ namespace OpenDemo {If you have any questions, suggestions, patches, etc., related to CFFI module feel free to contact us on the SWIG mailing list, and also please add a "[CFFI]" tag in the subject line.
-25.2.4 Inserting user code into generated - files
+27.2.4 Inserting user code into generated files +
It is often necessary to include user-defined code into the automatically generated interface files. For example, when building a C++ interface, example_wrap.cxx will likely not compile @@ -33205,7 +37144,7 @@ int fact(int n);
Note that the block %{ ... %} is effectively a shortcut for %insert("header") %{ ... %}.
-25.3 CLISP
+27.3 CLISP
CLISP is a feature-loaded implementation of common lisp which is portable across most of the operating system environments and hardware. CLISP includes an @@ -33227,7 +37166,7 @@ swig -clisp -module module-name file-name modify them. The good thing is that you don't need to complex interface file for the CLISP module. The CLISP module tries to produce code which is both human readable and easily modifyable.
-25.3.1 Additional Commandline Options
+27.3.1 Additional Commandline Options
The following table list the additional commandline options available for the CLISP module. They can also be seen by using:
@@ -33246,7 +37185,7 @@ swig -clisp -help def-c-type will be used to generate
shortcuts according to the typedefs in the input.
As mentioned earlier the CLISP bindings generated by SWIG may need some modifications. The clisp module creates a lisp file with the same name as the module name. This lisp file contains a 'defpackage' @@ -33304,18 +37243,18 @@ void test123(float x , double y); (ffi:def-call-out pointer_func (:name "pointer_func") (:arguments (ClosureFun (ffi:c-function (:arguments (arg0 (ffi:c-pointer NIL)) - (arg1 (ffi:c-pointer NIL)) - (arg2 (ffi:c-pointer NIL))) - (:return-type NIL))) - (y ffi:int)) + (arg1 (ffi:c-pointer NIL)) + (arg2 (ffi:c-pointer NIL))) + (:return-type NIL))) + (y ffi:int)) (:return-type ffi:int) (:library +library-name+)) (ffi:def-call-out func123 (:name "func123") (:arguments (x (ffi:c-pointer div_t)) - (z (ffi:c-ptr (ffi:c-array (ffi:c-ptr (ffi:c-ptr ffi:int)) 100))) - (y (ffi:c-ptr (ffi:c-ptr (ffi:c-array ffi:int (1000 10)))))) + (z (ffi:c-ptr (ffi:c-array (ffi:c-ptr (ffi:c-ptr ffi:int)) 100))) + (y (ffi:c-ptr (ffi:c-ptr (ffi:c-array ffi:int (1000 10)))))) (:return-type ffi:int) (:library +library-name+)) @@ -33323,14 +37262,14 @@ void test123(float x , double y); (ffi:def-call-out lispsort_double (:name "lispsort_double") (:arguments (n ffi:int) - (array (ffi:c-ptr DOUBLE-FLOAT))) + (array (ffi:c-ptr DOUBLE-FLOAT))) (:return-type NIL) (:library +library-name+)) (ffi:def-call-out test123 (:name "test") (:arguments (x SINGLE-FLOAT) - (y DOUBLE-FLOAT)) + (y DOUBLE-FLOAT)) (:return-type NIL) (:library +library-name+)) @@ -33364,9 +37303,9 @@ struct bar { -
The current SWIG implementation is designed to work with Lua 5.0.x, 5.1.x and 5.2.x. It should work with later versions of Lua, but certainly not with Lua 4.0 due to substantial API changes. It is possible to either static link or dynamic link a Lua module into the interpreter (normally Lua static links its libraries, as dynamic - linking is not available on all platforms). SWIG also supports eLua and - works with eLua 0.8. SWIG generated code for eLua has been tested on - Stellaris ARM Cortex-M3 LM3S and Infineon TriCore.
-Suppose that you defined a SWIG module such as the following:
@@ -33515,7 +37467,7 @@ $ swig -lua -eluac example.i is a catch though: Metatables are not generated with -eluac. To access any value from eLua, one must directly call the wrapper function associated with that value. -26.2.1 Additional command line options
+28.2.1 Additional command line options
The following table list the additional commandline options available for the Lua module. They can also be seen by using:
@@ -33531,8 +37483,15 @@ swig -lua -help for elua.-+ -nomoduleglobal Do not register the module name as a global variable but return the module table from calls to require. + -no-old-metatable-bindings Disable backward + compatibility: old-style binding names generations and a few other + things. Explanations are included in appropriate later sections. - -squash-bases Squashes symbols from all inheritance tree + of a given class into itself. Emulates pre-SWIG3.0 inheritance. + Insignificantly speeds things up, but increases memory consumption. +26.2.2 Compiling and Linking and Interpreter
+28.2.2 Compiling and Linking and Interpreter
Normally Lua is embedded into another program and will be statically linked. An extremely simple stand-alone interpreter (min.c) is given below:
@@ -33554,8 +37513,8 @@ int main(int argc,char* argv[]) return 0; } L=lua_open(); - luaopen_base(L); // load basic libs (eg. print) - luaopen_example(L); // load the wrapped module + luaopen_base(L); // load basic libs (eg. print) + luaopen_example(L); // load the wrapped module if (luaL_loadfile(L,argv[1])==0) // load and run the file lua_pcall(L,0,0,0); else @@ -33607,7 +37566,7 @@ LUALIB_API int ( luaopen_mod )(lua_State *L );More information on building and configuring eLua can be found here: http://www.eluaproject.net/doc/v0.8/en_building.html
-26.2.3 Compiling a dynamic module
+28.2.3 Compiling a dynamic module
Most, but not all platforms support the dynamic loading of modules (Windows & Linux do). Refer to the Lua manual to determine if your platform supports it. For compiling a dynamically loaded module the @@ -33617,8 +37576,8 @@ http://www.eluaproject.net/doc/v0.8/en_building.html
@@ -33684,7 +37643,7 @@ print(a,b,c)$ swig -lua example.i -o example_wrap.c -$ gcc -I/usr/include/lua -c example_wrap.c -o example_wrap.o -$ gcc -c example.c -o example.o +$ gcc -fPIC -I/usr/include/lua -c example_wrap.c -o example_wrap.o +$ gcc -fPIC -c example.c -o example.o $ gcc -shared -I/usr/include/lua -L/usr/lib/lua example_wrap.o example.o -o example.so
'loadlib' not installed/supported
Is quite obvious (Go back and consult the Lua documents on how to enable loadlib for your platform). -26.2.4 Using your module
+28.2.4 Using your module
Assuming all goes well, you will be able to this:
-@@ -33699,17 +37658,17 @@ $ ./my_lua >26.3 A tour of basic C/C++ wrapping
+28.3 A tour of basic C/C++ wrapping
By default, SWIG tries to build a very natural Lua interface to your C/C++ code. This section briefly covers the essential aspects of this wrapping.
-26.3.1 Modules
+28.3.1 Modules
The SWIG module directive specifies the name of the Lua module. If you specify `module example', then everything is wrapped into a Lua table 'example' containing all the functions and variables. When choosing a module name, make sure you don't use the same name as a built-in Lua command or standard module name.
-26.3.2 Functions
+28.3.2 Functions
Global functions are wrapped as new Lua built-in functions. For example,
@@ -33726,11 +37685,13 @@ int fact(int n); >-To avoid name collisions, SWIG create a Lua table which it keeps all - the functions and global variables in. It is possible to copy the - functions out of this and into the global environment with the +
To avoid name collisions, SWIG create a Lua table which keeps all + the functions, constants, classes and global variables in. It is + possible to copy the functions, constants and classes (but not + variables) out of this and into the global environment with the following code. This can easily overwrite existing functions, so this - must be used with care.
+ must be used with care. This option is considered deprecated and will + be removed in the near future.-> for k,v in pairs(example) do _G[k]=v end @@ -33749,7 +37710,7 @@ int fact(int n);2426.3.3 Global variables
+28.3.3 Global variables
Global variables (which are linked to C code) are supported, and appear to be just another variable in Lua. However the actual mechanism is more complex. Given a global variable:
@@ -33851,7 +37812,7 @@ nilIn general, functions of the form "variable_get()" and "variable_set()" are automatically generated by SWIG for use with -eluac.
-26.3.4 Constants and enums
+28.3.4 Constants and enums
Because Lua doesn't really have the concept of constants, C/C++ constants are not really constant in Lua. They are actually just a copy of the value into the Lua interpreter. Therefore they can be changed @@ -33894,7 +37855,65 @@ example.SUNDAY=0 Hello World
26.3.5 Pointers
+28.3.4.1 Constants/enums and classes/structures +
+Enums are exported into a class table. For example, given some + enums:
+++%module example +enum Days { SUNDAY = 0, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }; +struct Test { + enum { TEST1 = 10, TEST2 = 20 }; +#ifdef __cplusplus // There are no static members in C + static const int ICONST = 12; +#endif +}; ++There is a slight difference in behaviour wrapping C and C++ code + due to the different scoping rules of C and C++. The wrapped C++ code + is used as follows from Lua code:
++++> print(example.SUNDAY) +0 +> print(example.Test.TEST1) +10 +> print(example.Test.ICONST) +12 ++Enums within a C struct are in the global namespace and are used as + follows from Lua
++++> print(example.SUNDAY) +0 +> -- See the difference here +> print(example.TEST1) +10 ++Compatibility Note: Versions of SWIG prior to SWIG-3.0.0 did + not generate the class table members above. There is no change in the C + wrappers, but the following code was the only way to access these + constants/enums when wrapping C++ member constants:
++++> print(example.Test_TEST1) +10 +> print(example.Test_ICONST) +12 ++The old-style bindings are still generated in addition to the new + ones. If the -no-old-metatable-bindings option is used, then + these old-style bindings are not generated.
+It is worth mentioning, that example.Test.TEST1 and +example.Test_TEST1 are different entities and changing one does not + change the other. Given the fact that these are constantes and they are + not supposed to be changed, it is up to you to avoid such issues.
+28.3.5 Pointers
C/C++ pointers are fully supported by SWIG. Furthermore, SWIG has no problem working with incomplete type information. Given a wrapping of the <file.h> interface:
@@ -33943,7 +37962,7 @@ FILE * -- it's a FILE* nil
If you wrap a C structure, it is also mapped to a Lua userdata. By adding a metatable to the userdata, this provides a very natural interface. For example,
@@ -33966,8 +37985,9 @@ nil Similar access is provided for unions and the data members of C++
classes.
-
C structures are created using a function new_Point(), but
- for C++ classes are created using just the name Point().
If you print out the value of p in the above example, you will see something like this:
C++ classes are wrapped by a Lua userdata as well. For example, if you have this class,
In Lua, the static members can be accessed as follows:
+In Lua, C++ static members can be accessed as follows:
-> example.Spam_foo() -- calling Spam::foo() -> a=example.Spam_bar -- reading Spam::bar -> example.Spam_bar=b -- writing to Spam::bar +> example.Spam.foo() -- calling Spam::foo() +> a=example.Spam.bar -- reading Spam::bar +> example.Spam.bar=b -- writing to Spam::bar
It is not (currently) possible to access static members of an @@ -34124,7 +38144,19 @@ public: -- does NOT work
Compatibility Note: In versions prior to SWIG-3.0.0 only the + following names would work:
++> example.Spam_foo() -- calling Spam::foo() +> a=example.Spam_bar -- reading Spam::bar +> example.Spam_bar=b -- writing to Spam::bar ++
Both style names are generated by default now. However, if the +-no-old-metatable-bindings option is used, then the backward + compatible names are not generated in addition to ordinary ones.
+SWIG is fully aware of issues related to C++ inheritance. Therefore, if you have classes like this
then the function spam() accepts a Foo pointer or a pointer to any class derived from Foo.
It is safe to use multiple inheritance with SWIG.
-In C++, there are many different ways a function might receive and manipulate objects. For example:
C++ overloaded functions, methods, and constructors are mostly supported by SWIG. For example, if you have two functions like this:
or
-VOID FOO(bAR *B); ++@@ -34274,7 +38306,7 @@ void spam(short); // Ignoredvoid foo(Bar *b); void foo(Bar &b);Dealing with the Lua coercion mechanism, the priority is roughly (integers, floats, strings, userdata). But it is better to rename the functions rather than rely upon the ordering.
-26.3.11 C++ operators
+28.3.11 C++ operators
Certain C++ overloaded operators can be handled automatically by SWIG. For example, consider a class like this:
@@ -34346,13 +38378,12 @@ Complex operator+(double, const Complex &c);-__sub__ operator- __mul__ operator * __div__ operator/ -__neg__ unary minus +__unm__ unary minus __call__ operator() (often used in functor classes) __pow__ the exponential fn (no C++ equivalent, Lua uses ^) -__concat__ the concatenation operator (SWIG maps C++'s -~ to Lua's ..) +__concat__ the concatenation operator (Lua's ..) __eq__ operator== __lt__ operator< __le__ operator<= @@ -34409,7 +38440,33 @@ __getitem__() and __setitem__() };26.3.12 Class extension with %extend
+C++ operators are mapped to Lua predefined metafunctions. Class + inherits from its bases the following list of metafunctions ( thus + inheriting the folloging operators and pseudo-operators):
+
No other lua metafunction is inherited. For example, __gc is not + inherited and must be redefined in every class. __tostring is + subject to a special handling. If absent in class and in class bases, a + default one will be provided by SWIG.
+One of the more interesting features of SWIG is that it can extend structures and classes with new methods. In the previous section, the Complex class would have benefited greatly from an __str__() method as @@ -34443,7 +38500,7 @@ public: return tmp; } bool operator==(const Complex& c) - { return ($self->re()==c.re() && $self->im()==c.im();} + { return ($self->re()==c.re() && $self->im()==c.im());} };
If you have a function that allocates memory like this,
char *foo() { @@ -34489,7 +38546,7 @@ char *foo();
This will release the allocated memory.
-C++ templates don't present a huge problem for SWIG. However, in order to create wrappers, you have to tell SWIG to create wrappers for a particular template instantiation. To do this, you use the template @@ -34525,7 +38582,7 @@ struct pair {
Obviously, there is more to template wrapping than shown in this example. More details can be found in the SWIG and C++ chapter. Some more complicated examples will appear later.
-In certain C++ programs, it is common to use classes that have been wrapped by so-called "smart pointers." Generally, this involves the use of a template class that implements operator->() like this:
@@ -34580,7 +38637,7 @@ operator->() itself, simply use the __deref__() method. > f = p:__deref__() -- Returns underlying Foo *Lua does not natively support exceptions, but it has errors which are similar. When a Lua function terminates with an error it returns one value back to the caller. SWIG automatically maps any basic type @@ -34721,13 +38778,179 @@ userdata: 0003D880 Exception handling with %catches" section and the " Exception handling with %exception" section, for more details on how to add exception specification to functions or globally (respectively).
-Since SWIG-3.0.0 C++ namespaces are supported via the %nspace + feature.
+Namespaces are mapped into Lua tables. Each of those tables contains + names that were defined within appropriate namespace. Namespaces + structure (a.k.a nested namespaces) is preserved. Consider the + following C++ code:
+%module example +%nspace MyWorld::Nested::Dweller; +%nspace MyWorld::World; + +int module_function() { return 7; } +int module_variable = 9; + +namespace MyWorld { + class World { + public: + World() : world_max_count(9) {} + int create_world() { return 17; } + const int world_max_count; // = 9 + }; + namespace Nested { + class Dweller { + public: + enum Gender { MALE = 0, FEMALE = 1 }; + static int count() { return 19; } + }; + } +} ++
Now, from Lua usage is as follows:
++> print(example.module_function()) +7 +> print(example.module_variable) +9 +> print(example.MyWorld.World():create_world()) +17 +> print(example.MyWorld.World.world_max_count) +9 +> print(example.MyWorld.Nested.Dweller.MALE) +0 +> print(example.MyWorld.Nested.Dweller.count()) +19 +> ++
If SWIG is running in a backwards compatible way, i.e. without the +-no-old-metatable-bindings option, then additional old-style names + are generated (notice the underscore):
++9 +> print(example.MyWorld.Nested.Dweller_MALE) +0 +> print(example.MyWorld.Nested.Dweller_count()) +11 +> ++
If SWIG is launched without -no-old-metatable-bindings + option, then it enters backward-compatible mode. While in this mode, it + tries to generate additional names for static functions, class static + constants and class enums. Those names are in a form +$classname_$symbolname and are added to the scope surrounding the + class. If %nspace is enabled, then class namespace is taken as scope. + If there is no namespace, or %nspace is disabled, then module is + considered a class namespace.
+Consider the following C++ code
+%module example +%nspace MyWorld::Test; +namespace MyWorld { +class Test { + public: + enum { TEST1 = 10, TEST2 } + static const int ICONST = 12; +}; +class Test2 { + public: + enum { TEST3 = 20, TEST4 } + static const int ICONST2 = 23; +} ++
When in backward compatible mode, in addition to the usual names, + the following ones will be generated (notice the underscore):
++9 +> print(example.MyWorld.Test_TEST1) -- Test has %nspace enabled +10 +> print(example.MyWorld.Test_ICONST) -- Test has %nspace enabled +12 +> print(example.Test2_TEST3) -- Test2 doesn't have %nspace enabled +20 +> print(example.Test2_ICONST2) -- Test2 doesn't have %nspace enabled +23 +> ++
There is a slight difference with enums when in C mode. As per C + standard, enums from C structures are exported to surrounding scope + without any prefixing. Pretending that Test2 is a struct, not class, + that would be:
++> print(example.TEST3) -- NOT Test2_TEST3 +20 +> ++
The internal organization of inheritance has changed. Consider the + following C++ code:
+%module example +class Base { + public: + int base_func() +}; +class Derived : public Base { + public: + int derived_func() +} ++
Lets assume for a moment that class member functions are stored in +.fn table. Previously, when classes were exported to Lua during + module initialization, for every derived class all service tables +ST(i.e. ".fn") were squashed and added to corresponding derived + class ST: Everything from .fn table of class Base was + copied to .fn table of class Derived and so on. This was a + recursive procedure, so in the end the whole inheritance tree of + derived class was squashed into derived class.
+That means that any changes done to class Base after module + initialization wouldn't affect class Derived:
++base = example.Base() +der = example.Derived() +> print(base.base_func) +function: 0x1367940 +> getmetatable(base)[".fn"].new_func = function (x) return x -- Adding new function to class Base (to class, not to an instance!) +> print(base.new_func) -- Checking this function +function +> print(der.new_func) -- Wouldn't work. Derived doesn't check Base any more. +nil +> ++
This behaviour was changed. Now unless -squash-bases option is + provided, Derived store a list of it's bases and if some symbol is not + found in it's own service tables then its bases are searched for it. + Option -squash-bases will effectively return old behaviour.
+> print(der.new_func) -- Now it works +function +> ++
This section explains what typemaps are and how to use them. The default wrapping behaviour of SWIG is enough in most cases. However sometimes SWIG may need a little additional assistance to know which typemap to apply to provide the best wrapping. This section will be explaining how to use typemaps to best effect
-A typemap is nothing more than a code generation rule that is attached to a specific C datatype. For example, to convert integers from Lua to C, you might define a typemap like this:
@@ -34735,8 +38958,8 @@ Exception handling with %exception" section, for more details on how%module example %typemap(in) int { - $1 = (int) lua_tonumber(L,$input); - printf("Received an integer : %d\n",$1); + $1 = (int) lua_tonumber(L,$input); + printf("Received an integer : %d\n",$1); } %inline %{ extern int fact(int n); @@ -34761,7 +38984,7 @@ Received an integer : 6 720
There are many ready written typemaps built into SWIG for all common types (int, float, short, long, char*, enum and more), which SWIG uses automatically, with no effort required on your part.
@@ -34824,7 +39047,7 @@ void swap(int *sx, int *sy);Note: C++ references must be handled exactly the same way. However SWIG will automatically wrap a const int& as an input parameter (since that it obviously input).
-Arrays present a challenge for SWIG, because like pointers SWIG does not know whether these are input or output values, nor does SWIG have any indication of how large an array should be. However with the proper @@ -34896,7 +39119,8 @@ t=example.sort_double(t) -- replace t with the result accordingly. Take note of this behaviour if you have a C function which returns indexes.
Note: SWIG also can support arrays of pointers in a similar manner.
-Several C++ libraries use a pointer-pointer functions to create its objects. These functions require a pointer to a pointer which is then filled with the pointer to the new object. Microsoft's COM and DirectX @@ -34935,7 +39159,7 @@ int Create_Math(iMath** pptr); // its creator (assume it mallocs) ptr=nil -- the iMath* will be GC'ed as normal -
This section describes how you can modify SWIG's default wrapping behavior for various C/C++ datatypes using the %typemap directive. This is an advanced topic that assumes familiarity with the @@ -34950,7 +39174,7 @@ ptr=nil -- the iMath* will be GC'ed as normal You should not attempt to write your own typemaps until you have read and can understand both of these files (they may well also give you an idea to base your work on).
-There are many different types of typemap that can be written, the full list can be found in the "Typemaps" chapter. However the following are the most commonly used ones.
@@ -34963,7 +39187,7 @@ ptr=nil -- the iMath* will be GC'ed as normal function should be called (the syntax for the typecheck is different from the typemap, see typemaps for details). -This section explains the SWIG specific Lua-C API. It does not cover the main Lua-C api, as this is well documented and not worth covering.
int SWIG_ConvertPtr(lua_State* L,int index,void** @@ -35013,10 +39237,10 @@ if (!SWIG_IsOK(SWIG_ConvertPtr( .....)){ type);
This section covers adding of some small extra bits to your module to add the last finishing touches.
-Sometimes, it may be necessary to add your own special functions, which bypass the normal SWIG wrapper method, and just use the native Lua API calls. These 'native' functions allow direct adding of your own @@ -35038,7 +39262,7 @@ int native_function(lua_State*L) // my native code to be added into the module under the name 'my_func'. SWIG will not add any wrapper for this function, beyond adding it into the function table. How you write your code is entirely up to you.
-As well as adding additional C/C++ code, it's also possible to add your own Lua code to the module as well. This code is executed once all other initialisation, including the %init code has been called.
@@ -35069,7 +39293,7 @@ int native_function(lua_State*L) // my native codeGood uses for this feature is adding of new code, or writing helper functions to simplify some of the code. See Examples/lua/arrays for an example of this code.
-In the previous section, a high-level view of Lua wrapping was presented. Obviously a lot of stuff happens behind the scenes to make this happen. This section will explain some of the low-level details on @@ -35078,7 +39302,7 @@ int native_function(lua_State*L) // my native code stop reading here. This is going into the guts of the code and how it works. It's mainly for people who need to know what's going on within the code.
-Assuming that you had some global data that you wanted to share between C and Lua. How does SWIG do it?
As mentioned earlier, classes and structures, are all held as pointer, using the Lua 'userdata' structure. This structure is actually a pointer to a C structure 'swig_lua_userdata', which contains the @@ -35246,7 +39470,7 @@ end The current implementation is a bit rough as it will add any member function beginning with '__' into the metatable too, assuming its an operator overload.
-Lua is very helpful with the memory management. The 'swig_lua_userdata' is fully managed by the interpreter itself. This means that neither the C code nor the Lua code can damage it. Once a @@ -35267,7 +39491,7 @@ end the data (unlike most other scripting languages, Lua does not permit access to the data from within the interpreter).
This chapter describes SWIG's support of
+ This chapter describes SWIG's support for
Modula-3. You should be familiar with the basics
of SWIG, especially typemaps. Modula-3 is a compiled language in the tradition of Niklaus Wirth's
Modula 2, which is in turn a successor to Pascal. SWIG's Modula-3 support is currently very basic and highly
@@ -35326,7 +39550,7 @@ Modula-327.1 Overview
+29.1 Overview
Although it is possible to write Modula-3 code that performs as well as C/C++ most existing libraries are not written in Modula-3 but in C or C++, and even libraries in other languages may provide C header @@ -35340,21 +39564,21 @@ Modula-3. You should be familiar with the basics typemaps you can pass TEXTs or open arrays, and convert error return codes into exceptions.
If the library API is ill designed writing appropriate typemaps can - be still time-consuming. E.g. C programmers are very creative to + still be time-consuming. E.g. C programmers are very creative to work-around missing data types like (real) enumerations and sets. You should turn such work-arounds back to the Modula-3 way otherwise you lose static safety and consistency.
Without SWIG you would probably never consider trying to call C++ libraries from Modula-3, but with SWIG this is becomes feasible. SWIG can generate C wrappers to C++ functions and object methods that may - throw exceptions, and then wrap these C wrappers for Module-3. To make + throw exceptions, and then wrap these C wrappers for Modula-3. To make it complete you can then hide the C interface with Modula-3 classes and exceptions.
SWIG allows you to call C and C++ libraries from Modula-3 (even with call back functions), but it doesn't allow you to easily integrate a - Module-3 module into a C/C++ project.
-Modula-3 has integrated support for calling C functions. This is also extensively used by the standard Modula-3 libraries to call OS functions. The Modula-3 part of SWIG and the corresponding SWIG library @@ -35429,8 +39653,8 @@ Database, it is good Modula-3 style to set up one Module with the (different SWIG interfaces can share common data) per module. Identifiers belonging to a different module may ignored (%ignore ) and the principal type must be renamed (%typemap).
-Interfaces to C++ files are much more complicated and there are some more design decisions that are not made, yet. Modula-3 has no support for C++ functions but C++ compilers should support generating C++ @@ -35477,14 +39701,14 @@ C++ library
Be warned: There is no C++ library I wrote a SWIG interface for, so I'm not sure if this is possible or sensible, yet.
-There are different Modula-3 compilers around: cm3, pm3, ezm3, Klagenfurth Modula-3, Cambridge Modula-3. SWIG itself does not contain compiler specific code but the modula3.swg library file may do so. For testing examples I use Critical Mass cm3.
-There are some experimental command line options that prevent SWIG from generating interface files. Instead files are emitted that may assist you when writing SWIG interface files.
@@ -35523,8 +39747,8 @@ C++ library of interfaces and wrappers. Instead generate templates for some basic typemaps. -Each C procedure has a bunch of inputs and outputs. Inputs are passed as function arguments, outputs are updated referential arguments and the function value.
@@ -35603,7 +39827,7 @@ C++ library step should never be skipped, SWIG will put it in the FINALLY branch of a TRY .. FINALLY structure. -Subranges, enumerations, and sets are machine oriented types that make Modula very strong and expressive compared with the type systems of many other languages.
@@ -35628,12 +39852,12 @@ s that split the task up into converting the C bit patterns (integer or satisfying. So the best what you can currently do is to rewrite constant definitions manually. Though this is a tedious work that I'd like to automate. -Declarations of C++ classes are mapped to OBJECT types while it is tried to retain the access hierarchy "public - protected - private" using partial revelation. Though the example in Examples/modula3/class/example.i is not really useful, yet.
-Pieces of Modula-3 code provided by typemaps may contain identifiers from foreign modules. If the typemap m3wrapinconv for blah * contains code using the function M3toC.SharedTtoS you @@ -35653,7 +39877,7 @@ IMPORT M3toC; %}
Modula-3 provides another possibility of an output of a function: exceptions.
Any piece of Modula-3 code that SWIG inserts due to a typemap can @@ -35664,7 +39888,7 @@ throws extension. If the typemap m3wrapinconv for blah * contains code that may raise the exceptions OSError.E you should declare %typemap("m3wrapinconv:throws") blah * %{OSError.E%}.
-The generation of wrappers in Modula-3 needs very fine control to take advantage of the language features. Here is an example of a generated wrapper where almost everything is generated by a typemap:
@@ -35705,8 +39929,8 @@ throws extension. If the typemap m3wrapinconv for blah END Name; -Feature | Example | Description |
---|---|---|
multiretval | %m3multiretval get_box; or @@ -35725,7 +39949,7 @@ multiretval feature activated, but it is explicitly requested from option. In future it may be generalized to other kind of values such as strings. |
Pragma | Example | Description |
---|---|---|
unsafe | %pragma(modula3) unsafe="true"; | @@ -35735,16 +39959,14 @@ Mark the raw interface modules as UNSAFE. This will be Specifies the library name for the wrapper library to be created. It should be distinct from the name of the library to be wrapped. |
This section contains information on SWIG's support of Racket, formally known as MzScheme.
-Example interface file:
@@ -35780,15 +40002,15 @@ handle_ptr(struct diag_cntrs, cntrs);+Then in scheme, you can use regular struct access procedures like
-- ; suppose a function created a struct foo as - ; (define foo (make-diag-cntrs (#x1 #x2 #x3) (make-inspector)) - ; Then you can do - (format "0x~x" (diag-cntrs-field1 foo)) - (format "0x~x" (diag-cntrs-field2 foo)) - ;etc... + ; suppose a function created a struct foo as + ; (define foo (make-diag-cntrs (#x1 #x2 #x3) (make-inspector)) + ; Then you can do + (format "0x~x" (diag-cntrs-field1 foo)) + (format "0x~x" (diag-cntrs-field2 foo)) + ;etc...28.2 Simple example
+30.2 Simple example
A few examples are available in the Examples/mzscheme directory. The code and log of a session using SWIG below should help getting started.
C header file:
@@ -35879,7 +40101,7 @@ Welcome to MzScheme v4.2.4 [3m], Copyright (c) 2004-2010 PLT Scheme Inc. better performance, but work is still required for SWIG to emit code which is compatible with it. -28.3 External documentation
+30.3 External documentation
See the C API for more description of using the mechanism for adding extensions. The main documentation is @@ -35887,8 +40109,7 @@ here.
Tip: mzc's --vv option is very useful for debugging the inevitable library problems you'll encounter.
- -29 SWIG and Ocaml
+31 SWIG and Ocaml
@@ -35933,11 +40154,11 @@ here.-Overriding Methods in Ocaml Director Usage Example Creating director objects -Typemaps for directors, directorin, - directorout, directorargout -directorin typemap -directorout typemap -directorargout typemap +Typemaps for directors, directorin, + directorout, directorargout +typemap +directorout typemap +directorargout typemap Exceptions @@ -35946,24 +40167,24 @@ here.This chapter describes SWIG's support of Ocaml. Ocaml is a - relatively recent addition to the ML family, and is a recent addition - to SWIG. It's the second compiled, typed language to be added. Ocaml - has widely acknowledged benefits for engineers, mostly derived from a - sophisticated type system, compile-time checking which eliminates - several classes of common programming errors, and good native - performance. While all of this is wonderful, there are well-written C - and C++ libraries that Ocaml users will want to take advantage of as - part of their arsenal (such as SSL and gdbm), as well as their own - mature C and C++ code. SWIG allows this code to be used in a natural, - type-safe way with Ocaml, by providing the necessary, but repetitive - glue code which creates and uses Ocaml values to communicate with C and - C++ code. In addition, SWIG also produces the needed Ocaml source that - binds variants, functions, classes, etc.
+This chapter describes SWIG's support of Ocaml.
+Ocaml is a relatively recent addition to the ML family, and is a + recent addition to SWIG. It's the second compiled, typed language to be + added. Ocaml has widely acknowledged benefits for engineers, mostly + derived from a sophisticated type system, compile-time checking which + eliminates several classes of common programming errors, and good + native performance. While all of this is wonderful, there are + well-written C and C++ libraries that Ocaml users will want to take + advantage of as part of their arsenal (such as SSL and gdbm), as well + as their own mature C and C++ code. SWIG allows this code to be used in + a natural, type-safe way with Ocaml, by providing the necessary, but + repetitive glue code which creates and uses Ocaml values to communicate + with C and C++ code. In addition, SWIG also produces the needed Ocaml + source that binds variants, functions, classes, etc.
If you're not familiar with the Objective Caml language, you can - visit The Ocaml Website.
-29.1 Preliminaries
-SWIG 1.3 works with Ocaml 3.04 and above. Given the choice, you + visit The Ocaml Website.
+31.1 Preliminaries
+SWIG 3.0 works with Ocaml 3.08.3 and above. Given the choice, you should use the latest stable release. The SWIG Ocaml module has been tested on Linux (x86,PPC,Sparc) and Cygwin on Windows. The best way to determine whether your system will work is to compile the examples and @@ -35971,26 +40192,26 @@ here.
check from the SWIG root directory after installing SWIG. The Ocaml module has been tested using the system's dynamic linking (the usual -lxxx against libxxx.so, as well as with Gerd Stolpmann's -Dl package . The ocaml_dynamic and ocaml_dynamic_cpp targets in the +Dl package. The ocaml_dynamic and ocaml_dynamic_cpp targets in the file Examples/Makefile illustrate how to compile and link SWIG modules that will be loaded dynamically. This has only been tested on Linux so far. -29.1.1 Running SWIG
+31.1.1 Running SWIG
The basics of getting a SWIG Ocaml module up and running can be seen from one of SWIG's example Makefiles, but is also described here. To build an Ocaml module, run SWIG using the -ocaml option.
-%swig -ocaml example.i -+This will produce 3 files. The file example_wrap.c contains +
This will produce 3 files. The file example_wrap.c contains all of the C code needed to build an Ocaml module. To build the module, you will compile the file example_wrap.c with ocamlc or ocamlopt to create the needed .o file. You will need to compile the resulting .ml and .mli files as well, and do the final link with -custom (not needed for native link).
-29.1.2 Compiling the code
+31.1.2 Compiling the code
The OCaml SWIG module now requires you to compile a module (Swig ) separately. In addition to aggregating common SWIG functionality, the Swig module contains the data structure that represents C/C++ values. @@ -36007,23 +40228,22 @@ Dl package . The ocaml_dynamic and ocaml_dynamic_cpp targets in the % ocamlc -c -ccopt "-I/usr/include/foo" example_wrap.c % ocamlc -c example.mli % ocamlc -c example.ml -
ocamlc is aware of .c files and knows how to handle them. +
ocamlc is aware of .c files and knows how to handle them. Unfortunately, it does not know about .cxx, .cc, or .cpp files, so when SWIG is invoked in C++ mode, you must:
% cp example_wrap.cxx example_wrap.cxx.c -+% ocamlc -c ... -ccopt -xc++ example_wrap.cxx.c +% ... +
% ocamlc -c ... -ccopt -xc++ example_wrap.cxx.c -
% ... -
-
The camlp4 module (swigp4.ml -> swigp4.cmo) contains a simple
rewriter which makes C++ code blend more seamlessly with objective caml
- code. It's use is optional, but encouraged. The source file is included
+ code. Its use is optional, but encouraged. The source file is included
in the Lib/ocaml directory of the SWIG source distribution. You can
checkout this file with "swig -ocaml -co swigp4.ml". You
should compile the file with "ocamlc -I `camlp4 -where` -pp
@@ -36068,28 +40288,27 @@ Dl package . The ocaml_dynamic and ocaml_dynamic_cpp targets in the
(_atoi (C_string "2"))
let b = C_string (getenv "PATH")
-29.1.4 Using your module
+31.1.4 Using your module
You can test-drive your module by building a toplevel ocaml interpreter. Consult the ocaml manual for details.
When linking any ocaml bytecode with your module, use the -custom option to build your functions into the primitive list. This option is not needed when you build native code.
-As mentioned above, .cxx files need special handling to be compiled with ocamlc. Other than that, C code that uses class as a non-keyword, and C code that is too liberal with pointer types may not compile under the C++ compiler. Most code meant to be compiled as C++ will not have problems.
-In order to provide access to overloaded functions, and provide sensible outputs from them, all C entities are represented as members of the c_obj type:
In the code as seen by the typemap writer, there is a value,
swig_result, that always contains the current return data. It is a
list, and must be appended with the caml_list_append function, or with
- functions and macros provided by objective caml.
-
type c_obj = @@ -36115,13 +40334,12 @@ type c_obj =
A few functions exist which generate and return these:
Because of this style, a typemap can return any kind of value it - wants from a function. This enables out typemaps and inout typemaps to - work well. The one thing to remember about outputting values is that + wants from a function. This enables out typemaps and inout typemaps to + work well. The one thing to remember about outputting values is that you must append them to the return list with swig_result = caml_list_append(swig_result,v).
-This function will return a new list that has your element - appended. Upon return to caml space, the fnhelper function beautifies - the result. A list containing a single item degrades to only that item - (i.e. [ C_int 3 ] -> C_int 3), and a list containing more than one item - is wrapped in C_list (i.e. [ C_char 'a' ; C_char 'b' -> C_list [ C_char - 'a' ; C_char b ]). This is in order to make return values easier to +
This function will return a new list that has your element appended. + Upon return to caml space, the fnhelper function beautifies the result. + A list containing a single item degrades to only that item (i.e. [ + C_int 3 ] -> C_int 3), and a list containing more than one item is + wrapped in C_list (i.e. [ C_char 'a' ; C_char 'b' -> C_list [ C_char + 'a' ; C_char b ]). This is in order to make return values easier to handle when functions have only one return value, such as constructors, - and operators. In addition, string, pointer, and object values are + and operators. In addition, string, pointer, and object values are interchangeable with respect to caml_ptr_val, so you can allocate memory as caml strings and still use the resulting pointers for C purposes, even using them to construct simple objects on. Note, though, @@ -36151,7 +40369,7 @@ type c_obj = the SWIG interface does.
The wild card type that you can use in lots of different ways is C_obj. It allows you to wrap any type of thing you like as an object - using the same mechanism that the ocaml module does. When evaluated in + using the same mechanism that the ocaml module does. When evaluated in caml_ptr_val, the returned value is the result of a call to the object's "&" operator, taken as a pointer.
You should only construct values using objective caml, or using the @@ -36160,7 +40378,7 @@ type c_obj = provide everything a typemap needs to produce values. In addition, value items pass through directly, but you must make your own type signature for a function that uses value in this way.
-The SWIG %module directive specifies the name of the Ocaml module to be generated. If you specified `%module example', then your Ocaml code will be accessible in the module Example. The @@ -36186,12 +40404,12 @@ type c_obj = because it describes the output SWIG will generate for class definitions. -
SWIG will wrap enumerations as polymorphic variants in the output - Ocaml code, as above in C_enum. In order to support all C++-style uses + Ocaml code, as above in C_enum. In order to support all C++-style uses of enums, the function int_to_enum and enum_to_int are provided for - ocaml code to produce and consume these values as integers. Other than - that, correct uses of enums will not have a problem. Since enum labels + ocaml code to produce and consume these values as integers. Other than + that, correct uses of enums will not have a problem. Since enum labels may overlap between enums, the enum_to_int and int_to_enum functions take an enum type label as an argument. Example:
bash-2.05a$ ocamlmktop -custom enum_test_wrap.o enum_test.cmo -o enum_test_top -bash-2.05a$ ./enum_test_top +bash-2.05a$ ./enum_test_top Objective Caml version 3.04 # open Enum_test ;; @@ -36237,7 +40455,7 @@ val x : Enum_test.c_obj = C_enum `a - : Enum_test.c_obj = C_enum `c
The ocaml SWIG module now has support for loading and using multiple SWIG modules at the same time. This enhances modularity, but presents problems when used with a language which assumes that each module's @@ -36246,8 +40464,8 @@ val x : Enum_test.c_obj = C_enum `a values are shared between functions imported from different modules. You must convert values to master values using the swig_val function before sharing them with another module.
-SWIG has support for array types, but you generally will need to provide a typemap to handle them. You can currently roll your own, or expand some of the macros provided (but not included by default) with @@ -36257,7 +40475,7 @@ val x : Enum_test.c_obj = C_enum `a
%make_simple_array_typemap is the easiest way to get access to arrays of simple types with known bounds in your code, but this only works for arrays whose bounds are completely specified.
-Unfortunately, unbounded arrays and pointers can't be handled in a completely general way by SWIG, because the end-condition of such an array can't be predicted. In some cases, it will be by consent (e.g. an @@ -36265,15 +40483,15 @@ val x : Enum_test.c_obj = C_enum `a *buffer, int len), and sometimes by sentinel value (0,-1,etc.). SWIG can't predict which of these methods will be used in the array, so you have to specify it for yourself in the form of a typemap.
-It's possible to use C++ to your advantage by creating a simple object that provides access to your array. This may be more desirable in some cases, since the object can provide bounds checking, etc., that prevents crashes.
Consider writing an object when the ending condition of your array is complex, such as using a required sentinel, etc.
-This is a simple example in typemap for an array of float, where the length of the array is specified as an extra parameter. Other such typemaps will work similarly. In the example, the function @@ -36292,24 +40510,24 @@ val x : Enum_test.c_obj = C_enum `a #include <stdio.h> void printfloats( float *tab, int len ) { - int i; + int i; - for( i = 0; i < len; i++ ) { - printf( "%f ", tab[i] ); - } + for( i = 0; i < len; i++ ) { + printf( "%f ", tab[i] ); + } - printf( "\n" ); + printf( "\n" ); } %} %typemap(in) (float *tab, int len) { - int i; - /* $*1_type */ - $2 = caml_array_len($input); - $1 = ($*1_type *)malloc( $2 * sizeof( float ) ); - for( i = 0; i < $2; i++ ) { - $1[i] = caml_double_val(caml_array_nth($input,i)); - } + int i; + /* $*1_type */ + $2 = caml_array_len($input); + $1 = ($*1_type *)malloc( $2 * sizeof( float ) ); + for( i = 0; i < $2; i++ ) { + $1[i] = caml_double_val(caml_array_nth($input,i)); + } } void printfloats( float *tab, int len ); @@ -36325,14 +40543,14 @@ void printfloats( float *tab, int len ); -
C++ classes, along with structs and unions are represented by C_obj - (string -> c_obj -> c_obj) wrapped closures. These objects contain a + (string -> c_obj -> c_obj) wrapped closures. These objects contain a method list, and a type, which allow them to be used like C++ objects. When passed into typemaps that use pointers, they degrade to pointers - through their "&" method. Every method an object has is represented as + through their "&" method. Every method an object has is represented as a string in the object's method table, and each method table exists in - memory only once. In addition to any other operators an object might + memory only once. In addition to any other operators an object might have, certain builtin ones are provided by SWIG: (all of these take no arguments (C_void))
@@ -36448,30 +40666,30 @@ baz %} class QApplication { public: - QApplication( int argc, char **argv ); - void setMainWidget( QWidget *widget ); - void exec(); + QApplication( int argc, char **argv ); + void setMainWidget( QWidget *widget ); + void exec(); }; class QPushButton { public: - QPushButton( char *str, QWidget *w ); - void resize( int x, int y ); - void show(); + QPushButton( char *str, QWidget *w ); + void resize( int x, int y ); + void show(); }; |
---|
bash-2.05a$ QTPATH=/your/qt/path bash-2.05a$ for file in swig.mli swig.ml swigp4.ml ; do swig -ocaml -co $file ; done bash-2.05a$ ocamlc -c swig.mli ; ocamlc -c swig.ml bash-2.05a$ ocamlc -I `camlp4 -where` -pp "camlp4o pa_extend.cmo q_MLast.cmo" -c swigp4.ml -bash-2.05a$ swig -ocaml -c++ -I$QTPATH/include qt.i +bash-2.05a$ swig -ocaml -c++ -I$QTPATH/include qt.i bash-2.05a$ mv qt_wrap.cxx qt_wrap.c -bash-2.05a$ ocamlc -c -ccopt -xc++ -ccopt -g -g -ccopt -I$QTPATH/include qt_wrap.c +bash-2.05a$ ocamlc -c -ccopt -xc++ -ccopt -g -g -ccopt -I$QTPATH/include qt_wrap.c bash-2.05a$ ocamlc -c qt.mli bash-2.05a$ ocamlc -c qt.ml bash-2.05a$ ocamlmktop -custom swig.cmo -I `camlp4 -where` \ @@ -36479,10 +40697,10 @@ bash-2.05a$ ocamlmktop -custom swig.cmo -I `camlp4 -where` \ -L$QTPATH/lib -cclib -lqt
-bash-2.05a$ ./qt_top +bash-2.05a$ ./qt_top Objective Caml version 3.06 Camlp4 Parsing version 3.06 @@ -36502,8 +40720,8 @@ val hello : Qt.c_obj = C_obj <fun>
Assuming you have a working installation of QT, you will see a window containing the string "hi" in a button.
-Director classes are classes which allow Ocaml code to override the public methods of a C++ object. This facility allows the user to use C++ libraries that require a derived class to provide application @@ -36524,7 +40742,7 @@ class foo { }; -
Because the Ocaml language module treats C++ method calls as calls to a certain function, all you need to do is to define the function that will handle the method calls in terms of the public methods of the @@ -36544,7 +40762,7 @@ new_derived_object uses a stub class to call your methods in place
In this example, I'll examine the objective caml code involved in providing an overloaded class. This example is contained in Examples/ocaml/shapes.
-
29.2.5.4 Creating director objects+31.2.5.4 Creating director objectsThe definition of the actual object triangle can be described this way: let triangle = - new_derived_object + new_derived_object new_shape (triangle_class ((0.0,0.0),(0.5,1.0),(1.0,0.0))) '() @@ -36631,28 +40849,28 @@ let triangle = actual raise is from an inner function used by new_derived_object, and throws NotObject). This prevents a deleted C++ object from causing a core dump, as long as the object is destroyed properly. - Simply printing the value of a wrapped C++ type will print it's + Simply printing the value of a wrapped C++ type will print its typename. E.g., octave:1> swigexample; @@ -36974,7 +41199,7 @@ octave:2> f=swigexample.fopen("not there","r"); error: value on right hand side of assignment is undefined error: evaluating assignment expression near line 2, column 2 30.3.6 Structures and C++ classes+32.3.6 Structures and C++ classesSWIG wraps C structures and C++ classes by using a special Octave type called a swig_ref. A swig_ref contains a reference to one or more instances of C/C++ objects, or just the type @@ -37108,14 +41333,14 @@ ans = 1 Depending on the ownership setting of a swig_ref, it may call C++ destructors when its reference count goes to zero. See the section on memory management below for details. -30.3.7 C++ inheritance+32.3.7 C++ inheritanceSingle and multiple inheritance are fully supported. The swig_ref type carries type information along with any C++ object pointer it holds. This information contains the full class hierarchy. When an indexing operation (such as a method invocation) occurs, the tree is walked to find a match in the current class as well as any of its bases. The lookup is then cached in the swig_ref. -30.3.8 C++ overloaded functions+32.3.8 C++ overloaded functionsOverloaded functions are supported, and handled as in other modules. That is, each overload is wrapped separately (under internal names), and a dispatch function is also emitted under the external/visible @@ -37123,7 +41348,7 @@ swig_ref type carries type information along with any C++ object based on the passed arguments. typecheck typemaps are used to analyze each argument, as well as assign precedence. See the chapter on typemaps for details. -30.3.9 C++ operators+32.3.9 C++ operatorsC++ operator overloading is supported, in a way similar to other modules. The swig_ref type supports all unary and binary operators between itself and all other types that exist in the system @@ -37133,9 +41358,9 @@ swig_ref type carries type information along with any C++ object named is derived from the types of the operands (either both or just the lhs or rhs). For example, if a and b are SWIG variables in - Octave, a+b becomes a.__add(b). The wrapper is then - free to implement __add to do whatever it wants. A wrapper may define - the __add function manually, %rename some other function to + Octave, a+b becomes a.__add__(b). The wrapper is then + free to implement __add__ to do whatever it wants. A wrapper may define + the __add__ function manually, %rename some other function to it, or %rename a C++ operator to it. By default the C++ operators are renamed to their corresponding Octave operators. So without doing any work, the following interface @@ -37162,90 +41387,90 @@ assert(c.value==5);Octave operators are mapped in the following way: -__brace a{args} -__brace_asgn a{args} = rhs -__paren a(args) -__paren_asgn a(args) = rhs -__str generates string rep -__not !a -__uplus +a -__uminus -a -__transpose a.' -__hermitian a' -__incr a++ -__decr a-- -__add a + b -__sub a - b -__mul a * b -__div a / b -__pow a ^ b -__ldiv a \ b -__lshift a <<b -__rshift a >> b -__lt a <b -__le a <= b -__eq a == b -__ge a >= b -__gt a > b -__ne a != b -__el_mul a .* b -__el_div a ./ b -__el_pow a .^ b -__el_ldiv a .\ b -__el_and a & b -__el_or a | b +__brace__ a{args} +__brace_asgn__ a{args} = rhs +__paren__ a(args) +__paren_asgn__ a(args) = rhs +__str__ generates string rep +__not__ !a +__uplus__ +a +__uminus__ -a +__transpose__ a.' +__hermitian__ a' +__incr__ a++ +__decr__ a-- +__add__ a + b +__sub__ a - b +__mul__ a * b +__div__ a / b +__pow__ a ^ b +__ldiv__ a \ b +__lshift__ a <<b +__rshift__ a >> b +__lt__ a <b +__le__ a <= b +__eq__ a == b +__ge__ a >= b +__gt__ a > b +__ne__ a != b +__el_mul__ a .* b +__el_div__ a ./ b +__el_pow__ a .^ b +__el_ldiv__ a .\ b +__el_and__ a & b +__el_or__ a | b On the C++ side, the default mappings are as follows: -%rename(__add) *::operator+; -%rename(__add) *::operator+(); -%rename(__add) *::operator+() const; -%rename(__sub) *::operator-; -%rename(__uminus) *::operator-(); -%rename(__uminus) *::operator-() const; -%rename(__mul) *::operator*; -%rename(__div) *::operator/; -%rename(__mod) *::operator%; -%rename(__lshift) *::operator< +%rename(__add__) *::operator+; +%rename(__add__) *::operator+(); +%rename(__add__) *::operator+() const; +%rename(__sub__) *::operator-; +%rename(__uminus__) *::operator-(); +%rename(__uminus__) *::operator-() const; +%rename(__mul__) *::operator*; +%rename(__div__) *::operator/; +%rename(__mod__) *::operator%; +%rename(__lshift__) *::operator< +%rename(__rshift__) *::operator--> >; -%rename(__el_and) *::operator&&; -%rename(__el_or) *::operator||; -%rename(__xor) *::operator^; -%rename(__invert) *::operator~; -%rename(__lt) *::operator +%rename(__el_and__) *::operator&&; +%rename(__el_or__) *::operator||; +%rename(__xor__) *::operator^; +%rename(__invert__) *::operator~; +%rename(__lt__) *::operator +%rename(__le__) *::operator<=; +%rename(__gt__) *::operator--> ; -%rename(__ge) *::operator>=; -%rename(__eq) *::operator==; -%rename(__ne) *::operator!=; -%rename(__not) *::operator!; -%rename(__incr) *::operator++; -%rename(__decr) *::operator--; -%rename(__paren) *::operator(); -%rename(__brace) *::operator[]; +%rename(__ge__) *::operator>=; +%rename(__eq__) *::operator==; +%rename(__ne__) *::operator!=; +%rename(__not__) *::operator!; +%rename(__incr__) *::operator++; +%rename(__decr__) *::operator--; +%rename(__paren__) *::operator(); +%rename(__brace__) *::operator[]; Octave can also utilise friend (i.e. non-member) operators with a simple %rename: see the example in the Examples/octave/operator directory. -30.3.10 Class extension with %extend+32.3.10 Class extension with %extendThe %extend directive works the same as in other modules. You can use it to define special behavior, like for example defining Octave operators not mapped to C++ operators, or defining certain Octave mechanisms such as how an object prints. For example, the octave_value::{is_string,string_value,print} functions are routed - to a special method __str that can be defined inside an + to a special method __str__ that can be defined inside an %extend. %extend A { -string __str() { +string __str__() { stringstream sout; sout<<$self->value; return sout.str(); @@ -37261,11 +41486,23 @@ octave:2> a a = 4 octave:3> printf("%s\n",a); 4 -octave:4> a.__str() +octave:4> a.__str__() 4 30.3.11 C++ templates+Similarly, Octave can use the __float__ method to convert + an object to a numeric value. +Octave 3.8.0 and later versions will also map unary functions X() to + the corresponding __X__ method, where X includes: abs(), + acos(), acosh(), angle(), arg(), asin(), asinh(), atan(), atanh(), + cbrt(), ceil(), conj(), cos(), cosh(), dawson(), erf(), erfc(), + erfcinv(), erfcx(), erfi(), erfinv(), exp(), expm1(), finite(), fix(), + floor(), gamma(), imag(), isalnum(), isalpha(), isascii(), iscntrl(), + isdigit(), isgraph(), isinf(), islower(), isna(), isnan(), isprint(), + ispunct(), isspace(), isupper(), isxdigit(), lgamma(), log(), log10(), + log1p(), log2(), real(), round(), roundb(), signbit(), signum(), sin(), + sinh(), sqrt(), tan(), tanh(), toascii(), tolower(), toupper() +32.3.11 C++ templatesC++ class and function templates are fully supported as in other modules, in that the %template directive may used to create explicit instantiations of templated types. For example, function templates can @@ -37310,7 +41547,7 @@ ans = 22 + 46i s+=_s; return *this; } - std::string __str() const { + std::string __str__() const { std::stringstream sout; sout<<s; return sout.str(); @@ -37335,10 +41572,19 @@ ans = (7,4) - 30.3.12 C++ Smart Pointers+32.3.12 C++ Smart Pointers+32.3.12.1 The shared_ptr + Smart Pointer+The C++11 standard provides std::shared_ptr which was + derived from the Boost implementation, boost::shared_ptr. Both + of these are available for Octave in the SWIG library and usage is + outlined in the shared_ptr smart + pointer library section. +32.3.12.2 Generic Smart + PointersC++ smart pointers are fully supported as in other modules. -30.3.13 Directors (calling Octave from C++ - code)+32.3.13 Directors (calling Octave from C++ + code)There is full support for SWIG Directors, which permits Octave code to subclass C++ classes, and implement their virtual methods. Octave has no direct support for object oriented programming, @@ -37422,7 +41668,7 @@ c-side routine called octave-side routine called - 30.3.14 Threads+32.3.14 ThreadsThe use of threads in wrapped Director code is not supported; i.e., an Octave-side implementation of a C++ class must be called from the Octave interpreter's thread. Anything fancier (apartment/queue model, @@ -37430,7 +41676,7 @@ octave-side routine called to the limitation that Octave must drive the module... like, for example, an optimization package that calls Octave to evaluate an objective function. -30.3.15 Memory management+32.3.15 Memory managementAs noted above, swig_ref represents a reference counted pointer to a C/C++-side object. It also contains a flag indicating whether Octave or the C/C++ code owns the object. If Octave owns it, @@ -37468,9 +41714,9 @@ A destructing the object will invalidate the Octave-side object if it still exists (and call destructors of other C++ bases in the case of multiple inheritance/subclass()'ing). -30.3.16 STL support+32.3.16 STL supportVarious STL library files are provided for wrapping STL containers. -30.3.17 Matrix typemaps+32.3.17 Matrix typemaps Octave provides a rich set of classes for dealing with matrices.
Currently there are no built-in typemaps to deal with those. However,
these are relatively straight forward for users to add themselves (see
@@ -37490,7 +41736,7 @@ ans = -0.18388
- 31 SWIG and Perl5+33 SWIG and Perl5
@@ -37559,6 +41805,16 @@ ans = -0.18388
@@ -37569,7 +41825,7 @@ ans = -0.18388
results, it is recommended that SWIG be used with Perl 5.8 or later.
We're no longer testing regularly with older versions, but Perl 5.6
seems to mostly work, while older versions don't.
-31.1 Overview+33.1 OverviewTo build Perl extension modules, SWIG uses a layered approach. At the lowest level, simple procedural wrappers are generated for functions, classes, methods, and other declarations in the input file. @@ -37583,7 +41839,7 @@ ans = -0.18388 interface is presented. Finally, proxy classes are described. Advanced customization features, typemaps, and other options are found near the end of the chapter. -31.2 Preliminaries+33.2 PreliminariesTo build a Perl5 module, run SWIG using the -perl option as follows:
@@ -37598,7 +41854,7 @@ swig -perl example.i
properly load the module.
-To build the module, you will need to compile the file example_wrap.c and link it with the rest of your program. -31.2.1 Getting the right header files+33.2.1 Getting the right header filesIn order to compile, SWIG extensions need the following Perl5 header files:
@@ -37624,7 +41880,7 @@ $ perl -e 'use Config; print "$Config{archlib}\n";'
/usr/lib/perl/5.14
-31.2.2 Compiling a dynamic module+33.2.2 Compiling a dynamic moduleThe preferred approach to building an extension module is to compile it into a shared object file or DLL. Assuming you have code you need to link to in a file called example.c, you will need to compile @@ -37649,8 +41905,8 @@ SWIG Wiki for additional information. %module example', then the target should be named `example.so ', `example.sl', or the appropriate dynamic module name on your system. -31.2.3 Building a dynamic module with - MakeMaker+33.2.3 Building a dynamic module with MakeMaker +It is also possible to use Perl to build dynamically loadable modules for you using the MakeMaker utility. To do this, write a Perl script such as the following: @@ -37659,9 +41915,9 @@ SWIG Wiki for additional information. # File : Makefile.PL use ExtUtils::MakeMaker; WriteMakefile( - `NAME' => `example', # Name of package - `LIBS' => [`-lm'], # Name of custom libraries - `OBJECT' => `example.o example_wrap.o' # Object files + `NAME' => `example', # Name of package + `LIBS' => [`-lm'], # Name of custom libraries + `OBJECT' => `example.o example_wrap.o' # Object files ); @@ -37678,7 +41934,7 @@ $ make install the preferred approach to compilation. More information about MakeMaker can be found in "Programming Perl, 2nd ed." by Larry Wall, Tom Christiansen, and Randal Schwartz. -31.2.4 Building a static version of Perl+33.2.4 Building a static version of PerlIf you machine does not support dynamic loading or if you've tried to use it without success, you can build a new version of the Perl interpreter with your SWIG extensions added to it. To build a static @@ -37726,14 +41982,14 @@ $ swig -perl -static -lperlmain.i example.i $ gcc example.o example_wrap.o -L/usr/lib/perl/5.14/CORE \ - -lperl -lsocket -lnsl -lm -o myperl + -lperl -lsocket -lnsl -lm -o myperl This will produce a new version of Perl called myperl. It should be functionality identical to Perl with your C/C++ extension added to it. Depending on your machine, you may need to link with additional libraries such as -lsocket, -lnsl, -ldl, etc. -31.2.5 Using the module+33.2.5 Using the moduleTo use the module, simply use the Perl use statement. If all goes well, you will be able to do this:
@@ -37844,8 +42100,8 @@ $ env LD_LIBRARY_PATH=/home/beazley/projects/lib perl
crle (Solaris) to add additional search paths to the default system
configuration (this requires root access and you will need to read the
man pages).
-
-31.2.6 Compilation problems and compiling - with C+++33.2.6 Compilation problems and compiling with + C++Compilation of C++ extensions has traditionally been a tricky problem. Since the Perl interpreter is written in C, you need to take steps to make sure C++ is properly initialized and that modules are @@ -37867,8 +42123,8 @@ $ g++ -shared example.o example_wrap.o -o example.so $ swig -c++ -perl example.i -$ CC -c example.cxx -$ CC -c example_wrap.cxx -I/usr/lib/perl/5.14/i386-linux/CORE +$ CC -Kpic -c example.cxx +$ CC -Kpic -c example_wrap.cxx -I/usr/lib/perl/5.14/i386-linux/CORE $ CC -shared example.o example_wrap.o -o example.so -lCrun 31.2.7 Compiling for 64-bit platforms+33.2.7 Compiling for 64-bit platformsOn platforms that support 64-bit applications (Solaris, Irix, etc.), special care is required when building extension modules. On these machines, 64-bit applications are compiled and linked using a different @@ -37977,13 +42233,13 @@ $ that software. This may prevent the use of 64-bit extensions. It may also introduce problems on platforms that support more than one linking standard (e.g., -o32 and -n32 on Irix). -31.3 Building Perl Extensions under Windows+33.3 Building Perl Extensions under WindowsBuilding a SWIG extension to Perl under Windows is roughly similar to the process used with Unix. Normally, you will want to produce a DLL that can be loaded into the Perl interpreter. This section assumes you are using SWIG with Microsoft Visual C++ although the procedure may be similar with other compilers. -31.3.1 Running SWIG from Developer Studio+33.3.1 Running SWIG from Developer StudioIf you are developing your application within Microsoft developer studio, SWIG can be invoked as a custom build option. The process roughly requires these steps: @@ -38030,17 +42286,17 @@ print "$a\n";31.3.2 Using other compilers+33.3.2 Using other compilersSWIG is known to work with Cygwin and may work with other compilers on Windows. For general hints and suggestions refer to the Windows chapter. -31.4 The low-level interface+33.4 The low-level interfaceAt its core, the Perl module uses a simple low-level interface to C function, variables, constants, and classes. This low-level interface can be used to control your application. However, it is also used to construct more user-friendly proxy classes as described in the next section. -31.4.1 Functions+33.4.1 FunctionsC functions are converted into new Perl built-in commands (or subroutines). For example:
@@ -38057,7 +42313,7 @@ use example;
$a = &example::fact(2);
-31.4.2 Global variables+33.4.2 Global variablesGlobal variables are handled using Perl's magic variable mechanism. SWIG generates a pair of functions that intercept read/write operations and attaches them to a Perl variable with the same name as the C global @@ -38111,7 +42367,7 @@ extern char *path; extern char *path; // Declared later in the input 31.4.3 Constants+33.4.3 ConstantsBy default, constants are wrapped as read-only Perl variables. For example:
@@ -38139,7 +42395,7 @@ use example;
print example::FOO,"\n";
-31.4.4 Pointers+33.4.4 PointersSWIG represents pointers as blessed references. A blessed reference is the same as a Perl reference except that it has additional information attached to it indicating what kind of reference it is. @@ -38163,9 +42419,9 @@ defined() command: if (defined($ptr)) { - print "Not a NULL pointer."; + print "Not a NULL pointer."; } else { - print "Is a NULL pointer."; + print "Is a NULL pointer."; }@@ -38183,9 +42439,9 @@ $a and $b to check the equality of two C pointers. The if ($$a == $$b) { - print "a and b point to the same thing in C"; + print "a and b point to the same thing in C"; } else { - print "a and b point to different objects."; + print "a and b point to different objects."; }@@ -38224,14 +42480,14 @@ NULL if the conversion can't be performed. preserve the same pointer naming conventions as XS and xsubpp. Given the advancement of the SWIG typesystem and the growing differences between SWIG and XS, this is no longer supported. - 31.4.5 Structures+33.4.5 StructuresAccess to the contents of a structure are provided through a set of low-level accessor functions as described in the "SWIG Basics" chapter. For example, struct Vector { - double x,y,z; + double x,y,z; }; 31.4.6 C++ classes+33.4.6 C++ classesC++ classes are wrapped by building a set of low level accessor functions. Consider the following class:
@@ -38381,7 +42637,7 @@ print example::List_length_get($l),"\n";
fairly primitive, it provides direct access to C++ objects. A higher
level interface using Perl proxy classes can be built using these
low-level accessors. This is described shortly.
-
-31.4.7 C++ classes and type-checking+33.4.7 C++ classes and type-checkingThe SWIG type-checker is fully aware of C++ inheritance. Therefore, if you have classes like this
@@ -38405,7 +42661,7 @@ void spam(Foo *f);
pointer to any class derived from Foo. If necessary, the
type-checker also adjusts the value of the pointer (as is necessary
when multiple inheritance is used).
-
31.4.8 C++ overloaded functions+33.4.8 C++ overloaded functionsIf you have a C++ program with overloaded functions or methods, you will need to disambiguate those methods using %rename. For example: @@ -38437,7 +42693,7 @@ example::Spam_foo_d($s,3.14);Please refer to the "SWIG Basics" chapter for more information. -31.4.9 Operators+33.4.9 OperatorsAs of version 1.3.27 SWIG automatically renames the most common C++ operators, and maps them into the perl module with the proper 'use overload ...' so you don't need to do any work. @@ -38458,7 +42714,7 @@ example::Spam_foo_d($s,3.14);31.4.10 Modules and packages+33.4.10 Modules and packagesWhen you create a SWIG extension, everything gets placed into a single Perl module. The name of the module is determined by the %module directive. To use the module, do the following: @@ -38532,7 +42788,7 @@ use example; # Load the module like before print Foo::fact(4),"\n"; # Call a function in package FooBar </pre></div> --> -31.5 Input and output parameters+33.5 Input and output parametersA common problem in some C programs is handling parameters passed as simple pointers. For example:
@@ -38685,7 +42941,7 @@ print "$c\n";
Note: The REFERENCE feature is only currently supported for numeric types (integers and floating point). -31.6 Exception handling+33.6 Exception handlingThe SWIG %exception directive can be used to create a user-definable exception handler for converting exceptions in your C/C++ program into Perl exceptions. The chapter on customization @@ -38824,7 +43080,7 @@ Customization features" for more examples. This is still supported, but it is deprecated. The newer %exception directive provides the same functionality, but it has additional capabilities that make it more powerful. -31.7 Remapping datatypes with typemaps+33.7 Remapping datatypes with typemapsThis section describes how you can modify SWIG's default wrapping behavior for various C/C++ datatypes using the %typemap directive. This is an advanced topic that assumes familiarity with the @@ -38834,7 +43090,7 @@ Customization features" for more examples. a required part of using SWIG---the default wrapping behavior is enough in most cases. Typemaps are only used if you want to change some aspect of the primitive C-Perl interface. -31.7.1 A simple typemap example+33.7.1 A simple typemap exampleA typemap is nothing more than a code generation rule that is attached to a specific C datatype. For example, to convert integers from Perl to C, you might define a typemap like this: @@ -38843,8 +43099,8 @@ Customization features" for more examples. %module example %typemap(in) int { - $1 = (int) SvIV($input); - printf("Received an integer : %d\n", $1); + $1 = (int) SvIV($input); + printf("Received an integer : %d\n", $1); } ... %inline %{ @@ -38883,8 +43139,8 @@ typedef declarations. For example:%typemap(in) int n { - $1 = (int) SvIV($input); - printf("n = %d\n",$1); + $1 = (int) SvIV($input); + printf("n = %d\n",$1); } %inline %{ typedef int Integer; @@ -38916,7 +43172,7 @@ example::count("e","Hello World"); >>> 31.7.2 Perl5 typemaps+33.7.2 Perl5 typemapsThe previous section illustrated an "in" typemap for converting Perl objects to C. A variety of different typemap methods are defined by the Perl module. For example, to convert a C integer back into a Perl @@ -38951,7 +43207,7 @@ example::count("e","Hello World"); Return of C++ member data (all languages).
%typemap(check) Check value of input parameter.
-31.7.3 Typemap variables+33.7.3 Typemap variablesWithin typemap code, a number of special variables prefaced with a $ may appear. A full list of variables can be found in the " Typemaps" chapter. This is a list of the most common variables: @@ -38981,7 +43237,7 @@ Typemaps" chapter. This is a list of the most common variables:$symname The Perl name of the wrapper function being
created.
-31.7.4 Useful functions+33.7.4 Useful functionsWhen writing typemaps, it is necessary to work directly with Perl5 objects. This, unfortunately, can be a daunting task. Consult the "perlguts" man-page for all of the really ugly details. A short summary @@ -39028,12 +43284,12 @@ SV *SvRV(SV *); int sv_isa(SV *, char *0; 31.8 Typemap Examples+33.8 Typemap ExamplesThis section includes a few examples of typemaps. For more examples, you might look at the files "perl5.swg" and "typemaps.i " in the SWIG library. -31.8.1 Converting a Perl5 array to a char - **+33.8.1 Converting a Perl5 array to a char ** +A common problem in many C programs is the processing of command line arguments, which are usually passed in an array of NULL terminated strings. The following SWIG interface file allows a Perl5 array @@ -39044,47 +43300,47 @@ int sv_isa(SV *, char *0; // This tells SWIG to treat char ** as a special case %typemap(in) char ** { - AV *tempav; - I32 len; - int i; - SV **tv; - if (!SvROK($input)) - croak("Argument $argnum is not a reference."); - if (SvTYPE(SvRV($input)) != SVt_PVAV) - croak("Argument $argnum is not an array."); - tempav = (AV*)SvRV($input); - len = av_len(tempav); - $1 = (char **) malloc((len+2)*sizeof(char *)); - for (i = 0; i <= len; i++) { - tv = av_fetch(tempav, i, 0); - $1[i] = (char *) SvPV(*tv,PL_na); - } - $1[i] = NULL; + AV *tempav; + I32 len; + int i; + SV **tv; + if (!SvROK($input)) + croak("Argument $argnum is not a reference."); + if (SvTYPE(SvRV($input)) != SVt_PVAV) + croak("Argument $argnum is not an array."); + tempav = (AV*)SvRV($input); + len = av_len(tempav); + $1 = (char **) malloc((len+2)*sizeof(char *)); + for (i = 0; i <= len; i++) { + tv = av_fetch(tempav, i, 0); + $1[i] = (char *) SvPV(*tv,PL_na); + } + $1[i] = NULL; }; // This cleans up the char ** array after the function call %typemap(freearg) char ** { - free($1); + free($1); } // Creates a new Perl array and places a NULL-terminated char ** into it %typemap(out) char ** { - AV *myav; - SV **svs; - int i = 0,len = 0; - /* Figure out how many elements we have */ - while ($1[len]) - len++; - svs = (SV **) malloc(len*sizeof(SV *)); - for (i = 0; i < len ; i++) { - svs[i] = sv_newmortal(); - sv_setpv((SV*)svs[i],$1[i]); - }; - myav = av_make(len,svs); - free(svs); - $result = newRV_noinc((SV*)myav); - sv_2mortal($result); - argvi++; + AV *myav; + SV **svs; + int i = 0,len = 0; + /* Figure out how many elements we have */ + while ($1[len]) + len++; + svs = (SV **) malloc(len*sizeof(SV *)); + for (i = 0; i < len ; i++) { + svs[i] = sv_newmortal(); + sv_setpv((SV*)svs[i],$1[i]); + }; + myav = av_make(len,svs); + free(svs); + $result = newRV_noinc((SV*)myav); + sv_2mortal($result); + argvi++; } // Now a few test functions @@ -39118,7 +43374,7 @@ $b = argv::get_args(); # Get array of strings from C print @$b,"\n"; # Print it out 31.8.2 Return values+33.8.2 Return valuesReturn values are placed on the argument stack of each wrapper function. The current value of the argument stack pointer is contained in a variable argvi. Whenever a new output value is added, it @@ -39131,16 +43387,16 @@ print @$b,"\n"; # Print it out %typemap(argout) int *OUTPUT { - if (argvi >= items) { - EXTEND(sp,1); /* Extend the stack by 1 object */ - } - $result = sv_newmortal(); - sv_setiv($target,(IV) *($1)); - argvi++; + if (argvi >= items) { + EXTEND(sp,1); /* Extend the stack by 1 object */ + } + $result = sv_newmortal(); + sv_setiv($target,(IV) *($1)); + argvi++; } 31.8.3 Returning values from arguments+33.8.3 Returning values from argumentsSometimes it is desirable for a function to return a value in one of its arguments. This example describes the implementation of the OUTPUT typemap. @@ -39152,24 +43408,24 @@ OUTPUT typemap. // an output value. %typemap(argout) double *OUTPUT { - $result = sv_newmortal(); - sv_setnv($result, *$input); - argvi++; /* Increment return count -- important! */ + $result = sv_newmortal(); + sv_setnv($result, *$input); + argvi++; /* Increment return count -- important! */ } // We don't care what the input value is. Ignore, but set to a temporary variable %typemap(in,numinputs=0) double *OUTPUT(double junk) { - $1 = &junk; + $1 = &junk; } // Now a function to test it %{ /* Returns the first two input arguments */ int multout(double a, double b, double *out1, double *out2) { - *out1 = a; - *out2 = b; - return 0; + *out1 = a; + *out2 = b; + return 0; }; %} @@ -39189,7 +43445,7 @@ print "multout(7,13) = @r\n"; ($x,$y) = multout(7,13); -31.8.4 Accessing array structure members+33.8.4 Accessing array structure membersConsider the following data structure: @@ -39238,15 +43494,15 @@ typedef struct { the "in" typemap in the previous section would be used to convert an int[] array to C whereas the "memberin" typemap would be used to copy the converted array into a C data structure. - 31.8.6 Pointer handling+33.8.6 Pointer handlingOccasionally, it might be necessary to convert pointer values that have been stored using the SWIG typed-pointer representation. To convert a pointer from Perl to C, the following function is used: @@ -39349,14 +43605,14 @@ $descriptor() macro in a typemap. For example: } -31.9 Proxy classes+33.9 Proxy classesOut of date. Needs update. Using the low-level procedural interface, SWIG can also construct a high-level object oriented interface to C structures and C++ classes. This is done by constructing a Perl proxy class (also known as a shadow class) that provides an OO wrapper to the underlying code. This section describes the implementation details of the proxy interface. -31.9.1 Preliminaries+33.9.1 PreliminariesProxy classes, are generated by default. If you want to turn them off, use the -noproxy command line option. For example:
@@ -39371,15 +43627,15 @@ $ swig -c++ -perl -noproxy example.i
original module, SWIG creates a collection of high-level Perl wrappers.
In your scripts, you will use these high level wrappers. The wrappers,
in turn, interact with the low-level procedural module.
-
-31.9.2 Structure and class wrappers+33.9.2 Structure and class wrappersSuppose you have the following SWIG interface file: %module example struct Vector { - Vector(double x, double y, double z); - ~Vector(); - double x,y,z; + Vector(double x, double y, double z); + ~Vector(); + double x,y,z; };@@ -39425,8 +43681,9 @@ sub DESTROY { my $self = tied(%{$_[0]}); delete $ITERATORS{$self}; if (exists $OWNER{$self}) { - examplec::delete_Vector($self)); - delete $OWNER{$self}; + examplec::delete_Vector($self)); + delete $OWNER{$self}; + } } sub FETCH { @@ -39473,8 +43730,8 @@ $v->{x} = 7.5; # Assignment of all members %$v = ( x=>3, - y=>9, - z=>-2); + y=>9, + z=>-2); # Reading members $x = $v->{x}; @@ -39484,14 +43741,14 @@ $v->DESTROY(); 31.9.3 Object Ownership+33.9.3 Object OwnershipIn order for proxy classes to work properly, it is necessary for Perl to manage some mechanism of object ownership. Here's the crux of the problem---suppose you had a function like this: Vector *Vector_get(Vector *v, int index) { - return &v[i]; + return &v[i]; } Vector *new_Vector(double x, double y, double z) { - Vector *v; - v = new Vector(x,y,z); // Call C++ constructor - return v; + Vector *v; + v = new Vector(x,y,z); // Call C++ constructor + return v; } As always, a little care is in order. SWIG does not provide reference counting, garbage collection, or advanced features one might find in sophisticated languages. -31.9.4 Nested Objects+33.9.4 Nested ObjectsSuppose that we have a new object that looks like this: struct Particle { - Vector r; - Vector v; - Vector f; - int type; + Vector r; + Vector v; + Vector f; + int type; }@@ -39575,9 +43832,9 @@ struct Particle { package Particle; ... %BLESSEDMEMBERS = ( - r => `Vector', - v => `Vector', - f => `Vector', + r => `Vector', + v => `Vector', + f => `Vector', ); @@ -39596,7 +43853,7 @@ $p->{f}->{x} = 0.0; %${$p->{v}} = ( x=>0, y=>0, z=>0); 31.9.5 Proxy Functions+33.9.5 Proxy FunctionsWhen functions take arguments involving a complex object, it is sometimes necessary to write a proxy function. For example:
@@ -39621,7 +43878,7 @@ sub dot_product {
This function replaces the original function, but operates in an identical manner. -31.9.6 Inheritance+33.9.6 InheritanceSimple C++ inheritance is handled using the Perl @ISA array in each class package. For example, if you have the following interface file: @@ -39636,23 +43893,23 @@ sub dot_product { class Shape { public: - virtual double area() = 0; - virtual double perimeter() = 0; - void set_location(double x, double y); + virtual double area() = 0; + virtual double perimeter() = 0; + void set_location(double x, double y); }; class Circle : public Shape { public: - Circle(double radius); - ~Circle(); - double area(); - double perimeter(); + Circle(double radius); + ~Circle(); + double area(); + double perimeter(); }; class Square : public Shape { public: - Square(double size); - ~Square(); - double area(); - double perimeter(); + Square(double size); + ~Square(); + double area(); + double perimeter(); } @@ -39684,7 +43941,7 @@ Package Square; be forewarned that this is not a trivial problem. In particular, inheritance of data members is extremely tricky (and I'm not even sure if it really works). -31.9.7 Modifying the proxy methods+33.9.7 Modifying the proxy methodsIt is possible to override the SWIG generated proxy/shadow methods, using %feature("shadow"). It works like all the other %feature directives. Here is a simple example showing how to add @@ -39709,7 +43966,7 @@ public: }; 31.10 Adding additional Perl code+33.10 Adding additional Perl codeIf writing support code in C isn't enough, it is also possible to write code in Perl. This code gets inserted in to the .pm file created by SWIG. One use of Perl code might be to supply a high-level @@ -39750,10 +44007,265 @@ my $a = [0,0,0,1]]; set_transform($im, $a); - + + 33.11 Cross language polymorphism+Proxy classes provide a more natural, object-oriented way to access + extension classes. As described above, each proxy instance has an + associated C++ instance, and method calls to the proxy are passed to + the C++ instance transparently via C wrapper functions. +This arrangement is asymmetric in the sense that no corresponding + mechanism exists to pass method calls down the inheritance chain from + C++ to Perl. In particular, if a C++ class has been extended in Perl + (by extending the proxy class), these extensions will not be visible + from C++ code. Virtual method calls from C++ are thus not able access + the lowest implementation in the inheritance chain. +Changes have been made to SWIG to address this problem and make the + relationship between C++ classes and proxy classes more symmetric. To + achieve this goal, new classes called directors are introduced at the + bottom of the C++ inheritance chain. The job of the directors is to + route method calls correctly, either to C++ implementations higher in + the inheritance chain or to Perl implementations lower in the + inheritance chain. The upshot is that C++ classes can be extended in + Perl and from C++ these extensions look exactly like native C++ + classes. Neither C++ code nor Perl code needs to know where a + particular method is implemented: the combination of proxy classes, + director classes, and C wrapper functions takes care of all the + cross-language method routing transparently. +33.11.1 Enabling directors+The director feature is disabled by default. To use directors you + must make two changes to the interface file. First, add the "directors" + option to the %module directive, like this: +
+
++%module(directors="1") modulename ++ Without this option no director code will be generated. Second, you + must use the %feature("director") directive to tell SWIG which classes + and methods should get directors. The %feature directive can be applied + globally, to specific classes, and to specific methods, like this: +
+
++// generate directors for all classes that have virtual methods +%feature("director"); + +// generate directors for all virtual methods in class Foo +%feature("director") Foo; ++ You can use the %feature("nodirector") directive to turn off + directors for specific classes or methods. So for example, +
+
++%feature("director") Foo; +%feature("nodirector") Foo::bar; ++ will generate directors for all virtual methods of class Foo except + bar(). +Directors can also be generated implicitly through inheritance. In + the following, class Bar will get a director class that handles the + methods one() and two() (but not three()): +
+
++%feature("director") Foo; +class Foo { +public: + Foo(int foo); + virtual void one(); + virtual void two(); +}; - -+ then at the Perl side you can define +
+
++use mymodule; + +package MyFoo; +use base 'mymodule::Foo'; + +sub one { + print "one from Perl\n"; +} ++ 33.11.2 Director classes+For each class that has directors enabled, SWIG generates a new + class that derives from both the class in question and a special +Swig::Director class. These new classes, referred to as director + classes, can be loosely thought of as the C++ equivalent of the Perl + proxy classes. The director classes store a pointer to their underlying + Perl object and handle various issues related to object ownership. +For simplicity let's ignore the Swig::Director class and + refer to the original C++ class as the director's base class. By + default, a director class extends all virtual methods in the + inheritance chain of its base class (see the preceding section for how + to modify this behavior). Thus all virtual method calls, whether they + originate in C++ or in Perl via proxy classes, eventually end up in at + the implementation in the director class. The job of the director + methods is to route these method calls to the appropriate place in the + inheritance chain. By "appropriate place" we mean the method that would + have been called if the C++ base class and its extensions in Perl were + seamlessly integrated. That seamless integration is exactly what the + director classes provide, transparently skipping over all the messy + extension API glue that binds the two languages together. +In reality, the "appropriate place" is one of only two + possibilities: C++ or Perl. Once this decision is made, the rest is + fairly easy. If the correct implementation is in C++, then the lowest + implementation of the method in the C++ inheritance chain is called + explicitly. If the correct implementation is in Perl, the Perl API is + used to call the method of the underlying Perl object (after which the + usual virtual method resolution in Perl automatically finds the right + implementation). +Now how does the director decide which language should handle the + method call? The basic rule is to handle the method in Perl, unless + there's a good reason not to. The reason for this is simple: Perl has + the most "extended" implementation of the method. This assertion is + guaranteed, since at a minimum the Perl proxy class implements the + method. If the method in question has been extended by a class derived + from the proxy class, that extended implementation will execute exactly + as it should. If not, the proxy class will route the method call into a + C wrapper function, expecting that the method will be resolved in C++. + The wrapper will call the virtual method of the C++ instance, and since + the director extends this the call will end up right back in the + director method. Now comes the "good reason not to" part. If the + director method were to blindly call the Perl method again, it would + get stuck in an infinite loop. We avoid this situation by adding + special code to the C wrapper function that tells the director method + to not do this. The C wrapper function compares the pointer to the Perl + object that called the wrapper function to the pointer stored by the + director. If these are the same, then the C wrapper function tells the + director to resolve the method by calling up the C++ inheritance chain, + preventing an infinite loop. +One more point needs to be made about the relationship between + director classes and proxy classes. When a proxy class instance is + created in Perl, SWIG creates an instance of the original C++ class. + This is exactly what happens without directors and is true even if + directors are enabled for the particular class in question. When a + class derived from a proxy class is created, however, SWIG then + creates an instance of the corresponding C++ director class. The reason + for this difference is that user-defined subclasses may override or + extend methods of the original class, so the director class is needed + to route calls to these methods correctly. For unmodified proxy + classes, all methods are ultimately implemented in C++ so there is no + need for the extra overhead involved with routing the calls through + Perl. +33.11.3 Ownership and object destruction+Memory management issues are slightly more complicated with + directors than for proxy classes alone. Perl instances hold a pointer + to the associated C++ director object, and the director in turn holds a + pointer back to a Perl object. By default, proxy classes own their C++ + director object and take care of deleting it when they are garbage + collected. +This relationship can be reversed by calling the special +DISOWN() method of the proxy class. After calling this method the + director class increments the reference count of the Perl object. When + the director class is deleted it decrements the reference count. + Assuming no outstanding references to the Perl object remain, the Perl + object will be destroyed at the same time. This is a good thing, since + directors and proxies refer to each other and so must be created and + destroyed together. Destroying one without destroying the other will + likely cause your program to segfault. +Also note that due to the proxy implementation, the DESTROY() + method on directors can be called for several reasons, many of which + have little to do with the teardown of an object instance. To help + disambiguate this, a second argument is added to the DESTROY() + call when a C++ director object is being released. So, to avoid running + your clean-up code when an object is not really going away, or after it + has already been reclaimed, it is suggested that custom destructors in + Perl subclasses looks something like: +
+
++sub DESTROY { + my($self, $final) = @_; + if($final) { + # real teardown code + } + shift->SUPER::DESTROY(@_); +} ++ 33.11.4 Exception unrolling+With directors routing method calls to Perl, and proxies routing + them to C++, the handling of exceptions is an important concern. By + default, the directors ignore exceptions that occur during method calls + that are resolved in Perl. To handle such exceptions correctly, it is + necessary to temporarily translate them into C++ exceptions. This can + be done with the %feature("director:except") directive. The following + code should suffice in most cases: +
+
++%feature("director:except") { + if ($error != NULL) { + throw Swig::DirectorMethodException(); + } +} ++ This code will check the Perl error state after each method call + from a director into Perl, and throw a C++ exception if an error + occurred. This exception can be caught in C++ to implement an error + handler. +It may be the case that a method call originates in Perl, travels up + to C++ through a proxy class, and then back into Perl via a director + method. If an exception occurs in Perl at this point, it would be nice + for that exception to find its way back to the original caller. This + can be done by combining a normal %exception directive with the +director:except handler shown above. Here is an example of a + suitable exception handler: +
+
++%exception { + try { $action } + catch (Swig::DirectorException &e) { SWIG_fail; } +} ++ The class Swig::DirectorException used in this example is actually a + base class of Swig::DirectorMethodException, so it will trap this + exception. Because the Perl error state is still set when + Swig::DirectorMethodException is thrown, Perl will register the + exception as soon as the C wrapper function returns. +33.11.5 Overhead and code bloat+Enabling directors for a class will generate a new director method + for every virtual method in the class' inheritance chain. This alone + can generate a lot of code bloat for large hierarchies. Method + arguments that require complex conversions to and from target language + types can result in large director methods. For this reason it is + recommended that you selectively enable directors only for specific + classes that are likely to be extended in Perl and used in C++. +Compared to classes that do not use directors, the call routing in + the director methods does add some overhead. In particular, at least + one dynamic cast and one extra function call occurs per method call + from Perl. Relative to the speed of Perl execution this is probably + completely negligible. For worst case routing, a method call that + ultimately resolves in C++ may take one extra detour through Perl in + order to ensure that the method does not have an extended Perl + implementation. This could result in a noticeable overhead in some + cases. +Although directors make it natural to mix native C++ objects with + Perl objects (as director objects) via a common base class pointer, one + should be aware of the obvious fact that method calls to Perl objects + will be much slower than calls to C++ objects. This situation can be + optimized by selectively enabling director methods (using the %feature + directive) for only those methods that are likely to be extended in + Perl. +33.11.6 Typemaps+Typemaps for input and output of most of the basic types from + director classes have been written. These are roughly the reverse of + the usual input and output typemaps used by the wrapper code. The + typemap operation names are 'directorin', 'directorout', and + 'directorargout'. The director code does not currently use any of the + other kinds of typemaps. It is not clear at this point which kinds are + appropriate and need to be supported. ++ 34 SWIG and PHP
@@ -39773,10 +44285,11 @@ set_transform($im, $a);
@@ -39977,7 +44497,7 @@ varinit typemap.
method will result in a php fatal error because the function is
undefined.
32.1 Generating PHP Extensions+34.1 Generating PHP ExtensionsTo build a PHP extension, run swig using the -php option as follows:
@@ -39838,56 +44351,63 @@ php_example.h contains the header information needed if you wish to
more detail in section 27.2.6.
The usual (and recommended) way is to build the extension as a separate dynamically loaded module (which is supported by all modern - operating systems). You can then specify that this be loaded - automatically in php.ini or load it explicitly for any script - which needs it. + operating systems).It is also possible to rebuild PHP from source so that your module is statically linked into the php executable/library. This is a lot more work, and also requires a full rebuild of PHP to update your module, and it doesn't play nicely with package system. We don't recommend this approach, or provide explicit support for it. -32.1.1 Building a loadable extension+34.1.1 Building a loadable extensionTo build your module as a dynamically loadable extension, use compilation commands like these (if you aren't using GCC, the commands will be different, and there may be some variation between platforms - these commands should at least work for Linux though): - gcc `php-config --includes` -fpic -c example_wrap.c - gcc -shared example_wrap.o -o example.so + gcc `php-config --includes` -fpic -c example_wrap.c example.c + gcc -shared example_wrap.o example.o -o example.so 32.1.2 Using PHP Extensions-To test the extension from a PHP script, you need to load it first. - You can load it for every script by adding this line to the [PHP] + 34.1.2 Using PHP Extensions+To test the extension from a PHP script, you first need to tell PHP + to load it. To do this, add a line like this to the [PHP] section of php.ini: - extension=/path/to/modulename.so + extension=/path/to/modulename.so Alternatively, you can load it explicitly only for scripts which - need it by adding this line to the start of each such PHP script:: +If the module is in PHP's default extension directory, you can omit + the path. +For some SAPIs (for example, the CLI SAPI) you can instead use the dl() function to + load an extension at run time, by adding a like like this to the start + of each PHP script which uses your extension: - dl("/path/to/modulename.so"); // Load the module + dl("/path/to/modulename.so"); // Load the module SWIG also generates a php module, which attempts to do the dl() - call for you: +But note that this doesn't work when running PHP through a webserver + in PHP5.3 and later - you'll need to use extension in +php.ini as described above. +The PHP module which SWIG generates will also attempt to do the +dl() call for you if the extension isn't already loaded: - include("example.php"); + include("example.php"); 32.2 Basic PHP interface+This PHP module also defines the PHP classes for the wrapped API, so + you'll almost certainly want to include it anyway. +34.2 Basic PHP interfaceIt is important to understand that PHP uses a single global namespace into which all symbols from extension modules are loaded. It is quite possible for names of symbols in one extension module to clash with other symbols unless care is taken to %rename them. At present SWIG doesn't have support for the namespace feature added in PHP 5.3. -32.2.1 Constants+34.2.1 ConstantsThese work in much the same way as in C/C++. Constants can be defined by using either the normal C pre-processor declarations, or the %constant SWIG directive. These will then be available from @@ -39915,16 +44435,16 @@ echo "E = " . E . "\n"; There's one peculiarity of how constants work in PHP which it is useful to note (this is not specific to SWIG though) - if you try to - use an undeclared constant, PHP will issue a warning and then expand - the constant to a string version of the constant's name. The warning - will often be missed though as if you're using PHP in a webserver, it + use an undeclared constant, PHP will emit a notice and then expand the + constant to a string version of the constant's name. Unfortunately it + is easy to miss the notice if you're using PHP in a webserver, as it will probably end up in error.log or similar. For example, %module example -#define EASY_TO_MISPELL 0 +#define EASY_TO_MISPELL 0 accessed incorrectly in PHP, @@ -39933,9 +44453,9 @@ echo "E = " . E . "\n"; include("example.php"); if(EASY_TO_MISPEL) { - .... + ... } else { - .... + ... } @@ -39943,7 +44463,7 @@ if(EASY_TO_MISPEL) {The mis-spelled constant will become the string 'EASY_TO_MISPEL', which is treated as true by the if test, when the value of the intended constant would be treated as false! -32.2.2 Global Variables+34.2.2 Global VariablesBecause PHP does not provide a mechanism to intercept access and assignment of global variables, global variables are supported through the use of automatically generated accessor functions. @@ -39964,7 +44484,7 @@ if(EASY_TO_MISPEL) {include("example.php"); print seki_get(); -seki_set( seki_get() * 2); # The C variable is now 4. +seki_set( seki_get() * 2); # The C variable is now 4. print seki_get(); At this time SWIG does not support custom accessor methods. -32.2.3 Functions+34.2.3 FunctionsC functions are converted into PHP functions. Default/optional arguments are also allowed. An interface file like this :
@@ -39994,7 +44514,7 @@ double bar(double, double b = 3.0);
include("example.php");
$a = foo(2);
$b = bar(3.5, -1.5);
-$c = bar(3.5); # Use default argument for 2nd parameter
+$c = bar(3.5); # Use default argument for 2nd parameter
@@ -40022,7 +44542,7 @@ $a = foo($s); # invokes 'foo(2)';
print $s; # The value of $s was not changed.
</pre></div>
-->
-32.2.4 Overloading+34.2.4 OverloadingAlthough PHP does not support overloading functions natively, swig will generate dispatch functions which will use %typecheck typemaps to allow overloading. This dispatch function's operation and @@ -40072,7 +44592,7 @@ Cause less confusion and <tt>doit("2");</tt> will invoke t taking the integer argument. </p> --> - 32.2.5 Pointers and References+34.2.5 Pointers and ReferencesPointers to C/C++ objects are represented as PHP resources, rather like MySQL connection handles. There are multiple ways to wrap pointers to simple types. Given the @@ -40141,10 +44661,15 @@ echo "The sum $in1 + $in2 = $result\n"; Because PHP has a native concept of reference, it may seem more natural to the PHP developer to use references to pass pointers. To enable this, one needs to include phppointers.i which defines - the named typemap REFERENCE. -However, this relies on call-time pass-by-reference, which has been - deprecated in PHP for some time, and was finally removed in PHP 5.4 -. So you should avoid creating new wrappers which rely on this approach. + the named typemap REF. +Prior to SWIG 3.0, the REF typemaps relied on PHP's call-time + pass-by-reference, which was deprecated in PHP 5.3 and removed in PHP + 5.4. So if you use these REF typemaps, you should ensure that SWIG≥3.0 + is used to generate wrappers from your interface file. +In case you write your own typemaps, SWIG supports an attribute + called byref: if you set that, then SWIG will make sure that + the generated wrapper function will want the input parameter as a + reference. %module example @@ -40164,7 +44689,7 @@ include("example.php"); $in1 = 3; $in2 = 5; $result = 0; -add(&$in1,&$in2,&$result); +add($in1,$in2,$result); echo "The sum $in1 + $in2 = $result\n"; ?> @@ -40181,7 +44706,7 @@ echo "The sum $in1 + $in2 = $result\n"; is sometimes required in C libraries. A NULL pointer can be created in PHP in a number of ways: by using unset on an existing variable, or assigning NULL to a variable. - Member variables and methods are accessed using the -> operator. -32.2.6.1 Using -noproxy+34.2.6.1 Using -noproxyThe -noproxy option flattens the object structure and generates collections of named functions (these are the functions which the PHP5 class wrappers call). The above example results in the @@ -40253,7 +44778,7 @@ Complex_im_set($obj,$d); Complex_im_get($obj); - 32.2.6.2 Constructors and Destructors+34.2.6.2 Constructors and DestructorsThe constructor is called when new Object() (or new_Object() if using -noproxy) is used to create an instance of the object. If multiple constructors are defined for an @@ -40279,7 +44804,7 @@ $o_copy = new Object($o); the instance are reassigned or go out of scope. The destructor is not available to be called manually. To force a destructor to be called the programmer can either reassign the variable or call unset($v) -32.2.6.3 Static Member Variables+34.2.6.3 Static Member VariablesStatic member variables in C++ are not wrapped as such in PHP as it does not appear to be possible to intercept accesses to such variables. Therefore, static member variables are wrapped using a class function @@ -40290,7 +44815,7 @@ $o_copy = new Object($o); %module example class Ko { - static int threats; + static int threats; }; @@ -40315,7 +44840,7 @@ echo "There have now been " . Ko::threats() . " threats\n"; - 32.2.6.4 Static Member Functions+34.2.6.4 Static Member FunctionsStatic member functions are supported in PHP using the class::function() syntax. For example
@@ -40331,8 +44856,20 @@ include("example.php");
Ko::threats();
-32.2.7 PHP Pragmas, Startup and Shutdown - code+34.2.6.5 Specifying Implemented Interfaces+ PHP supports the concept of abstract interfaces which a class can
+ implement. Since SWIG 3.0.3, you can tell SWIG that a wrapped class
+ (for example
+
++%typemap("phpinterfaces") MyIterator "Iterator"; ++ If there are multiple interfaces, just list them separated by + commas. +34.2.7 PHP Pragmas, Startup and Shutdown code +To place PHP code in the generated "example.php" file one can use the code pragma. The code is inserted after loading the shared object. @@ -40403,7 +44940,7 @@ include \"include.php\";The %rinit and %rshutdown statements are very similar but insert code into the request init (PHP_RINIT_FUNCTION) and request shutdown (PHP_RSHUTDOWN_FUNCTION) code respectively. -32.3 Cross language polymorphism+34.3 Cross language polymorphismProxy classes provide a more natural, object-oriented way to access extension classes. As described above, each proxy instance has an associated C++ instance, and method calls to the proxy are passed to @@ -40427,7 +44964,7 @@ include \"include.php\"; know where a particular method is implemented: the combination of proxy classes, director classes, and C wrapper functions takes care of all the cross-language method routing transparently. -32.3.1 Enabling directors+34.3.1 Enabling directorsThe director feature is disabled by default. To use directors you must make two changes to the interface file. First, add the "directors" option to the %module directive, like this: @@ -40490,7 +45027,7 @@ class MyFoo extends Foo { } -32.3.2 Director classes+34.3.2 Director classesFor each class that has directors enabled, SWIG generates a new class that derives from both the class in question and a special Swig::Director class. These new classes, referred to as director @@ -40551,7 +45088,7 @@ Swig::Director class. These new classes, referred to as director unmodified proxy classes, all methods are ultimately implemented in C++ so there is no need for the extra overhead involved with routing the calls through PHP. -32.3.3 Ownership and object destruction+34.3.3 Ownership and object destructionMemory management issues are slightly more complicated with directors than for proxy classes alone. PHP instances hold a pointer to the associated C++ director object, and the director in turn holds a @@ -40590,7 +45127,7 @@ $c->addFoo($a); In this example, we are assuming that FooContainer will take care of deleting all the Foo pointers it contains at some point. -32.3.4 Exception unrolling+34.3.4 Exception unrollingWith directors routing method calls to PHP, and proxies routing them to C++, the handling of exceptions is an important concern. By default, the directors ignore exceptions that occur during method calls that are @@ -40633,7 +45170,7 @@ director:except handler shown above. Here is an example of a exception. Because the PHP error state is still set when Swig::DirectorMethodException is thrown, PHP will register the exception as soon as the C wrapper function returns. -32.3.5 Overhead and code bloat+34.3.5 Overhead and code bloatEnabling directors for a class will generate a new director method for every virtual method in the class' inheritance chain. This alone can generate a lot of code bloat for large hierarchies. Method @@ -40657,7 +45194,7 @@ director:except handler shown above. Here is an example of a optimized by selectively enabling director methods (using the %feature directive) for only those methods that are likely to be extended in PHP. -32.3.6 Typemaps+34.3.6 TypemapsTypemaps for input and output of most of the basic types from director classes have been written. These are roughly the reverse of the usual input and output typemaps used by the wrapper code. The @@ -40665,11 +45202,11 @@ director:except handler shown above. Here is an example of a 'directorargout'. The director code does not currently use any of the other kinds of typemaps. It is not clear at this point which kinds are appropriate and need to be supported. -32.3.7 Miscellaneous+34.3.7 MiscellaneousDirector typemaps for STL classes are mostly in place, and hence you should be able to use std::string, etc., as you would any other type. - 33 SWIG and Pike+35 SWIG and Pike
@@ -40704,8 +45241,8 @@ director:except handler shown above. Here is an example of a
least, make sure you read the "SWIG Basics"
chapter.
-- 33.1 Preliminaries-33.1.1 Running SWIG+35.1 Preliminaries+35.1.1 Running SWIGSuppose that you defined a SWIG module such as the following: %module example @@ -40742,7 +45279,7 @@ example_wrap.cxx, if you ran SWIG with the -c++ option).$ swig -pike -o pseudonym.c example.i 33.1.2 Getting the right header files+35.1.2 Getting the right header filesIn order to compile the C/C++ wrappers, the compiler needs to know the path to the Pike header files. These files are usually contained in a directory such as @@ -40754,7 +45291,7 @@ example_wrap.cxx, if you ran SWIG with the -c++ option). location of these files, so you may need to hunt around for them. You're looking for files with the names global.h, program.h and so on. -33.1.3 Using your module+35.1.3 Using your moduleTo use your module, simply use Pike's import statement: @@ -40765,14 +45302,14 @@ Pike v7.4 release 10 running Hilfe v3.5 (Incremental Pike Frontend) (1) Result: 24 33.2 Basic C/C++ Mapping-33.2.1 Modules+35.2 Basic C/C++ Mapping+35.2.1 ModulesAll of the code for a given SWIG module is wrapped into a single Pike module. Since the name of the shared library that implements your module ultimately determines the module's name (as far as Pike is concerned), SWIG's %module directive doesn't really have any significance. -33.2.2 Functions+35.2.2 FunctionsGlobal functions are wrapped as new Pike built-in functions. For example,
@@ -40791,7 +45328,7 @@ int fact(int n);
(1) Result: 24
-33.2.3 Global variables+35.2.3 Global variablesGlobal variables are currently wrapped as a pair of functions, one to get the current value of the variable and another to set it. For example, the declaration @@ -40815,14 +45352,14 @@ double Foo; (3) Result: 3.14159033.2.4 Constants and enumerated types+35.2.4 Constants and enumerated typesEnumerated types in C/C++ declarations are wrapped as Pike constants, not as Pike enums. -33.2.5 Constructors and Destructors+35.2.5 Constructors and DestructorsConstructors are wrapped as create() methods, and destructors are wrapped as destroy() methods, for Pike classes. -33.2.6 Static Members+35.2.6 Static MembersSince Pike doesn't support static methods or data for Pike classes, static member functions in your C++ classes are wrapped as regular functions and static member variables are wrapped as pairs of functions @@ -40844,7 +45381,7 @@ public: methods, Shape_nshapes_get() and Shape_nshapes_set(), to get and set the value of Shape::nshapes. - 34 SWIG and Python+36 SWIG and Python
@@ -40877,7 +45414,13 @@ public:
34.1 Overview+36.1 OverviewTo build Python extension modules, SWIG uses a layered approach in which parts of the extension module are defined in C and other parts are defined in Python. The C layer contains low-level wrappers whereas @@ -40991,8 +45557,8 @@ public: Next, the Python interface to common C and C++ programming features is described. Advanced customization features such as typemaps are then described followed by a discussion of low-level implementation details. -34.2 Preliminaries-34.2.1 Running SWIG+36.2 Preliminaries+36.2.1 Running SWIGSuppose that you defined a SWIG module such as the following: @@ -41068,11 +45634,11 @@ example_wrap.c or example_wrap.cxx and a Python source example, then a file example.py is created. Notes: Usually the pythonappend and pythonprepend @@ -43487,7 +48087,7 @@ public: class Foo { public: int bar(int x); -} +}; Note that when the underlying C++ method is overloaded, there is @@ -43515,11 +48115,11 @@ class Foo { public: int bar(int x); int bar(); -} +}; The same applies for overloaded constructors. -34.6.3 Class extension with %extend+36.6.3 Class extension with %extendOne of the more interesting features of SWIG is that it can extend structures and classes with new methods--at least in the Python interface. Here is a simple example: @@ -43589,7 +48189,7 @@ Vector(12,14,16)%extend works with both C and C++ code. It does not modify the underlying object in any way---the extensions only show up in the Python interface. -34.6.4 Exception handling with %exception+36.6.4 Exception handling with %exceptionIf a C or C++ function throws an error, you may want to convert that error into a Python exception. To do this, you can use the %exception directive. %exception simply lets you rewrite @@ -43690,12 +48290,12 @@ PyExc_ZeroDivisionError The language-independent exception.i library file can also be used to raise exceptions. See the SWIG Library chapter. -34.7 Tips and techniques+36.7 Tips and techniquesAlthough SWIG is largely automatic, there are certain types of wrapping problems that require additional user input. Examples include dealing with output parameters, strings, binary data, and arrays. This chapter discusses the common techniques for solving these problems. -34.7.1 Input and output parameters+36.7.1 Input and output parametersA common problem in some C programs is handling parameters passed as simple pointers. For example:
@@ -43844,7 +48444,7 @@ void foo(Bar *OUTPUT);
may not have the intended effect since typemaps.i does not define an OUTPUT rule for Bar. -34.7.2 Simple pointers+36.7.2 Simple pointersIf you must work with simple pointers such as int * or double * and you don't want to use typemaps.i, consider using the cpointer.i library file. For example: @@ -43896,7 +48496,7 @@ _108fea8_p_intSee the SWIG Library chapter for further details. -34.7.3 Unbounded C Arrays+36.7.3 Unbounded C ArraysSometimes a C function expects an array to be passed as a pointer. For example,
@@ -43944,7 +48544,7 @@ int sumitems(int *first, int nitems) {
other hand, this low-level approach is extremely efficient and well
suited for applications in which you need to create buffers, package
binary data, etc.
-
-34.7.4 String handling+36.7.4 String handlingIf a C function has an argument of char *, then a Python string can be passed as input. For example:
@@ -43989,7 +48589,78 @@ int parity(char *data, int size, int initial);
-If you need to return binary data, you might use the cstring.i library file. The cdata.i library can also be used to extra binary data from arbitrary pointers. -34.8 Typemaps+36.7.5 Default arguments+C++ default argument code generation is documented in the main +Default arguments section. There is also an optional Python specific + feature that can be used called the python:cdefaultargs +feature flag. By default, SWIG attempts to convert C++ default + argument values into Python values and generates code into the Python + layer containing these values. For example: +
+
++struct CDA { + int fff(int a = 1, bool b = false); +}; ++ From Python this can be called as follows: +
+
++>>> CDA().fff() # C++ layer receives a=1 and b=false +>>> CDA().fff(2) # C++ layer receives a=2 and b=false +>>> CDA().fff(3, True) # C++ layer receives a=3 and b=true ++ The default code generation in the Python layer is: +
+
++class CDA(object): + ... + def fff(self, a=1, b=False): + return _default_args.CDA_fff(self, a, b) ++ Adding the feature: +
+
++%feature("python:cdefaultargs") CDA::fff; +struct CDA { + int fff(int a = 1, bool b = false); ++ results in identical behaviour when called from Python, however, it + results in different code generation: +
+
++class CDA(object): + ... + def fff(self, *args): + return _default_args.CDA_fff(self, *args) ++ The default arguments are obtained in the C++ wrapper layer instead + of the Python layer. Some code generation modes are quite different, eg + -builtin and -fastproxy, and are unaffected by +python:cdefaultargs as the default values are always obtained from + the C++ layer. +Note that not all default arguments can be converted into a Python + equivalent. When SWIG does not convert them, it will generate code to + obtain them from the C++ layer as if python:cdefaultargs was + specified. This will happen if just one argument cannot be converted + into a Python equivalent. This occurs typically when the argument is + not fully numeric, such as int(1): +
+
++struct CDA { + int fff(int a = int(1), bool b = false); +}; ++ Compatibility Note: SWIG-3.0.6 introduced the +python:cdefaultargs feature. Versions of SWIG prior to this varied + in their ability to convert C++ default values into equivalent Python + default argument values. +36.8 TypemapsThis section describes how you can modify SWIG's default wrapping behavior for various C/C++ datatypes using the %typemap directive. This is an advanced topic that assumes familiarity with the @@ -44000,7 +48671,7 @@ Typemaps" chapter. in most cases. Typemaps are only used if you want to change some aspect of the primitive C-Python interface or if you want to elevate your guru status. -34.8.1 What is a typemap?+36.8.1 What is a typemap?A typemap is nothing more than a code generation rule that is attached to a specific C datatype. For example, to convert integers from Python to C, you might define a typemap like this: @@ -44009,8 +48680,8 @@ Typemaps" chapter. %module example %typemap(in) int { - $1 = (int) PyLong_AsLong($input); - printf("Received an integer : %d\n",$1); + $1 = (int) PyLong_AsLong($input); + printf("Received an integer : %d\n",$1); } %inline %{ extern int fact(int n); @@ -44043,11 +48714,11 @@ int datatype. You can refine this by supplying an optional %module example %typemap(in) int nonnegative { - $1 = (int) PyLong_AsLong($input); - if ($1 < 0) { - PyErr_SetString(PyExc_ValueError,"Expected a nonnegative value."); - return NULL; - } + $1 = (int) PyLong_AsLong($input); + if ($1 < 0) { + PyErr_SetString(PyExc_ValueError,"Expected a nonnegative value."); + return NULL; + } } %inline %{ extern int fact(int nonnegative); @@ -44065,8 +48736,8 @@ extern int fact(int nonnegative);%typemap(in) int n { - $1 = (int) PyLong_AsLong($input); - printf("n = %d\n",$1); + $1 = (int) PyLong_AsLong($input); + printf("n = %d\n",$1); } %inline %{ typedef int Integer; @@ -44096,7 +48767,7 @@ int count(char c, char *str, int len); >>> 34.8.2 Python typemaps+36.8.2 Python typemapsThe previous section illustrated an "in" typemap for converting Python objects to C. A variety of different typemap methods are defined by the Python module. For example, to convert a C integer back into a @@ -44121,7 +48792,7 @@ Typemaps" chapter. simplicity and pedagogic value.To learn how to write a simple or your first typemap, you better take a look at the SWIG library version 1.3.20 or so. -34.8.3 Typemap variables+36.8.3 Typemap variablesWithin typemap code, a number of special variables prefaced with a $ may appear. A full list of variables can be found in the " Typemaps" chapter. This is a list of the most common variables: @@ -44151,7 +48822,7 @@ Typemaps" chapter. This is a list of the most common variables:$symname The Python name of the wrapper function being
created.
-34.8.4 Useful Python Functions+36.8.4 Useful Python FunctionsWhen you write a typemap, you usually have to work directly with Python objects. The following functions may prove to be useful. Python Integer Functions @@ -44242,11 +48913,11 @@ int PyFile_Check(PyObject *); write me34.9 Typemap Examples+36.9 Typemap ExamplesThis section includes a few examples of typemaps. For more examples, you might look at the files "python.swg" and "typemaps.i " in the SWIG library. -34.9.1 Converting Python list to a char **+36.9.1 Converting Python list to a char **A common problem in many C programs is the processing of command line arguments, which are usually passed in an array of NULL terminated strings. The following SWIG interface file allows a Python list object @@ -44265,11 +48936,11 @@ write me for (i = 0; i < size; i++) { PyObject *o = PyList_GetItem($input,i); if (PyString_Check(o)) - $1[i] = PyString_AsString(PyList_GetItem($input,i)); + $1[i] = PyString_AsString(PyList_GetItem($input,i)); else { - PyErr_SetString(PyExc_TypeError,"list must contain strings"); - free($1); - return NULL; + PyErr_SetString(PyExc_TypeError,"list must contain strings"); + free($1); + return NULL; } } $1[i] = 0; @@ -44303,7 +48974,7 @@ int print_args(char **argv) { >>> from argv import * ->>> print_args(["Dave","Mike","Mary","Jane","John"]) +>>> print_args(["Dave", "Mike", "Mary", "Jane", "John"]) argv[0] = Dave argv[1] = Mike argv[2] = Mary @@ -44317,8 +48988,8 @@ argv[4] = John dynamic memory allocation is used to allocate memory for the array, the "freearg" typemap is used to later release this memory after the execution of the C function. - 34.9.4 Mapping Python tuples into small - arrays+36.9.4 Mapping Python tuples into small arrays +In some applications, it is sometimes desirable to pass small arrays of numbers as arguments. For example :
@@ -44500,7 +49198,7 @@ extern void set_direction(double a[4]); // Set direction vector
-Since our mapping copies the contents of a Python tuple into a C array, such an approach would not be recommended for huge arrays, but for small structures, this approach works fine. -34.9.5 Mapping sequences to C arrays+36.9.5 Mapping sequences to C arraysSuppose that you wanted to generalize the previous example to handle C arrays of different sizes. To do this, you might write a typemap as follows: @@ -44579,7 +49277,7 @@ static int convert_darray(PyObject *input, double *ptr, int size) { }34.9.6 Pointer handling+36.9.6 Pointer handlingOccasionally, it might be necessary to convert pointer values that have been stored using the SWIG typed-pointer representation. Since there are several ways in which pointers can be represented, the @@ -44644,7 +49342,7 @@ if ((SWIG_ConvertPtr($input,(void **) &$1, $descriptor(Foo *), retrieve a pointer from any object that has a this attribute. In addition, SWIG_NewPointerObj() can automatically generate a proxy class object (if applicable). -34.10 Docstring Features+36.10 Docstring FeaturesUsing docstrings in Python code is becoming more and more important and more tools are coming on the scene that take advantage of them, everything from full-blown documentation generators to class browsers @@ -44662,7 +49360,7 @@ bool function_name(int x, int y, Foo* foo=NULL, Bar* bar=NULL); docstrings to your modules, functions and methods that can then be used by the various tools out there to make the programming experience of your users much simpler. -34.10.1 Module docstring+36.10.1 Module docstringPython allows a docstring at the beginning of the .py file before any other statements, and it is typically used to give a general description of the entire module. SWIG supports this by setting an @@ -44685,7 +49383,7 @@ layout of controls on a panel, etc. to be loaded from an XML file." %module(docstring=DOCSTRING) xrc 34.10.2 %feature("autodoc")+36.10.2 %feature("autodoc")As alluded to above SWIG will generate all the function and method proxy wrappers with just "*args" (or "*args, **kwargs" if the -keyword option is used) for a parameter list and will then sort out the @@ -44706,7 +49404,7 @@ layout of controls on a panel, etc. to be loaded from an XML file." four levels for autodoc controlled by the value given to the feature, %feature("autodoc", "level"). The four values for level are covered in the following sub-sections. -34.10.2.1 %feature("autodoc", "0")+36.10.2.1 %feature("autodoc", "0")When level "0" is used then the types of the parameters will not be included in the autodoc string. For example, given this function prototype: @@ -44724,7 +49422,7 @@ def function_name(*args, **kwargs): ... -34.10.2.2 %feature("autodoc", "1")+36.10.2.2 %feature("autodoc", "1")When level "1" is used then the parameter types will be used in the autodoc string. In addition, an attempt is made to simplify the type name such that it makes more sense to the Python user. @@ -44741,21 +49439,24 @@ def function_name(*args, **kwargs): ... - 34.10.2.3 %feature("autodoc", "2")+36.10.2.3 %feature("autodoc", "2")Level "2" results in the function prototype as per level "0". In - addition, a line of documentation is generated for each parameter. - Using the previous example, the generated code will be: + addition, a line of documentation is generated for each parameter using + +numpydoc style. Using the previous example, the generated code will + be:def function_name(*args, **kwargs): """ function_name(x, y, foo=None, bar=None) -> bool - Parameters: - x: int - y: int - foo: Foo * - bar: Bar * + Parameters + ---------- + x: int + y: int + foo: Foo * + bar: Bar * """ ... @@ -44780,16 +49481,17 @@ def function_name(*args, **kwargs): """ function_name(x, y, foo=None, bar=None) -> bool - Parameters: - x (C++ type: int) -- Input x dimension - y: int - foo: Foo * - bar: Bar * + Parameters + ---------- + x (C++ type: int) -- Input x dimension + y: int + foo: Foo * + bar: Bar * """ 34.10.2.4 %feature("autodoc", "3")+36.10.2.4 %feature("autodoc", "3")Level "3" results in the function prototype as per level "1" but also contains the same additional line of documentation for each parameter as per level "2". Using our earlier example again, the @@ -44800,17 +49502,18 @@ def function_name(*args, **kwargs): """ function_name(int x, int y, Foo foo=None, Bar bar=None) -> bool - Parameters: - x: int - y: int - foo: Foo * - bar: Bar * + Parameters + ---------- + x: int + y: int + foo: Foo * + bar: Bar * """ ... - 34.10.2.5 %feature("autodoc", "docstring")+36.10.2.5 %feature("autodoc", "docstring")Finally, there are times when the automatically generated autodoc string will make no sense for a Python programmer, particularly when a typemap is involved. So if you give an explicit value for the autodoc @@ -44822,7 +49525,7 @@ def function_name(*args, **kwargs): void GetPosition(int* OUTPUT, int* OUTPUT); - 34.10.3 %feature("docstring")+36.10.3 %feature("docstring")In addition to the autodoc strings described above, you can also attach any arbitrary descriptive text to a node in the parse tree with the "docstring" feature. When the proxy module is generated then any @@ -44844,10 +49547,67 @@ with more than one line. """ - 34.11 Python Packages-Using the package option of the %module directive - allows you to specify what Python package that the module will be - living in when installed. +36.11 Python Packages+Python has concepts of modules and packages. Modules are separate + units of code and may be grouped together to form a package. Packages + may be nested, that is they may contain subpackages. This leads to + tree-like hierarchy, with packages as intermediate nodes and modules as + leaf nodes. +The hierarchy of Python packages/modules follows the hierarchy of +*.py files found in a source tree (or, more generally, in the + Python path). Normally, the developer creates new module by placing a +*.py file somewhere under Python path; the module is then named + after that *.py file. A package is created by placing an +__init__.py file within a directory; the package is then named + after that directory. For example, the following source tree: +
+
++mod1.py +pkg1/__init__.py +pkg1/mod2.py +pkg1/pkg2/__init__.py +pkg1/pkg2/mod3.py ++ defines the following Python packages and modules: +
+
++pkg1 # package +pkg1.pkg2 # package +mod1 # module +pkg1.mod2 # module +pkg1.pkg2.mod3 # module ++ The purpose of an __init__.py file is two-fold. First, the + existence of __init__.py in a directory informs the Python + interpreter that this directory contains a Python package. Second, the + code in __init__.py is loaded/executed automatically when the + package is initialized (when it or its submodule/subpackage gets +import'ed). By default, SWIG generates proxy Python code – one +*.py file for each *.i interface. The __init__.py + files, however, are not generated by SWIG. They should be created by + other means. Both files (module *.py and __init__.py) + should be installed in appropriate destination directories in order to + obtain a desirable package/module hierarchy. +Python3 adds another option for packages with +PEP 0420 (implicit namespace packages). Implicit namespace packages + no longer use __init__.py files. SWIG generated Python modules support + implicit namespace packages. See +36.11.5 Implicit Namespace Packages for more information. +If you place a SWIG generated module into a Python package then + there are details concerning the way SWIG +searches for the wrapper module that you may want to familiarize + yourself with. +The way Python defines its modules and packages impacts SWIG users. + Some users may need to use special features such as the package + option in the %module directive or import related command line + options. These are explained in the following sections. +36.11.1 Setting the Python package ++Using the package option in the %module directive + allows you to specify a Python package that the module will be in when + installed. %module(package="wx") xrc @@ -44856,12 +49616,474 @@ with more than one line.
Now if one simply used import pkg1.pkg2, it will usually + fail: +
+
++>>> import pkg1.pkg2 +Traceback (most recent call last): + File "<stdin>", line 1, in <module> + File "./pkg1/pkg2/__init__.py", line 2, in <module> + from .bar import Bar + File "./pkg1/pkg2/bar.py", line 3, in <module> + class Bar(pkg1.pkg2.foo.Foo): pass +AttributeError: 'module' object has no attribute 'pkg2' ++ Surprisingly, if we execute the import pkg1.pkg2 directive + for the second time, it succeeds. The reason seems to be following: + when Python spots the from .bar import Bar directive in +pkg1/pkg2/__init__.py it starts loading pkg1/pkg2/bar.py. + This module imports pkg1.pkg2.foo in turn and tries to use +pkg1.pkg2.foo.Foo, but the package pkg1 is not fully + initialized yet (the initialization procedure is actually in progress) + and it seems like the effect of the already seen import + pkg1.pkg2.pkg3.foo is "delayed" or ignored. Exactly the same may + happen to a proxy module generated by SWIG. +One workaround for this case is to use a relative import in +pkg1/pkg2/bar.py. If we change bar.py to be: +
+
++from .pkg3 import foo +class Bar(foo.Foo): pass ++ or +
+
++from . import pkg3 +from .pkg3 import foo +class Bar(pkg3.foo.Foo): pass ++ then the example works again. With SWIG, you need to enable the +-relativeimport option in order to have the above workaround in + effect (note, that the Python 2 case also needs the -relativeimport + workaround). +36.11.5 Implicit + Namespace Packages+Python 3.3 introduced +PEP 0420 which implements implicit namespace packages. In a + nutshell, implicit namespace packages remove the requirement of an + __init__.py file and allow packages to be split across multiple PATH + elements. For example: +
+
++/fragment1/pkg1/mod1.py +/fragment2/pkg1/mod2.py +/fragment3/pkg1/mod3.py ++ If PYTHONPATH is set to "/fragment1:/fragment2:/fragment3", then + mod1, mod2 and mod3 will be part of pkg1. This allows for splitting of + packages into separate pieces. This can be useful for SWIG generated + wrappers in the following way. +Suppose you create a SWIG wrapper for a module called robin. The + SWIG generated code consists of two files robin.py and _robin.so. You + wish to make these modules part of a subpackage (brave.sir). With + implicit namespace packages you can place these files in the following + configurations: +Using PYTHONPATH="/some/path" +
+
++/some/path/brave/sir/robin.py +/some/path/brave/sir/_robin.so ++ Using PYTHONPATH="/some/path:/some/other/path"
+
++/some/path/brave/sir/robin.py +/some/other/path/brave/sir/_robin.so ++ Finally suppose that your pure python code is stored in a .zip file + or some other way (database, web service connection, etc). Python can + load the robin.py module using a custom importer. But the _robin.so + module will need to be located on a file system. Implicit namespace + packages make this possible. For example, using + PYTHONPATH="/some/path/foo.zip:/some/other/path" +Contents of foo.zip +
+
++brave/ +brave/sir/ +brave/sir/robin.py ++ File system contents +
+
++/some/other/path/brave/sir/_robin.so ++ Support for implicit namespace packages was added to python-3.3. The + zipimporter requires python-3.5.1 or newer to work with subpackages. +Compatibility Note: Support for implicit namespace packages + was added in SWIG-3.0.9. +36.11.6 Searching for the wrapper + module+When SWIG creates wrappers from an interface file, say foo.i, two + Python modules are created. There is a pure Python module module + (foo.py) and C/C++ code which is built and linked into a dynamically + (or statically) loaded module _foo (see the +Preliminaries section for details). So, the interface file really + defines two Python modules. How these two modules are loaded is covered + next. +The pure Python module needs to load the C/C++ module in order to + link to the wrapped C/C++ methods. To do this it must make some + assumptions about what package the C/C++ module may be located in. The + approach the pure Python module uses to find the C/C++ module is as + follows: +
As an example suppose foo.i is compiled into foo.py and _foo.so. + Assuming /dir is on PYTHONPATH, then the two modules can be installed + and used in the following ways: +36.11.6.1 Both + modules in the same package+Both modules are in one package: +
+
++/dir/package/foo.py +/dir/package/__init__.py +/dir/package/_foo.so ++ And imported with +
+
++from package import foo ++ 36.11.6.2 Split + modules+The pure python module is in a package and the C/C++ module is + global: +
+
++/dir/package/foo.py +/dir/package/__init__.py +/dir/_foo.so ++ And imported with +
+
++from package import foo ++ 36.11.6.3 Both + modules are global+Both modules are global: +
+
++/dir/foo.py +/dir/_foo.so ++ And imported with +
+
++import foo ++ If _foo is statically linked into an embedded Python interpreter, + then it may or may not be in a Python package. This depends in the + exact way the module was loaded statically. The above search order will + still be used for statically loaded modules. So, one may place the + module either globally or in a package as desired. +36.11.6.4 Statically linked C + modules+It is strongly recommended to use dynamically linked modules for the + C portion of your pair of Python modules. If for some reason you still + need to link the C module of the pair of Python modules generated by + SWIG into your interpreter, then this section provides some details on + how this impacts the pure Python modules ability to locate the other + part of the pair. Please also see the Static + Linking section. +When Python is extended with C code the Python interpreter needs to + be informed about details of the new C functions that have been linked + into the executable. The code to do this is created by SWIG and is + automatically called in the correct way when the module is dynamically + loaded. However when the code is not dynamically loaded (because it is + statically linked) Then the initialization method for the module + created by SWIG is not called automatically and the Python interpreter + has no idea that the new SWIG C module exists. +Before Python 3, one could simply call the init method created by + SWIG which would have normally been called when the shared object was + dynamically loaded. The specific name of this method is not given here + because statically linked modules are not encouraged with SWIG ( +Static Linking). However one can find this init function in the C + file generated by SWIG. +If you are really keen on static linking there are two ways to + initialize the SWIG generated C module with the init method. Which way + you use depends on what version of Python your module is being linked + with. Python 2 and Python 3 treat this init function differently. And + the way they treat it affects how the pure Python module will be able + to locate the C module. +The details concerning this are covered completly in the + documentation for Python itself. Links to the relavent sections follow: + +There are two keys things to understand. The first is that in Python + 2 the init() function returns void. In Python 3 the init() function + returns a PyObject * which points to the new module. Secondly, when you + call the init() method manually, you are the Python importer. So, you + determine which package the C module will be located in. +So, if you are using Python 3 it is important that you follow what is + described in the Python documentation linked above. In particular, you + can't simply call the init() function generated by SWIG and cast the + PyObject pointer it returns over the side. If you do then Python 3 will + have no idea that your C module exists and the pure Python half of your + wrapper will not be able to find it. You need to register your module + with the Python interpreter as described in the Python docs. +With Python 2 things are somewhat more simple. In this case the init + function returns void. Calling it will register your new C module as a + global module. The pure Python part of the SWIG wrapper will be + able to find it because it tries both the pure Python module it is part + of and the global module. If you wish not to have the statically linked + module be a global module then you will either need to refer to the + Python documentation on how to do this (remember you are now the Python + importer) or use dynamic linking. +36.12 Python 3 SupportSWIG is able to support Python 3.0. The wrapper code generated by SWIG can be compiled with both Python 2.x or 3.0. Further more, by passing the -py3 command line option to SWIG, wrapper code @@ -44878,7 +50100,7 @@ with more than one line. The following are Python 3.0 new features that are currently supported by SWIG. -34.12.1 Function annotation+36.12.1 Function annotationThe -py3 option will enable function annotation support. When used SWIG is able to generate proxy method definitions like this:
@@ -44898,9 +50120,9 @@ with more than one line.
may be append depend on whether you enabled the keyword argument. This
fallback is due to all overloaded functions share the same function in
SWIG generated proxy class.
-
- For detailed usage of function annotation, see
+ For detailed usage of function annotation, see
PEP 3107. Buffer protocols were revised in Python 3. SWIG also gains a series
of new typemaps to support buffer interfaces. These typemap macros are
defined in pybuffer.i, which must be included in order to use
@@ -44992,42 +50214,239 @@ bytearray(b'FOO\x00')
immutable buffers. As a result, the wrapped function should not modify
the buffer. %pybuffer_string(parm) -
- This macro maps an object's buffer as a string pointer parm -. It is similar to %pybuffer_mutable_string but the buffer - could be both mutable and immutable. And your function should not - modify the buffer. +%pybuffer_string(parm) +
+
+This macro maps an object's buffer as a string pointer parm +. It is similar to %pybuffer_mutable_string but the buffer + could be both mutable and immutable. And your function should not + modify the buffer. +36.12.3 Abstract base classes+By including pyabc.i and using the -py3 command + line option when calling SWIG, the proxy classes of the STL containers + will automatically gain an appropriate abstract base class. For + example, the following SWIG interface: +
+
++%include <pyabc.i> +%include <std_map.i> +%include <std_list.i> + +namespace std { + %template(Mapii) map<int, int>; + %template(IntList) list<int>; +} ++ will generate a Python proxy class Mapii inheriting from +collections.MutableMap and a proxy class IntList + inheriting from collections.MutableSequence. +pyabc.i also provides a macro %pythonabc that + could be used to define an abstract base class for your own C++ class: +
+
++%pythonabc(MySet, collections.MutableSet); ++ For details of abstract base class, please see +PEP 3119. +36.12.4 Byte string output conversion+By default, any byte string (char* or std::string) + returned from C or C++ code is decoded to text as UTF-8. This decoding + uses the surrogateescape error handler under Python 3.1 or + higher -- this error handler decodes invalid byte sequences to high + surrogate characters in the range U+DC80 to U+DCFF. As an example, + consider the following SWIG interface, which exposes a byte string that + cannot be completely decoded as UTF-8: +
+
++%module example + +%include <std_string.i> + +%inline %{ + +const char* non_utf8_c_str(void) { + return "h\xe9llo w\xc3\xb6rld"; +} + +%} ++ When this method is called from Python 3, the return value is the + following text string: +
+
++>>> s = example.non_utf8_c_str() +>>> s +'h\udce9llo wörld' ++ Since the C string contains bytes that cannot be decoded as UTF-8, + those raw bytes are represented as high surrogate characters that can + be used to obtain the original byte sequence: +
+
++>>> b = s.encode('utf-8', errors='surrogateescape') +>>> b +b'h\xe9llo w\xc3\xb6rld' ++ One can then attempt a different encoding, if desired (or simply + leave the byte string as a raw sequence of bytes for use in binary + protocols): +
+
++>>> b.decode('latin-1') +'héllo wörld' ++ Note, however, that text strings containing surrogate characters are + rejected with the default strict codec error handler. For + example: +
+
++>>> with open('test', 'w') as f: +... print(s, file=f) +... +Traceback (most recent call last): + File "<stdin>", line 2, in <module> +UnicodeEncodeError: 'utf-8' codec can't encode character '\udce9' in position 1: surrogates not allowed ++ This requires the user to check most strings returned by SWIG + bindings, but the alternative is for a non-UTF8 byte string to be + completely inaccessible in Python 3 code. +For more details about the surrogateescape error handler, + please see PEP 383 +. +In some cases, users may wish to instead handle all byte strings as + bytes objects in Python 3. This can be accomplished by adding +SWIG_PYTHON_STRICT_BYTE_CHAR to the generated code: +
+
++%module char_to_bytes +%begin %{ +#define SWIG_PYTHON_STRICT_BYTE_CHAR +%} + +char *charstring(char *s) { + return s; +} ++ This will modify the behavior so that only Python 3 bytes objects + will be accepted and converted to a C/C++ string, and any string + returned from C/C++ will be converted to a bytes object in Python 3: +
+
++>>> from char_to_bytes import * +>>> charstring(b"hi") # Byte string +b'hi' +>>> charstring("hi") # Unicode string +Traceback (most recent call last): + File "<stdin>", line 1, in ? +TypeError: in method 'charstring', argument 1 of type 'char *' ++ Note that in Python 2, defining SWIG_PYTHON_STRICT_BYTE_CHAR + has no effect, since strings in Python 2 are equivalent to Python 3 + bytes objects. However, there is a similar capability to force + unicode-only handling for wide characters C/C++ strings (wchar_t * + or std::wstring types) in Python 2. By default, in Python 2 + both strings and unicode strings are converted to C/C++ wide strings, + and returned wide strings are converted to a Python unicode string. To + instead only convert unicode strings to wide strings, users can add +SWIG_PYTHON_STRICT_UNICODE_WCHAR to the generated code: +
+
++%module wchar_to_unicode +%begin %{ +#define SWIG_PYTHON_STRICT_UNICODE_WCHAR +%} + +wchar_t *wcharstring(wchar_t *s) { + return s; +} ++ This ensures that only unicode strings are accepted by wcharstring + in both Python 2 and Python 3: +
+
++>>> from wchar_to_unicode import * +>>> wcharstring(u"hi") # Unicode string +u'hi' +>>> wcharstring(b"hi") # Byte string +Traceback (most recent call last): + File "<stdin>", line 1, in ? +TypeError: in method 'charstring', argument 1 of type 'wchar_t *' ++ By defining both SWIG_PYTHON_STRICT_BYTE_CHAR and +SWIG_PYTHON_STRICT_UNICODE_WCHAR, Python wrapper code can support + overloads taking both std::string (as Python bytes) and std::wstring + (as Python unicode). +36.12.5 Python 2 Unicode+A Python 3 string is a Unicode string so by default a Python 3 + string that contains Unicode characters passed to C/C++ will be + accepted and converted to a C/C++ string (char * or +std::string types). A Python 2 string is not a unicode string by + default and should a Unicode string be passed to C/C++ it will fail to + convert to a C/C++ string (char * or std::string + types). The Python 2 behavior can be made more like Python 3 by + defining SWIG_PYTHON_2_UNICODE when compiling the generated + C/C++ code. By default when the following is wrapped: +
+
-+%module unicode_strings +char *charstring(char *s) { + return s; +} + 34.12.3 Abstract base classes-By including pyabc.i and using the -py3 command - line option when calling SWIG, the proxy classes of the STL containers - will automatically gain an appropriate abstract base class. For - example, the following SWIG interface: +An error will occur when using Unicode strings in Python 2: +
+
++>>> from unicode_strings import * +>>> charstring("hi") +'hi' +>>> charstring(u"hi") +Traceback (most recent call last): + File "<stdin>", line 1, in ? +TypeError: in method 'charstring', argument 1 of type 'char *' ++ When the SWIG_PYTHON_2_UNICODE macro is added to the + generated code: -%include <pyabc.i> -%include <std_map.i> -%include <std_list.i> +%module unicode_strings +%begin %{ +#define SWIG_PYTHON_2_UNICODE +%} -namespace std { - %template(Mapii) map<int, int>; - %template(IntList) list<int>; +char *charstring(char *s) { + return s; } will generate a Python proxy class Mapii inheriting from -collections.MutableMap and a proxy class IntList - inheriting from collections.MutableSequence. -pyabc.i also provides a macro %pythonabc that - could be used to define an abstract base class for your own C++ class: -
+
-Unicode strings will be successfully accepted and converted from + UTF-8, but note that they are returned as a normal Python 2 string: +-%pythonabc(MySet, collections.MutableSet); +>>> from unicode_strings import * +>>> charstring("hi") +'hi' +>>> charstring(u"hi") +'hi' +>>> For details of abstract base class, please see -PEP 3119. +Note that defining both SWIG_PYTHON_2_UNICODE and +SWIG_PYTHON_STRICT_BYTE_CHAR at the same time is not allowed, since + the first is allowing unicode conversion and the second is explicitly + prohibiting it. @@ -45041,7 +50460,7 @@ PEP 3119.- 35 SWIG and R+37 SWIG and R
@@ -45062,13 +50481,13 @@ www.r-project.org. The R bindings are under active development. They
have been used to compile and run an R interface to QuantLib running on
Mandriva Linux with gcc. The R bindings also work on Microsoft Windows
using Visual C++.
-
-35.1 Bugs+37.1 BugsCurrently the following features are not implemented or broken:
35.2 Using R and SWIG+37.2 Using R and SWIGTo use R and SWIG in C mode, execute the following commands where example.c is the name of the file with the functions in them
@@ -45116,7 +50535,26 @@ cacheMetaData(1)
The cacheMetaData(1) will cause R to refresh its object tables.
Without it, inheritance of wrapped objects may fail.
These two files can be loaded in any order -35.3 Precompiling large R files+If you are compiling code yourself (not using R itself), there are a + few things to watch out for: +
37.3 Precompiling large R filesIn cases where the R file is large, one make save a lot of loading time by precompiling the R wrapper. This can be done by creating the file makeRData.R which contains the following @@ -45127,30 +50565,30 @@ q(save="no") This will generate a compiled R file called BigFile.RData that will save a large amount of loading time. -35.4 General policy+37.4 General policyThe general policy of the module is to treat the C/C++ as a basic wrapping over the underlying functions and rely on the R type system to provide R syntax. -35.5 Language conventions+37.5 Language conventionsgetitem and setitem use C++ conventions (i.e. zero based indices). [ -35.6 C++ classes+37.6 C++ classesC++ objects are implemented as external pointer objects with the class being the mangled name of the class. The C++ classes are encapsulated as an SEXP with an external pointer type. The class is the mangled name of the class. The nice thing about R is that is allows you to keep track of the pointer object which removes the necessity for a lot of the proxy class baggage you see in other languages. -35.7 Enumerations+37.7 Enumerationsenumerations are characters which are then converted back and forth to ints before calling the C routines. All of the enumeration code is done in R. - 36 SWIG and Ruby+38 SWIG and Ruby
@@ -45187,7 +50625,13 @@ slices)
This chapter describes SWIG's support of Ruby. -36.1 Preliminaries-SWIG 1.3 is known to work with Ruby versions 1.6 and later. Given + 38.1 Preliminaries+SWIG 3.0 is known to work with Ruby versions 1.8 and later. Given the choice, you should use the latest stable version of Ruby. You should also determine if your system supports shared libraries and dynamic loading. SWIG will work with or without dynamic loading, but @@ -45308,7 +50752,7 @@ slices) found in earlier chapters. At the very least, make sure you also read the "SWIG Basics" chapter. It is also assumed that the reader has a basic understanding of Ruby. -36.1.1 Running SWIG+38.1.1 Running SWIGTo build a Ruby module, run SWIG using the -ruby option: $ swig -ruby example.i @@ -45323,13 +50767,13 @@ slices) if compiling a C++ extension) that contains all of the code needed to build a Ruby extension module. To finish building the module, you need to compile this file and link it with the rest of your program. - will result in an extension module using the feature name "example" and Ruby module name "Example". -36.1.5 Static linking+38.1.5 Static linkingAn alternative approach to dynamic linking is to rebuild the Ruby interpreter with your extension module added to it. In the past, this approach was sometimes necessary due to limitations in dynamic loading @@ -45427,14 +50880,14 @@ puts "Your login name: #{Etc.getlogin}" the Ruby source, adding an entry to the ext/Setup file, adding your directory to the list of extensions in the file, and finally rebuilding Ruby. -36.1.6 Compilation of C++ extensions+38.1.6 Compilation of C++ extensionsOn most machines, C++ extension modules should be linked using the C++ compiler. For example: $ swig -c++ -ruby example.i -$ g++ -c example.cxx -$ g++ -c example_wrap.cxx -I/usr/local/lib/ruby/1.6/i686-linux +$ g++ -fPIC -c example.cxx +$ g++ -fPIC -c example_wrap.cxx -I/usr/include/ruby-2.1.0 $ g++ -shared example.o example_wrap.o -o example.so 36.2 Building Ruby Extensions under Windows - 95/NT+38.2 Building Ruby Extensions under Windows 95/NT +Building a SWIG extension to Ruby under Windows 95/NT is roughly similar to the process used with Unix. Normally, you will want to produce a DLL that can be loaded into the Ruby interpreter. For all @@ -45473,7 +50926,7 @@ C:\swigtest> nmake install order to build extensions, you may need to download the source distribution to the Ruby package, as you will need the Ruby header files. -36.2.1 Running SWIG from Developer Studio+38.2.1 Running SWIG from Developer StudioIf you are developing your application within Microsoft developer studio, SWIG can be invoked as a custom build option. The process roughly follows these steps : @@ -45529,10 +50982,10 @@ C:\swigtest> ruby run.rb Foo = 3.036.3 The Ruby-to-C/C++ Mapping+38.3 The Ruby-to-C/C++ MappingThis section describes the basics of how SWIG maps C or C++ declarations in your SWIG interface files to Ruby constructs. -36.3.1 Modules+38.3.1 ModulesThe SWIG %module directive specifies the name of the Ruby module. If you specify:
@@ -45566,3539 +51019,5413 @@ Foo = 3.0
$ swig -ruby -prefix "foo::bar::" example.i
-Starting with SWIG 1.3.20, you can also choose to wrap everything - into the global module by specifying the -globalmodule option - on the SWIG command line, i.e. -
- -$ swig -ruby -globalmodule example.i -+ Starting with SWIG 1.3.20, you can also choose to wrap everything + into the global module by specifying the -globalmodule option + on the SWIG command line, i.e. +
+
++$ swig -ruby -globalmodule example.i ++ Note that this does not relieve you of the requirement of specifying + the SWIG module name with the %module directive (or the +-module command-line option) as described earlier. +When choosing a module name, do not use the same name as a built-in + Ruby command or standard module name, as the results may be + unpredictable. Similarly, if you're using the -globalmodule + option to wrap everything into the global module, take care that the + names of your constants, classes and methods don't conflict with any of + Ruby's built-in names. +38.3.2 Functions+Global functions are wrapped as Ruby module methods. For example, + given the SWIG interface file example.i: +
+
+%module example + +int fact(int n);+ and C source file example.c: +
+
+int fact(int n) { + if (n == 0) + return 1; + return (n * fact(n-1)); +}+ SWIG will generate a method fact in the Example module + that can be used like so: +
+
+$ irb +irb(main):001:0> require 'example' +true +irb(main):002:0> Example.fact(4) +24+ 38.3.3 Variable Linking+C/C++ global variables are wrapped as a pair of singleton methods + for the module: one to get the value of the global variable and one to + set it. For example, the following SWIG interface file declares two + global variables: +
+
+// SWIG interface file with global variables +%module example +... +%inline %{ + extern int variable1; + extern double Variable2; +%} +...+ Now look at the Ruby interface: +
+
+$ irb +irb(main):001:0> require 'Example' +true +irb(main):002:0> Example.variable1 = 2 +2 +irb(main):003:0> Example.Variable2 = 4 * 10.3 +41.2 +irb(main):004:0> Example.Variable2 +41.2+ If you make an error in variable assignment, you will receive an + error message. For example: +
+
+irb(main):005:0> Example.Variable2 = "hello" +TypeError: no implicit conversion to float from string +from (irb):5:in `Variable2=' +from (irb):5+ If a variable is declared as const, it is wrapped as a + read-only variable. Attempts to modify its value will result in an + error. +To make ordinary variables read-only, you can also use the +%immutable directive. For example: +
+
+%immutable; +%inline %{ + extern char *path; +%} +%mutable;+ The %immutable directive stays in effect until it is + explicitly disabled using %mutable. +38.3.4 Constants+C/C++ constants are wrapped as module constants initialized to the + appropriate value. To create a constant, use #define or the +%constant directive. For example: +
+
+#define PI 3.14159 +#define VERSION "1.0" + +%constant int FOO = 42; +%constant const char *path = "/usr/local"; + +const int BAR = 32;+ Remember to use the :: operator in Ruby to get at these constant + values, e.g. +
+
+$ irb +irb(main):001:0> require 'Example' +true +irb(main):002:0> Example::PI +3.14159+ 38.3.5 Pointers+"Opaque" pointers to arbitrary C/C++ types (i.e. types that aren't + explicitly declared in your SWIG interface file) are wrapped as data + objects. So, for example, consider a SWIG interface file containing + only the declarations: +
+
+Foo *get_foo(); +void set_foo(Foo *foo);+ For this case, the get_foo() method returns an instance of an + internally generated Ruby class: +
+
+irb(main):001:0> foo = Example::get_foo() +#<SWIG::TYPE_p_Foo:0x402b1654>+ A NULL pointer is always represented by the Ruby nil + object. +38.3.6 Structures+C/C++ structs are wrapped as Ruby classes, with accessor methods + (i.e. "getters" and "setters") for all of the struct members. For + example, this struct declaration: +
+
+struct Vector { + double x, y; +};+ gets wrapped as a Vector class, with Ruby instance methods +x, x=, y and y=. These methods can be + used to access structure data from Ruby as follows: +
+
+$ irb +irb(main):001:0> require 'Example' +true +irb(main):002:0> f = Example::Vector.new +#<Example::Vector:0x4020b268> +irb(main):003:0> f.x = 10 +nil +irb(main):004:0> f.x +10.0+ Similar access is provided for unions and the public data members of + C++ classes. +const members of a structure are read-only. Data members can + also be forced to be read-only using the %immutable directive + (in C++, private may also be used). For example: +
+
+struct Foo { + ... + %immutable; + int x; /* Read-only members */ + char *name; + %mutable; + ... +};+ When char * members of a structure are wrapped, the + contents are assumed to be dynamically allocated using malloc + or new (depending on whether or not SWIG is run with the +-c++ option). When the structure member is set, the old contents + will be released and a new value created. If this is not the behavior + you want, you will have to use a typemap (described shortly). +Array members are normally wrapped as read-only. For example, this + code: +
+
+struct Foo { + int x[50]; +};+ produces a single accessor function like this: +
+
+int *Foo_x_get(Foo *self) { + return self->x; +};+ If you want to set an array member, you will need to supply a + "memberin" typemap described in the +section on typemaps. As a special case, SWIG does generate code to + set array members of type char (allowing you to store a Ruby + string in the structure). +When structure members are wrapped, they are handled as pointers. For + example, +
+
+struct Foo { + ... +}; + +struct Bar { + Foo f; +};+ generates accessor functions such as this: +
+
+Foo *Bar_f_get(Bar *b) { + return &b->f; +} + +void Bar_f_set(Bar *b, Foo *val) { + b->f = *val; +}+ 38.3.7 C++ classes+Like structs, C++ classes are wrapped by creating a new Ruby class + of the same name with accessor methods for the public class member + data. Additionally, public member functions for the class are wrapped + as Ruby instance methods, and public static member functions are + wrapped as Ruby singleton methods. So, given the C++ class declaration: +
+
+class List { +public: + List(); + ~List(); + int search(char *item); + void insert(char *item); + void remove(char *item); + char *get(int n); + int length; + static void print(List *l); +};+ SWIG would create a List class with: +
In Ruby, these functions are used as follows: +
+
+require 'Example' + +l = Example::List.new + +l.insert("Ale") +l.insert("Stout") +l.insert("Lager") +Example.print(l) +l.length() +----- produces the following output +Lager +Stout +Ale +3+ 38.3.8 C++ Inheritance+The SWIG type-checker is fully aware of C++ inheritance. Therefore, + if you have classes like this: +
+
+class Parent { + ... +}; + +class Child : public Parent { + ... +};+ those classes are wrapped into a hierarchy of Ruby classes that + reflect the same inheritance structure. All of the usual Ruby utility + methods work normally: +
+
+irb(main):001:0> c = Child.new +#<Bar:0x4016efd4> +irb(main):002:0> c.instance_of? Child +true +irb(main):003:0> b.instance_of? Parent +false +irb(main):004:0> b.is_a? Child +true +irb(main):005:0> b.is_a? Parent +true +irb(main):006:0> Child < Parent +true +irb(main):007:0> Child > Parent +false+ Furthermore, if you have a function like this: +
+
+void spam(Parent *f);+ then the function spam() accepts Parent* or a + pointer to any class derived from Parent. +Until recently, the Ruby module for SWIG didn't support multiple + inheritance, and this is still the default behavior. This doesn't mean + that you can't wrap C++ classes which inherit from multiple base + classes; it simply means that only the first base class listed + in the class declaration is considered, and any additional base classes + are ignored. As an example, consider a SWIG interface file with a + declaration like this: +
+
+class Derived : public Base1, public Base2 +{ + ... +};+ For this case, the resulting Ruby class (Derived) will only + consider Base1 as its superclass. It won't inherit any of +Base2's member functions or data and it won't recognize Base2 + as an "ancestor" of Derived (i.e. the is_a? + relationship would fail). When SWIG processes this interface file, + you'll see a warning message like: +
+
+example.i:5: Warning 802: Warning for Derived: Base Base2 ignored. +Multiple inheritance is not supported in Ruby.+ Starting with SWIG 1.3.20, the Ruby module for SWIG provides limited + support for multiple inheritance. Because the approach for dealing with + multiple inheritance introduces some limitations, this is an optional + feature that you can activate with the -minherit command-line + option: +
+
++$ swig -c++ -ruby -minherit example.i ++ Using our previous example, if your SWIG interface file contains a + declaration like this: +
+
+class Derived : public Base1, public Base2 +{ + ... +};+ and you run SWIG with the -minherit command-line option, + then you will end up with a Ruby class Derived that appears to + "inherit" the member data and functions from both Base1 and +Base2. What actually happens is that three different top-level + classes are created, with Ruby's Object class as their + superclass. Each of these classes defines a nested module named +Impl, and it's in these nested Impl modules that the + actual instance methods for the classes are defined, i.e. +
+
+class Base1 + module Impl + # Define Base1 methods here + end + include Impl +end + +class Base2 + module Impl + # Define Base2 methods here + end + include Impl +end + +class Derived + module Impl + include Base1::Impl + include Base2::Impl + # Define Derived methods here + end + include Impl +end+ Observe that after the nested Impl module for a class is + defined, it is mixed-in to the class itself. Also observe that the +Derived::Impl module first mixes-in its base classes' Impl + modules, thus "inheriting" all of their behavior. +The primary drawback is that, unlike the default mode of operation, + neither Base1 nor Base2 is a true superclass of +Derived anymore: +
+
+obj = Derived.new +obj.is_a? Base1 # this will return false... +obj.is_a? Base2 # ... and so will this+ In most cases, this is not a serious problem since objects of type +Derived will otherwise behave as though they inherit from both +Base1 and Base2 (i.e. they exhibit +"Duck Typing"). +38.3.9 C++ Overloaded Functions+C++ overloaded functions, methods, and constructors are mostly + supported by SWIG. For example, if you have two functions like this: +
+
+void foo(int); +void foo(char *c);+ You can use them in Ruby in a straightforward manner: +
+
+irb(main):001:0> foo(3) # foo(int) +irb(main):002:0> foo("Hello") # foo(char *c)+ Similarly, if you have a class like this, +
+
+class Foo { +public: + Foo(); + Foo(const Foo &); + ... +};+ you can write Ruby code like this: +
+
+irb(main):001:0> f = Foo.new # Create a Foo +irb(main):002:0> g = Foo.new(f) # Copy f+ Overloading support is not quite as flexible as in C++. Sometimes + there are methods that SWIG can't disambiguate. For example: +
+
+void spam(int); +void spam(short);+ or +
+
+void foo(Bar *b); +void foo(Bar &b);+ If declarations such as these appear, you will get a warning message + like this: +
+
++example.i:12: Warning 509: Overloaded method spam(short) effectively ignored, +example.i:11: Warning 509: as it is shadowed by spam(int). ++ To fix this, you either need to ignore or rename one of the methods. + For example: +
+
+%rename(spam_short) spam(short); +... +void spam(int); +void spam(short); // Accessed as spam_short+ or +
+
+%ignore spam(short); +... +void spam(int); +void spam(short); // Ignored+ SWIG resolves overloaded functions and methods using a + disambiguation scheme that ranks and sorts declarations according to a + set of type-precedence rules. The order in which declarations appear in + the input does not matter except in situations where ambiguity + arises--in this case, the first declaration takes precedence. +Please refer to the "SWIG and C++" chapter + for more information about overloading. +38.3.10 C++ Operators+For the most part, overloaded operators are handled automatically by + SWIG and do not require any special treatment on your part. So if your + class declares an overloaded addition operator, e.g. +
+
+class Complex { + ... + Complex operator+(Complex &); + ... +};+ the resulting Ruby class will also support the addition (+) method + correctly. +For cases where SWIG's built-in support is not sufficient, C++ + operators can be wrapped using the %rename directive + (available on SWIG 1.3.10 and later releases). All you need to do is + give the operator the name of a valid Ruby identifier. For example: +
+
+%rename(add_complex) operator+(Complex &, Complex &); +... +Complex operator+(Complex &, Complex &);+ Now, in Ruby, you can do this: +
+
-a = Example::Complex.new(2, 3) +b = Example::Complex.new(4, -1) +c = Example.add_complex(a, b) Note that this does not relieve you of the requirement of specifying - the SWIG module name with the %module directive (or the --module command-line option) as described earlier. -When choosing a module name, do not use the same name as a built-in - Ruby command or standard module name, as the results may be - unpredictable. Similarly, if you're using the -globalmodule - option to wrap everything into the global module, take care that the - names of your constants, classes and methods don't conflict with any of - Ruby's built-in names. -36.3.2 Functions-Global functions are wrapped as Ruby module methods. For example, - given the SWIG interface file example.i: +More details about wrapping C++ operators into Ruby operators is + discussed in the section on + operator overloading. +38.3.11 C++ namespaces+SWIG is aware of C++ namespaces, but namespace names do not appear + in the module nor do namespaces result in a module that is broken up + into submodules or packages. For example, if you have a file like this, %module example -int fact(int n);- and C source file example.c: -
-
-int fact(int n) { - if (n == 0) - return 1; - return (n * fact(n-1)); -}+namespace foo { + int fact(int n); + struct Vector { + double x,y,z; + }; +}; SWIG will generate a method fact in the Example module - that can be used like so: +it works in Ruby as follows:
-
-$ irb -irb(main):001:0> require 'example' +irb(main):001:0> require 'example' true -irb(main):002:0> Example.fact(4) -24+irb(main):002:0> Example.fact(3) +6 +irb(main):003:0> v = Example::Vector.new +#<Example::Vector:0x4016f4d4> +irb(main):004:0> v.x = 3.4 +3.4 +irb(main):004:0> v.y +0.0 36.3.3 Variable Linking-C/C++ global variables are wrapped as a pair of singleton methods - for the module: one to get the value of the global variable and one to - set it. For example, the following SWIG interface file declares two - global variables: +If your program has more than one namespace, name conflicts (if any) + can be resolved using %rename For example:
-
+// SWIG interface file with global variables -%module example -... -%inline %{ - extern int variable1; - extern double Variable2; +%rename(Bar_spam) Bar::spam; + +namespace Foo { + int spam(); +} + +namespace Bar { + int spam(); +}+ If you have more than one namespace and your want to keep their + symbols separate, consider wrapping them as separate SWIG modules. For + example, make the module name the same as the namespace and create + extension modules for each namespace separately. If your program + utilizes thousands of small deeply nested namespaces each with + identical symbol names, well, then you get what you deserve. +38.3.12 C++ templates+C++ templates don't present a huge problem for SWIG. However, in + order to create wrappers, you have to tell SWIG to create wrappers for + a particular template instantiation. To do this, you use the +%template directive. For example: +
+
-%module example + +%{ +#include "pair.h" %} -...+ +template<class T1, class T2> +struct pair { + typedef T1 first_type; + typedef T2 second_type; + T1 first; + T2 second; + pair(); + pair(const T1&, const T2&); + ~pair(); +}; + +%template(Pairii) pair<int,int>; Now look at the Ruby interface: +In Ruby:
-
-$ irb -irb(main):001:0> require 'Example' +irb(main):001:0> require 'example' true -irb(main):002:0> Example.variable1 = 2 -2 -irb(main):003:0> Example.Variable2 = 4 * 10.3 -41.2 -irb(main):004:0> Example.Variable2 -41.2+irb(main):002:0> p = Example::Pairii.new(3, 4) +#<Example:Pairii:0x4016f4df> +irb(main):003:0> p.first +3 +irb(main):004:0> p.second +4 If you make an error in variable assignment, you will receive an - error message. For example: -
- irb(main):005:0> Example.Variable2 = "hello" -TypeError: no implicit conversion to float from string -from (irb):5:in `Variable2=' -from (irb):5+ 38.3.13 C++ Standard Template Library (STL) ++On a related note, the standard SWIG library contains a number of + modules that provide typemaps for standard C++ library classes (such as + std::pair, std::string and std::vector). + These library modules don't provide wrappers around the templates + themselves, but they do make it convenient for users of your extension + module to pass Ruby objects (such as arrays and strings) to wrapped C++ + code that expects instances of standard C++ templates. For example, + suppose the C++ library you're wrapping has a function that expects a + vector of floats: +
+
-%module example + +float sum(const std::vector<float>& values); If a variable is declared as const, it is wrapped as a - read-only variable. Attempts to modify its value will result in an - error. -To make ordinary variables read-only, you can also use the -%immutable directive. For example: +Rather than go through the hassle of writing an "in" typemap to + convert an array of Ruby numbers into a std::vector<float>, you can + just use the std_vector.i module from the standard SWIG + library:
-
-%immutable; -%inline %{ - extern char *path; -%} -%mutable;+ %module example + +%include std_vector.i +float sum(const std::vector<float>& values); The %immutable directive stays in effect until it is - explicitly disabled using %mutable. -36.3.4 Constants-C/C++ constants are wrapped as module constants initialized to the - appropriate value. To create a constant, use #define or the -%constant directive. For example: +Ruby's STL wrappings provide additional methods to make them behave + more similarly to Ruby's native classes. +Thus, you can do, for example: +
+
+v = IntVector.new +v << 2 +v << 3 +v << 4 +v.each { |x| puts x } + +=> 2 +3 +4 +v.delete_if { |x| x == 3 } +=> [2,4]+ The SWIG Ruby module provides also the ability for all the STL + containers to carry around Ruby native objects (Fixnum, Classes, etc) + making them act almost like Ruby's own Array, Hash, etc. To do that, + you need to define a container that contains a swig::GC_VALUE, like:
-
-#define PI 3.14159 -#define VERSION "1.0" ++%module nativevector -%constant int FOO = 42; -%constant const char *path = "/usr/local"; +%{ +std::vector< swig::GC_VALUE > NativeVector; +%} -const int BAR = 32;+%template(NativeVector) std::vector< swig::GC_VALUE >; + Remember to use the :: operator in Ruby to get at these constant - values, e.g. -
- $ irb -irb(main):001:0> require 'Example' -true -irb(main):002:0> Example::PI -3.14159+ This vector can then contain any Ruby object, making them almost + identical to Ruby's own Array class. +
+
-require 'nativevector' +include NativeVector + +v = NativeVector.new +v << 1 +v << [1,2] +v << 'hello' + +class A; end + +v << A.new + +puts v +=> [1, [1,2], 'hello', #<A:0x245325>] + 36.3.5 Pointers-"Opaque" pointers to arbitrary C/C++ types (i.e. types that aren't - explicitly declared in your SWIG interface file) are wrapped as data - objects. So, for example, consider a SWIG interface file containing - only the declarations: +Obviously, there is a lot more to template wrapping than shown in + these examples. More details can be found in the +SWIG and C++ chapter. +38.3.14 C++ STL Functors+Some containers in the STL allow you to modify their default behavior + by using so called functors or function objects. Functors are often + just a very simple struct with operator() redefined or an + actual C/C++ function. This allows you, for example, to always keep the + sort order of a STL container to your liking. +The Ruby STL mappings allows you to modify those containers that + support functors using Ruby procs or methods, instead. Currently, this + includes std::set, set::map, std::multiset + and std::multimap. +The functors in swig are called swig::UnaryFunction and +swig::BinaryFunction. For C++ predicates (ie. functors that must + return bool as a result) swig::UnaryPredicate and +swig::BinaryPredicate are provided. +As an example, if given this swig file:
-
-Foo *get_foo(); -void set_foo(Foo *foo);+ +%module intset; + +%include <std_set.i> + +%template(IntSet) std::set< int, swig::BinaryPredicate >; + For this case, the get_foo() method returns an instance of an - internally generated Ruby class: -
- irb(main):001:0> foo = Example::get_foo() -#<SWIG::TYPE_p_Foo:0x402b1654>+ You can then use the set from Ruby with or without a proc object as a + predicate: +
+
-+require 'intset' +include Intset + +# Default sorting behavior defined in C++ +a = IntSet.new +a << 1 +a << 2 +a << 3 +a +=> [1,2,3] + +# Custom sorting behavior defined by a Ruby proc +b = IntSet.new( proc { |a,b| a > b } ) +b << 1 +b << 2 +b << 3 +b +=> [3,2,1] + A NULL pointer is always represented by the Ruby nil - object. -36.3.6 Structures-C/C++ structs are wrapped as Ruby classes, with accessor methods - (i.e. "getters" and "setters") for all of the struct members. For - example, this struct declaration: +38.3.15 C++ STL Iterators+The STL is well known for the use of iterators. There are a number of + iterators possible with different properties, but in general there are + two main categories: const iterators and non-const iterators. The const + iterators can access and not modify the values they point at, while the + non-const iterators can both read and modify the values. +The Ruby STL wrappings support both type of iterators by using a + proxy class in-between. This proxy class is swig::Iterator or +swig::ConstIterator. Derived from them are template classes that + need to be initialized with the actual iterator for the container you + are wrapping and often times with the beginning and ending points of + the iteration range. +The SWIG STL library already provides typemaps to all the standard + containers to do this wrapping automatically for you, but if you have + your own STL-like iterator, you will need to write your own typemap for + them. For out typemaps, the special functions make_const_iterator + and make_nonconst_iterator are provided. +These can be used either like:
-
-struct Vector { - double x, y; -};+ +make_const_iterator( iterator, rubyclass ); +make_const_iterator( iterator, iterator_begin, iterator_end, rubyclass ); + gets wrapped as a Vector class, with Ruby instance methods -x, x=, y and y=. These methods can be - used to access structure data from Ruby as follows: -
- $ irb -irb(main):001:0> require 'Example' -true -irb(main):002:0> f = Example::Vector.new -#<Example::Vector:0x4020b268> -irb(main):003:0> f.x = 10 -nil -irb(main):004:0> f.x -10.0+ The iterators support a next() and previous() + member function to just change the iterator without returning anything. + previous() should obviously only be used for bidirectional + iterators. You can also advance the iterator multiple steps by using + standard math operations like +=. +The value the iterator points at can be accessed with value() + -- this is equivalent to dereferencing it with *i. For + non-const iterators, a value=() function is also provided + which allows you to change the value pointed by the iterator. This is + equivalent to the C++ construct of dereferencing and assignment, like +*i = something. +Thus, given say a vector class of doubles defined as: +
+
-+%module doublevector + +%include std_vector.i + +%template(DoubleVector) std::vector<double>; + Similar access is provided for unions and the public data members of - C++ classes. -const members of a structure are read-only. Data members can - also be forced to be read-only using the %immutable directive - (in C++, private may also be used). For example: +Its iterator can then be used from Ruby like: +
+
++require 'doublevector' +include Doublevector + +v = DoubleVector.new +v << 1 +v << 2 +v << 3 + +# +# an elaborate and less efficient way of doing v.map! { |x| x+2 } +# +i = v.begin +e = v.end +while i != e + val = i.value + val += 2 + i.value = val + i.next +end +i +>> [3, 4, 5 ] ++ If you'd rather have STL classes without any iterators, you should + define -DSWIG_NO_EXPORT_ITERATOR_METHODS when running swig. +38.3.16 C++ Smart Pointers+38.3.16.1 The shared_ptr + Smart Pointer+The C++11 standard provides std::shared_ptr which was + derived from the Boost implementation, boost::shared_ptr. Both + of these are available for Ruby in the SWIG library and usage is + outlined in the shared_ptr smart + pointer library section. +38.3.16.2 Generic Smart + Pointers+In certain C++ programs, it is common to use classes that have been + wrapped by so-called "smart pointers." Generally, this involves the use + of a template class that implements operator->() like this:
-
-struct Foo { +template<class T> class SmartPtr { ... - %immutable; - int x; /* Read-only members */ - char *name; - %mutable; + T *operator->(); ... -};+} When char * members of a structure are wrapped, the - contents are assumed to be dynamically allocated using malloc - or new (depending on whether or not SWIG is run with the --c++ option). When the structure member is set, the old contents - will be released and a new value created. If this is not the behavior - you want, you will have to use a typemap (described shortly). -Array members are normally wrapped as read-only. For example, this - code: +Then, if you have a class like this,
-
-struct Foo { - int x[50]; +class Foo { +public: + int x; + int bar(); }; produces a single accessor function like this: +A smart pointer would be used in C++ as follows:
-
-int *Foo_x_get(Foo *self) { - return self->x; -};+ SmartPtr<Foo> p = CreateFoo(); // Created somehow (not shown) +... +p->x = 3; // Foo::x +int y = p->bar(); // Foo::bar If you want to set an array member, you will need to supply a - "memberin" typemap described in the -section on typemaps. As a special case, SWIG does generate code to - set array members of type char (allowing you to store a Ruby - string in the structure). -When structure members are wrapped, they are handled as pointers. For - example, +To wrap this in Ruby, simply tell SWIG about the SmartPtr + class and the low-level Foo object. Make sure you instantiate +SmartPtr using %template if necessary. For example:
-
-struct Foo { - ... -}; - -struct Bar { - Foo f; -};+ %module example +... +%template(SmartPtrFoo) SmartPtr<Foo>; +... generates accessor functions such as this: +Now, in Ruby, everything should just "work": +
+
+irb(main):001:0> p = Example::CreateFoo() # Create a smart-pointer somehow +#<Example::SmartPtrFoo:0x4016f4df> +irb(main):002:0> p.x = 3 # Foo::x +3 +irb(main):003:0> p.bar() # Foo::bar+ If you ever need to access the underlying pointer returned by +operator->() itself, simply use the __deref__() method. + For example: +
+
+irb(main):004:0> f = p.__deref__() # Returns underlying Foo *+ 38.3.17 Cross-Language Polymorphism+SWIG's Ruby module supports cross-language polymorphism (a.k.a. the + "directors" feature) similar to that for SWIG's Python module. Rather + than duplicate the information presented in the +Python chapter, this section just notes the differences that you + need to be aware of when using this feature with Ruby. +38.3.17.1 Exception Unrolling+Whenever a C++ director class routes one of its virtual member + function calls to a Ruby instance method, there's always the + possibility that an exception will be raised in the Ruby code. By + default, those exceptions are ignored, which simply means that the + exception will be exposed to the Ruby interpreter. If you would like to + change this behavior, you can use the %feature("director:except") + directive to indicate what action should be taken when a Ruby exception + is raised. The following code should suffice in most cases:
-
-Foo *Bar_f_get(Bar *b) { - return &b->f; -} - -void Bar_f_set(Bar *b, Foo *val) { - b->f = *val; +%feature("director:except") { + throw Swig::DirectorMethodException($error); } 36.3.7 C++ classes-Like structs, C++ classes are wrapped by creating a new Ruby class - of the same name with accessor methods for the public class member - data. Additionally, public member functions for the class are wrapped - as Ruby instance methods, and public static member functions are - wrapped as Ruby singleton methods. So, given the C++ class declaration: +When this feature is activated, the call to the Ruby instance method + is "wrapped" using the rb_rescue2() function from Ruby's C + API. If any Ruby exception is raised, it will be caught here and a C++ + exception is raised in its place. +38.4 Naming+Ruby has several common naming conventions. Constants are generally + in upper case, module and class names are in camel case and methods are + in lower case with underscores. For example: +
+
+
Prior to version 1.3.28, SWIG did not support these Ruby conventions. + The only modifications it made to names was to capitalize the first + letter of constants (which includes module and class names). +SWIG 1.3.28 introduces the new -autorename command line parameter. + When this parameter is specified, SWIG will automatically change + constant, class and method names to conform with the standard Ruby + naming conventions. For example: +
+
+$ swig -ruby -autorename example.i ++ To disable renaming use the -noautorename command line option. +Since this change significantly changes the wrapper code generated by + SWIG, it is turned off by default in SWIG 1.3.28. However, it is + planned to become the default option in future releases. +38.4.1 Defining Aliases+It's a fairly common practice in the Ruby built-ins and standard + library to provide aliases for method names. For example, + Array#size is an alias for Array#length. If you would + like to provide an alias for one of your class' instance methods, one + approach is to use SWIG's %extend directive to add a new + method of the aliased name that calls the original function. For + example:
-
-class List { +class MyArray { public: - List(); - ~List(); - int search(char *item); - void insert(char *item); - void remove(char *item); - char *get(int n); - int length; - static void print(List *l); -};- SWIG would create a List class with: -
In Ruby, these functions are used as follows: -
-
-require 'Example' + // Construct an empty array + MyArray(); -l = Example::List.new + // Return the size of this array + size_t length() const; +}; -l.insert("Ale") -l.insert("Stout") -l.insert("Lager") -Example.print(l) -l.length() ------ produces the following output -Lager -Stout -Ale -3+%extend MyArray { + // MyArray#size is an alias for MyArray#length + size_t size() const { + return $self->length(); + } +} + 36.3.8 C++ Inheritance-The SWIG type-checker is fully aware of C++ inheritance. Therefore, - if you have classes like this: +A better solution is to use the %alias directive (unique to + SWIG's Ruby module). The previous example could then be rewritten as:
-
-class Parent { - ... -}; +// MyArray#size is an alias for MyArray#length +%alias MyArray::length "size"; -class Child : public Parent { - ... +class MyArray { +public: + // Construct an empty array + MyArray(); + + // Return the size of this array + size_t length() const; }; those classes are wrapped into a hierarchy of Ruby classes that - reflect the same inheritance structure. All of the usual Ruby utility - methods work normally: -
-
-irb(main):001:0> c = Child.new -#<Bar:0x4016efd4> -irb(main):002:0> c.instance_of? Child -true -irb(main):003:0> b.instance_of? Parent -false -irb(main):004:0> b.is_a? Child -true -irb(main):005:0> b.is_a? Parent -true -irb(main):006:0> Child < Parent -true -irb(main):007:0> Child > Parent -false- Furthermore, if you have a function like this: +Multiple aliases can be associated with a method by providing a + comma-separated list of aliases to the %alias directive, e.g.
-
-void spam(Parent *f);+ %alias MyArray::length "amount,quantity,size"; then the function spam() accepts Parent* or a - pointer to any class derived from Parent. -Until recently, the Ruby module for SWIG didn't support multiple - inheritance, and this is still the default behavior. This doesn't mean - that you can't wrap C++ classes which inherit from multiple base - classes; it simply means that only the first base class listed - in the class declaration is considered, and any additional base classes - are ignored. As an example, consider a SWIG interface file with a - declaration like this: +From an end-user's standpoint, there's no functional difference + between these two approaches; i.e. they should get the same result from + calling either MyArray#size or MyArray#length. + However, when the %alias directive is used, SWIG doesn't need + to generate all of the wrapper code that's usually associated with + added methods like our MyArray::size() example. +Note that the %alias directive is implemented using SWIG's + "features" mechanism and so the same name matching rules used for other + kinds of features apply (see the chapter on +"Customization Features") for more details). +38.4.2 Predicate Methods+Ruby methods that return a boolean value and end in a question mark + are known as predicate methods. Examples of predicate methods in + standard Ruby classes include Array#empty? (which returns +true for an array containing no elements) and + Object#instance_of? (which returns true if the object is + an instance of the specified class). For consistency with Ruby + conventions, methods that return boolean values should be marked as + predicate methods. +One cumbersome solution to this problem is to rename the method + (using SWIG's %rename directive) and provide a custom typemap + that converts the function's actual return type to Ruby's true + or false. For example:
-
-class Derived : public Base1, public Base2 -{ - ... -};- For this case, the resulting Ruby class (Derived) will only - consider Base1 as its superclass. It won't inherit any of -Base2's member functions or data and it won't recognize Base2 - as an "ancestor" of Derived (i.e. the is_a? - relationship would fail). When SWIG processes this interface file, - you'll see a warning message like: -
-
-example.i:5: Warning 802: Warning for Derived: Base Base2 ignored. -Multiple inheritance is not supported in Ruby.- Starting with SWIG 1.3.20, the Ruby module for SWIG provides limited - support for multiple inheritance. Because the approach for dealing with - multiple inheritance introduces some limitations, this is an optional - feature that you can activate with the -minherit command-line - option: -
-
--$ swig -c++ -ruby -minherit example.i -+ %rename("is_it_safe?") is_it_safe(); + +%typemap(out) int is_it_safe "$result = ($1 != 0) ? Qtrue : Qfalse;"; + +int is_it_safe(); Using our previous example, if your SWIG interface file contains a - declaration like this: +A better solution is to use the %predicate directive + (unique to SWIG's Ruby module) to designate a method as a predicate + method. For the previous example, this would look like:
-
-class Derived : public Base1, public Base2 -{ - ... -};- and you run SWIG with the -minherit command-line option, - then you will end up with a Ruby class Derived that appears to - "inherit" the member data and functions from both Base1 and -Base2. What actually happens is that three different top-level - classes are created, with Ruby's Object class as their - superclass. Each of these classes defines a nested module named -Impl, and it's in these nested Impl modules that the - actual instance methods for the classes are defined, i.e. -
-
-class Base1 - module Impl - # Define Base1 methods here - end - include Impl -end - -class Base2 - module Impl - # Define Base2 methods here - end - include Impl -end +%predicate is_it_safe(); -class Derived - module Impl - include Base1::Impl - include Base2::Impl - # Define Derived methods here - end - include Impl -end+int is_it_safe(); Observe that after the nested Impl module for a class is - defined, it is mixed-in to the class itself. Also observe that the -Derived::Impl module first mixes-in its base classes' Impl - modules, thus "inheriting" all of their behavior. -The primary drawback is that, unlike the default mode of operation, - neither Base1 nor Base2 is a true superclass of -Derived anymore: +This method would be invoked from Ruby code like this:
-
-obj = Derived.new -obj.is_a? Base1 # this will return false... -obj.is_a? Base2 # ... and so will this+ irb(main):001:0> Example::is_it_safe? +true In most cases, this is not a serious problem since objects of type -Derived will otherwise behave as though they inherit from both -Base1 and Base2 (i.e. they exhibit -"Duck Typing"). -36.3.9 C++ Overloaded Functions-C++ overloaded functions, methods, and constructors are mostly - supported by SWIG. For example, if you have two functions like this: +The %predicate directive is implemented using SWIG's + "features" mechanism and so the same name matching rules used for other + kinds of features apply (see the chapter on +"Customization Features") for more details). +38.4.3 Bang Methods+Ruby methods that modify an object in-place and end in an + exclamation mark are known as bang methods. An example of a bang method + is Array#sort! which changes the ordering of items in an + array. Contrast this with Array#sort, which returns a copy of + the array with the items sorted instead of modifying the original + array. For consistency with Ruby conventions, methods that modify + objects in place should be marked as bang methods. +Bang methods can be marked using the %bang directive which + is unique to the Ruby module and was introduced in SWIG 1.3.28. For + example:
-
-void foo(int); -void foo(char *c);+ %bang sort(int arr[]); + +int sort(int arr[]); You can use them in Ruby in a straightforward manner: -
- irb(main):001:0> foo(3) # foo(int) -irb(main):002:0> foo("Hello") # foo(char *c)+ This method would be invoked from Ruby code like this: +
+
-irb(main):001:0> Example::sort!(arr) Similarly, if you have a class like this, +The %bang directive is implemented using SWIG's "features" + mechanism and so the same name matching rules used for other kinds of + features apply (see the chapter on +"Customization Features") for more details). +38.4.4 Getters and Setters+Often times a C++ library will expose properties through getter and + setter methods. For example: class Foo { -public: - Foo(); - Foo(const Foo &); - ... + Foo() {} + int getValue() { return value_; } + void setValue(int value) { value_ = value; } + +private: + int value_; }; you can write Ruby code like this: -
- irb(main):001:0> f = Foo.new # Create a Foo -irb(main):002:0> g = Foo.new(f) # Copy f+ By default, SWIG will expose these methods to Ruby as get_value + and set_value. However, it more natural for these methods to + be exposed in Ruby as value and value=. That allows + the methods to be used like this: +
+
-irb(main):001:0> foo = Foo.new() +irb(main):002:0> foo.value = 5 +irb(main):003:0> puts foo.value Overloading support is not quite as flexible as in C++. Sometimes - there are methods that SWIG can't disambiguate. For example: +This can be done by using the %rename directive:
-
-void spam(int); -void spam(short);+ %rename("value") Foo::getValue(); +%rename("value=") Foo::setValue(int value); or +38.5 Input and output parameters+A common problem in some C programs is handling parameters passed as + simple pointers. For example:
-
-void foo(Bar *b); -void foo(Bar &b);+ void add(int x, int y, int *result) { + *result = x + y; +} If declarations such as these appear, you will get a warning message - like this: -
+ or +-example.i:12: Warning 509: Overloaded method spam(short) effectively ignored, -example.i:11: Warning 509: as it is shadowed by spam(int). -+int sub(int *x, int *y) { + return *x-*y; +} To fix this, you either need to ignore or rename one of the methods. - For example: +The easiest way to handle these situations is to use the +typemaps.i file. For example:
-
-%rename(spam_short) spam(short); -... -void spam(int); -void spam(short); // Accessed as spam_short+ %module Example +%include "typemaps.i" + +void add(int, int, int *OUTPUT); +int sub(int *INPUT, int *INPUT); or +In Ruby, this allows you to pass simple values. For example: +
+
+a = Example.add(3,4) +puts a +7 +b = Example.sub(7,4) +puts b +3+ Notice how the INPUT parameters allow integer values to be + passed instead of pointers and how the OUTPUT parameter + creates a return result. +If you don't want to use the names INPUT or OUTPUT, + use the %apply directive. For example:
-
-%ignore spam(short); -... -void spam(int); -void spam(short); // Ignored+ %module Example +%include "typemaps.i" + +%apply int *OUTPUT { int *result }; +%apply int *INPUT { int *x, int *y}; + +void add(int x, int y, int *result); +int sub(int *x, int *y); SWIG resolves overloaded functions and methods using a - disambiguation scheme that ranks and sorts declarations according to a - set of type-precedence rules. The order in which declarations appear in - the input does not matter except in situations where ambiguity - arises--in this case, the first declaration takes precedence. -Please refer to the "SWIG and C++" chapter - for more information about overloading. -36.3.10 C++ Operators-For the most part, overloaded operators are handled automatically by - SWIG and do not require any special treatment on your part. So if your - class declares an overloaded addition operator, e.g. +If a function mutates one of its parameters like this,
-
-class Complex { - ... - Complex operator+(Complex &); - ... -};+ void negate(int *x) { + *x = -(*x); +} the resulting Ruby class will also support the addition (+) method - correctly. -For cases where SWIG's built-in support is not sufficient, C++ - operators can be wrapped using the %rename directive - (available on SWIG 1.3.10 and later releases). All you need to do is - give the operator the name of a valid Ruby identifier. For example: +you can use INOUT like this:
-
-%rename(add_complex) operator+(Complex &, Complex &); +%include "typemaps.i" ... -Complex operator+(Complex &, Complex &);+void negate(int *INOUT); Now, in Ruby, you can do this: +In Ruby, a mutated parameter shows up as a return value. For example:
-
-a = Example::Complex.new(2, 3) -b = Example::Complex.new(4, -1) -c = Example.add_complex(a, b)+ a = Example.negate(3) +print a +-3 More details about wrapping C++ operators into Ruby operators is - discussed in the section on - operator overloading. -36.3.11 C++ namespaces-SWIG is aware of C++ namespaces, but namespace names do not appear - in the module nor do namespaces result in a module that is broken up - into submodules or packages. For example, if you have a file like this, +The most common use of these special typemap rules is to handle + functions that return more than one value. For example, sometimes a + function returns a result as well as a special error code: +
+
+/* send message, return number of bytes sent, success code, and error_code */ +int send_message(char *text, int *success, int *error_code);+ To wrap such a function, simply use the OUTPUT rule above. + For example: %module example - -namespace foo { - int fact(int n); - struct Vector { - double x,y,z; - }; -};+%include "typemaps.i" +... +int send_message(char *, int *OUTPUT, int *OUTPUT); it works in Ruby as follows: +When used in Ruby, the function will return an array of multiple + values.
-
-irb(main):001:0> require 'example' -true -irb(main):002:0> Example.fact(3) -6 -irb(main):003:0> v = Example::Vector.new -#<Example::Vector:0x4016f4d4> -irb(main):004:0> v.x = 3.4 -3.4 -irb(main):004:0> v.y -0.0- If your program has more than one namespace, name conflicts (if any) - can be resolved using %rename For example: -
-
-%rename(Bar_spam) Bar::spam; - -namespace Foo { - int spam(); -} - -namespace Bar { - int spam(); -}+ bytes, success, error_code = send_message("Hello World") +if not success + print "error #{error_code} : in send_message" +else + print "Sent", bytes +end If you have more than one namespace and your want to keep their - symbols separate, consider wrapping them as separate SWIG modules. For - example, make the module name the same as the namespace and create - extension modules for each namespace separately. If your program - utilizes thousands of small deeply nested namespaces each with - identical symbol names, well, then you get what you deserve. -36.3.12 C++ templates-C++ templates don't present a huge problem for SWIG. However, in - order to create wrappers, you have to tell SWIG to create wrappers for - a particular template instantiation. To do this, you use the -%template directive. For example: +Another way to access multiple return values is to use the +%apply rule. In the following example, the parameters rows and + columns are related to SWIG as OUTPUT values through the use + of %apply
-
%module example - -%{ -#include "pair.h" -%} - -template<class T1, class T2> -struct pair { - typedef T1 first_type; - typedef T2 second_type; - T1 first; - T2 second; - pair(); - pair(const T1&, const T2&); - ~pair(); -}; - -%template(Pairii) pair<int,int>;+ %module Example +%include "typemaps.i" +%apply int *OUTPUT { int *rows, int *columns }; +... +void get_dimensions(Matrix *m, int *rows, int*columns); In Ruby:
-
+irb(main):001:0> require 'example' -true -irb(main):002:0> p = Example::Pairii.new(3, 4) -#<Example:Pairii:0x4016f4df> -irb(main):003:0> p.first -3 -irb(main):004:0> p.second -4+ r, c = Example.get_dimensions(m)+ 38.6 Exception handling+38.6.1 Using the %exception directive+The SWIG %exception directive can be used to define a + user-definable exception handler that can convert C/C++ errors into + Ruby exceptions. The chapter on Customization + Features contains more details, but suppose you have a C++ class + like the following : +
+
-class DoubleArray { +private: + int n; + double *ptr; +public: + // Create a new array of fixed size + DoubleArray(int size) { + ptr = new double[size]; + n = size; + } + + // Destroy an array + ~DoubleArray() { + delete ptr; + } + + // Return the length of the array + int length() { + return n; + } + + // Get an array item and perform bounds checking. + double getitem(int i) { + if ((i >= 0) && (i < n)) + return ptr[i]; + else + throw RangeError(); + } + + // Set an array item and perform bounds checking. + void setitem(int i, double val) { + if ((i >= 0) && (i < n)) + ptr[i] = val; + else { + throw RangeError(); + } + } +}; 36.3.13 C++ Standard Template Library - (STL)-On a related note, the standard SWIG library contains a number of - modules that provide typemaps for standard C++ library classes (such as - std::pair, std::string and std::vector). - These library modules don't provide wrappers around the templates - themselves, but they do make it convenient for users of your extension - module to pass Ruby objects (such as arrays and strings) to wrapped C++ - code that expects instances of standard C++ templates. For example, - suppose the C++ library you're wrapping has a function that expects a - vector of floats: +Since several methods in this class can throw an exception for an + out-of-bounds access, you might want to catch this in the Ruby + extension by writing the following in an interface file:
-
-%module example +%exception { + try { + $action + } + catch (const RangeError&) { + static VALUE cpperror = rb_define_class("CPPError", rb_eStandardError); + rb_raise(cpperror, "Range error."); + } +} -float sum(const std::vector<float>& values);+class DoubleArray { + ... +}; Rather than go through the hassle of writing an "in" typemap to - convert an array of Ruby numbers into a std::vector<float>, you can - just use the std_vector.i module from the standard SWIG - library: +The exception handling code is inserted directly into generated + wrapper functions. When an exception handler is defined, errors can be + caught and used to gracefully raise a Ruby exception instead of forcing + the entire program to terminate with an uncaught error. +As shown, the exception handling code will be added to every wrapper + function. Because this is somewhat inefficient, you might consider + refining the exception handler to only apply to specific methods like + this:
-
-%module example - -%include std_vector.i -float sum(const std::vector<float>& values);- Ruby's STL wrappings provide additional methods to make them behave - more similarly to Ruby's native classes. -Thus, you can do, for example: -
-
-v = IntVector.new -v << 2 -v << 3 -v << 4 -v.each { |x| puts x } - -=> 2 -3 -4 -v.delete_if { |x| x == 3 } -=> [2,4]+ %exception getitem { + try { + $action + } catch (const RangeError&) { + static VALUE cpperror = rb_define_class("CPPError", rb_eStandardError); + rb_raise(cpperror, "Range error in getitem."); + } +} + +%exception setitem { + try { + $action + } catch (const RangeError&) { + static VALUE cpperror = rb_define_class("CPPError", rb_eStandardError); + rb_raise(cpperror, "Range error in setitem."); + } +} The SWIG Ruby module provides also the ability for all the STL - containers to carry around Ruby native objects (Fixnum, Classes, etc) - making them act almost like Ruby's own Array, Hash, etc. To do that, - you need to define a container that contains a swig::GC_VALUE, like: +In this case, the exception handler is only attached to methods and + functions named getitem and setitem. +Since SWIG's exception handling is user-definable, you are not + limited to C++ exception handling. See the chapter on +Customization Features for more examples. +38.6.2 Handling Ruby Blocks+One of the highlights of Ruby and most of its standard library is the + use of blocks, which allow the easy creation of continuations and other + niceties. Blocks in ruby are also often used to simplify the passing of + many arguments to a class. +In order to make your class constructor support blocks, you can take + advantage of the %exception directive, which will get run after the C++ + class' constructor was called. +For example, this yields the class over after its construction:
-
--%module nativevector - -%{ -std::vector< swig::GC_VALUE > NativeVector; -%} +class Window +{ +public: + Window(int x, int y, int w, int h); + // .... other methods here .... +}; -%template(NativeVector) std::vector< swig::GC_VALUE >; -+// Add support for yielding self in the Class' constructor. +%exception Window::Window { + $action + if (rb_block_given_p()) { + rb_yield(self); + } +} This vector can then contain any Ruby object, making them almost - identical to Ruby's own Array class. +Then, in ruby, it can be used like:
-
-require 'nativevector' -include NativeVector - -v = NativeVector.new -v << 1 -v << [1,2] -v << 'hello' - -class A; end - -v << A.new - -puts v -=> [1, [1,2], 'hello', #<A:0x245325>] ++Window.new(0,0,360,480) { |w| + w.color = Fltk::RED + w.border = false +} Obviously, there is a lot more to template wrapping than shown in - these examples. More details can be found in the -SWIG and C++ chapter. -36.3.14 C++ STL Functors-Some containers in the STL allow you to modify their default behavior - by using so called functors or function objects. Functors are often - just a very simple struct with operator() redefined or an - actual C/C++ function. This allows you, for example, to always keep the - sort order of a STL container to your liking. -The Ruby STL mappings allows you to modify those containers that - support functors using Ruby procs or methods, instead. Currently, this - includes std::set, set::map, std::multiset - and std::multimap. -The functors in swig are called swig::UnaryFunction and -swig::BinaryFunction. For C++ predicates (ie. functors that must - return bool as a result) swig::UnaryPredicate and -swig::BinaryPredicate are provided. -As an example, if given this swig file: +For other methods, you can usually use a dummy parameter with a + special in typemap, like: -%module intset; +// +// original function was: +// +// void func(int x); -%include <std_set.i> +%typemap(in,numinputs=0) int RUBY_YIELD_SELF { + if ( !rb_block_given_p() ) + rb_raise("No block given"); + return rb_yield(self); +} -%typemap(IntSet) std::set< int, swig::BinaryPredicate >; +%extend { + void func(int x, int RUBY_YIELD_SELF ); +} You can then use the set from Ruby with or without a proc object as a - predicate: -
- -require 'intset' -include Intset - -# Default sorting behavior defined in C++ -a = IntSet.new -a << 1 -a << 2 -a << 3 -a -=> [1,2,3] - -# Custom sorting behavior defined by a Ruby proc -b = IntSet.new( proc { |a,b| a > b } ) -b << 1 -b << 2 -b << 3 -b -=> [3,2,1] -+ For more information on typemaps, see Typemaps +. +38.6.3 Raising exceptions+There are three ways to raise exceptions from C++ code to Ruby. +The first way is to use SWIG_exception(int code, const char *msg) +. The following table shows the mappings from SWIG error codes to Ruby + exceptions: +
+
-
36.3.15 C++ STL Iterators-The STL is well known for the use of iterators. There are a number of - iterators possible with different properties, but in general there are - two main categories: const iterators and non-const iterators. The const - iterators can access and not modify the values they point at, while the - non-const iterators can both read and modify the values. -The Ruby STL wrappings support both type of iterators by using a - proxy class in-between. This proxy class is swig::Iterator or - swig::ConstIterator. Derived from them are template classes that - need to be initialized with the actual iterator for the container you - are wrapping and often times with the beginning and ending points of - the iteration range. -The SWIG STL library already provides typemaps to all the standard - containers to do this wrapping automatically for you, but if you have - your own STL-like iterator, you will need to write your own typemap for - them. For out typemaps, the special functions make_const_iterator - and make_nonconst_iterator are provided. -These can be used either like: +The second way to raise errors is to use SWIG_Raise(obj, type, + desc). Obj is a C++ instance of an exception class, type is a + string specifying the type of exception (for example, "MyError") and + desc is the SWIG description of the exception class. For example: -make_const_iterator( iterator, rubyclass ); -make_const_iterator( iterator, iterator_begin, iterator_end, rubyclass ); +%raise(SWIG_NewPointerObj(e, SWIGTYPE_p_AssertionFailedException, 0), ":AssertionFailedException", SWIGTYPE_p_AssertionFailedException); The iterators support a next() and previous() - member function to just change the iterator without returning anything. - previous() should obviously only be used for bidirectional - iterators. You can also advance the iterator multiple steps by using - standard math operations like +=. -The value the iterator points at can be accessed with value() - -- this is equivalent to dereferencing it with *i. For - non-const iterators, a value=() function is also provided - which allows you to change the value pointed by the iterator. This is - equivalent to the C++ construct of dereferencing and assignment, like -*i = something. -Thus, given say a vector class of doubles defined as: +This is useful when you want to pass the current exception object + directly to Ruby, particularly when the object is an instance of class + marked as an %exceptionclass (see the next section for more + information). +Last, you can raise an exception by directly calling Ruby's C api. + This is done by invoking the rb_raise() function. The first + argument passed to rb_raise() is the exception type. You can + raise a custom exception type or one of the built-in Ruby exception + types. +38.6.4 Exception classes+Starting with SWIG 1.3.28, the Ruby module supports the +%exceptionclass directive, which is used to identify C++ classes + that are used as exceptions. Classes that are marked with the +%exceptionclass directive are exposed in Ruby as child classes of +rb_eRuntimeError. This allows C++ exceptions to be directly mapped + to Ruby exceptions, providing for a more natural integration between + C++ code and Ruby code.
-
--%module doublevector +%exceptionclass CustomError; -%include std_vector.i +%inline %{ + class CustomError { }; -%template(DoubleVector) std::vector<double>; -+ class Foo { + public: + void test() { throw CustomError; } + }; +%} Its iterator can then be used from Ruby like: -
- -require 'doublevector' -include Doublevector - -v = DoubleVector.new -v << 1 -v << 2 -v << 3 - -# -# an elaborate and less efficient way of doing v.map! { |x| x+2 } -# -i = v.begin -e = v.end -while i != e - val = i.value - val += 2 - i.value = val - i.next -end -i ->> [3, 4, 5 ] -+ From Ruby you can now call this method like this: +
+
-foo = Foo.new +begin + foo.test() +rescue CustomError => e + puts "Caught custom error" +end If you'd rather have STL classes without any iterators, you should - define -DSWIG_NO_EXPORT_ITERATOR_METHODS when running swig. -36.3.16 C++ Smart Pointers-In certain C++ programs, it is common to use classes that have been - wrapped by so-called "smart pointers." Generally, this involves the use - of a template class that implements operator->() like this: +For another example look at swig/Examples/ruby/exception_class. +38.7 Typemaps+This section describes how you can modify SWIG's default wrapping + behavior for various C/C++ datatypes using the %typemap + directive. This is an advanced topic that assumes familiarity with the + Ruby C API as well as the material in the "Typemaps +" chapter. +Before proceeding, it should be stressed that typemaps are not a + required part of using SWIG---the default wrapping behavior is enough + in most cases. Typemaps are only used if you want to change some aspect + of the primitive C-Ruby interface. +38.7.1 What is a typemap?+A typemap is nothing more than a code generation rule that is + attached to a specific C datatype. The general form of this declaration + is as follows ( parts enclosed in [...] are optional ):
-
-template<class T> class SmartPtr { - ... - T *operator->(); - ... -}+ +%typemap( method [, modifiers...] ) typelist code; + Then, if you have a class like this, -
- class Foo { -public: - int x; - int bar(); -};+ method is a simply a name that specifies what kind of + typemap is being defined. It is usually a name like "in", +"out", or "argout" (or its director variations). The + purpose of these methods is described later. +modifiers is an optional comma separated list of +name="value" values. These are sometimes to attach extra + information to a typemap and is often target-language dependent. +typelist is a list of the C++ type patterns that the + typemap will match. The general form of this list is as follows: +
+
-typelist : typepattern [, typepattern, typepattern, ... ] ; + +typepattern : type [ (parms) ] + | type name [ (parms) ] + | ( typelist ) [ (parms) ] A smart pointer would be used in C++ as follows: -
- SmartPtr<Foo> p = CreateFoo(); // Created somehow (not shown) -... -p->x = 3; // Foo::x -int y = p->bar(); // Foo::bar+ Each type pattern is either a simple type, a simple type and + argument name, or a list of types in the case of multi-argument + typemaps. In addition, each type pattern can be parameterized with a + list of temporary variables (parms). The purpose of these variables + will be explained shortly. +code specifies the C code used in the typemap. It can take + any one of the following forms: +
+
-code : { ... } + | " ... " + | %{ ... %} To wrap this in Ruby, simply tell SWIG about the SmartPtr - class and the low-level Foo object. Make sure you instantiate -SmartPtr using %template if necessary. For example: +For example, to convert integers from Ruby to C, you might define a + typemap like this: %module example -... -%template(SmartPtrFoo) SmartPtr<Foo>; -...- Now, in Ruby, everything should just "work": -
-
-irb(main):001:0> p = Example::CreateFoo() # Create a smart-pointer somehow -#<Example::SmartPtrFoo:0x4016f4df> -irb(main):002:0> p.x = 3 # Foo::x -3 -irb(main):003:0> p.bar() # Foo::bar+ +%typemap(in) int { + $1 = (int) NUM2INT($input); + printf("Received an integer : %d\n",$1); +} + +%inline %{ + extern int fact(int n); +%} If you ever need to access the underlying pointer returned by -operator->() itself, simply use the __deref__() method. - For example: +Typemaps are always associated with some specific aspect of code + generation. In this case, the "in" method refers to the conversion of + input arguments to C/C++. The datatype int is the datatype to + which the typemap will be applied. The supplied C code is used to + convert values. In this code a number of special variables prefaced by + a $ are used. The $1 variable is placeholder for a + local variable of type int. The $input variable is + the input Ruby object. +When this example is compiled into a Ruby module, the following + sample code:
-
-irb(main):004:0> f = p.__deref__() # Returns underlying Foo *- 36.3.17 Cross-Language Polymorphism-SWIG's Ruby module supports cross-language polymorphism (a.k.a. the - "directors" feature) similar to that for SWIG's Python module. Rather - than duplicate the information presented in the -Python chapter, this section just notes the differences that you - need to be aware of when using this feature with Ruby. -36.3.17.1 Exception Unrolling-Whenever a C++ director class routes one of its virtual member - function calls to a Ruby instance method, there's always the - possibility that an exception will be raised in the Ruby code. By - default, those exceptions are ignored, which simply means that the - exception will be exposed to the Ruby interpreter. If you would like to - change this behavior, you can use the %feature("director:except") - directive to indicate what action should be taken when a Ruby exception - is raised. The following code should suffice in most cases: -
-
-%feature("director:except") { - throw Swig::DirectorMethodException($error); -}- When this feature is activated, the call to the Ruby instance method - is "wrapped" using the rb_rescue2() function from Ruby's C - API. If any Ruby exception is raised, it will be caught here and a C++ - exception is raised in its place. -36.4 Naming-Ruby has several common naming conventions. Constants are generally - in upper case, module and class names are in camel case and methods are - in lower case with underscores. For example: -
-
-
require 'example' + +puts Example.fact(6) Prior to version 1.3.28, SWIG did not support these Ruby conventions. - The only modifications it made to names was to capitalize the first - letter of constants (which includes module and class names). -SWIG 1.3.28 introduces the new -autorename command line parameter. - When this parameter is specified, SWIG will automatically change - constant, class and method names to conform with the standard Ruby - naming conventions. For example: +prints the result:
-
-$ swig -ruby -autorename example.i ++Received an integer : 6 +720 To disable renaming use the -noautorename command line option. -Since this change significantly changes the wrapper code generated by - SWIG, it is turned off by default in SWIG 1.3.28. However, it is - planned to become the default option in future releases. -36.4.1 Defining Aliases-It's a fairly common practice in the Ruby built-ins and standard - library to provide aliases for method names. For example, - Array#size is an alias for Array#length. If you would - like to provide an alias for one of your class' instance methods, one - approach is to use SWIG's %extend directive to add a new - method of the aliased name that calls the original function. For - example: -
- class MyArray { -public: - // Construct an empty array - MyArray(); - - // Return the size of this array - size_t length() const; -}; + |
---|