diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..800ac4669 --- /dev/null +++ b/.gitignore @@ -0,0 +1,127 @@ +# Compiled Source +*.o +*.class + +# Editor files and various other junk +*.sw? +*.bak + +# Local PCRE +pcre +*.gz + +# C/C++ object files, based on: +# https://github.com/github/gitignore/blob/master/C.gitignore +# https://github.com/github/gitignore/blob/master/C%2B%2B.gitignore +*.slo +*.lo + +# C/C++ dynamic libraries, based on: +# https://github.com/github/gitignore/blob/master/C.gitignore +# https://github.com/github/gitignore/blob/master/C%2B%2B.gitignore +*.dll +*.so +*.so.* +*.dylib + +# C/C++ static libraries, based on: +# https://github.com/github/gitignore/blob/master/C.gitignore +# https://github.com/github/gitignore/blob/master/C%2B%2B.gitignore +*.lib +*.lai +*.la +*.a + +# C/C++ executables, based on: +# https://github.com/github/gitignore/blob/master/C.gitignore +# https://github.com/github/gitignore/blob/master/C%2B%2B.gitignore +*.exe +*.out +*.app + +# Generated by autogen.sh +CCache/autom4te.cache/ +CCache/config.h.in +CCache/configure +Source/Include/swigconfig.h.in +Source/Makefile.in +Tools/config/compile +Tools/config/config.guess +Tools/config/config.sub +Tools/config/depcomp +Tools/config/install-sh +Tools/config/missing +Tools/config/ylwrap +aclocal.m4 +autom4te.cache/ +configure + +# Generated by ./configure +CCache/Makefile +CCache/ccache_swig_config.h +CCache/config.h +CCache/config.log +CCache/config.status +Examples/Makefile +Examples/guile/Makefile +Examples/test-suite/*/Makefile +Examples/xml/Makefile +Lib/ocaml/swigp4.ml +/Makefile +Source/Include/stamp-h1 +Source/Include/swigconfig.h +Source/Makefile +.deps +config.log +config.status +preinst-swig +swig.spec + +# Build Artifacts +.dirstamp +CCache/ccache-swig +Source/CParse/parser.c +Source/CParse/parser.h +Source/eswig +swig + +# Generated documentation +Doc/Manual/CCache.html +Doc/Manual/SWIGDocumentation.html +Doc/Manual/SWIGDocumentation.pdf +Doc/Manual/*.book + +# Test Suite Generated Files +Examples/test-suite/allegrocl/*/ +Examples/test-suite/cffi/*/ +Examples/test-suite/chicken/*/ +Examples/test-suite/clisp/*/ +Examples/test-suite/csharp/*/ +Examples/test-suite/d/*/ +Examples/test-suite/go/*/ +Examples/test-suite/guile/*/ +Examples/test-suite/guilescm/*/ +Examples/test-suite/java/*/ +Examples/test-suite/lua/*/ +Examples/test-suite/mzscheme/*/ +Examples/test-suite/ocaml/*/ +Examples/test-suite/octave/*/ +Examples/test-suite/perl5/*/ +Examples/test-suite/php/*/ +Examples/test-suite/pike/*/ +Examples/test-suite/python/*/ +Examples/test-suite/r/*/ +Examples/test-suite/ruby/*/ +Examples/test-suite/tcl/*/ +Examples/test-suite/uffi/*/ + +# Python generated files, based on: +# https://github.com/github/gitignore/blob/master/Python.gitignore +*.py[cod] +*/__pycache__/ +/__pycache__/ + +# C# generated files +*_runme.exe.mdb +*_runme.exe + diff --git a/.project b/.project deleted file mode 100644 index 86af75213..000000000 --- a/.project +++ /dev/null @@ -1,11 +0,0 @@ - - - SWIG - - - - - - - - diff --git a/ANNOUNCE b/ANNOUNCE index ad3e8f8d6..1c3297a5c 100644 --- a/ANNOUNCE +++ b/ANNOUNCE @@ -1,31 +1,31 @@ -*** ANNOUNCE: SWIG 2.0.1 (in progress) *** +*** ANNOUNCE: SWIG 2.0.10 (in progress) *** http://www.swig.org -We're pleased to announce SWIG-2.0.1, the latest SWIG release. +We're pleased to announce SWIG-2.0.10, the latest SWIG release. What is SWIG? ============= SWIG is a software development tool that reads C/C++ header files and generates the wrapper code needed to make C and C++ code accessible -from other languages including Perl, Python, Tcl, Ruby, PHP, Java, -Scheme (Guile, MzScheme, CHICKEN), Ocaml, Lua, Pike, C#, Modula-3, Octave, R, -Common Lisp (CLISP, Allegro CL, CFFI, UFFI). SWIG can also export its parse -tree in the form of XML and Lisp s-expressions. Major applications of -SWIG include generation of scripting language extension modules, rapid -prototyping, testing, and user interface development for large C/C++ -systems. +from other programming languages including Perl, Python, Tcl, Ruby, +PHP, C#, Go, Java, Lua, Scheme (Guile, MzScheme, CHICKEN), D, Ocaml, +Pike, Modula-3, Octave, R, Common Lisp (CLISP, Allegro CL, CFFI, UFFI). +SWIG can also export its parse tree in the form of XML and Lisp +s-expressions. Major applications of SWIG include generation of +scripting language extension modules, rapid prototyping, testing, +and user interface development for large C/C++ systems. Availability ============ The release is available for download on Sourceforge at - http://prdownloads.sourceforge.net/swig/swig-2.0.1.tar.gz + http://prdownloads.sourceforge.net/swig/swig-2.0.10.tar.gz A Windows version is also available at - http://prdownloads.sourceforge.net/swig/swigwin-2.0.1.zip + http://prdownloads.sourceforge.net/swig/swigwin-2.0.10.zip Please report problems with this release to the swig-devel mailing list, details at http://www.swig.org/mail.html. diff --git a/CCache/ccache.c b/CCache/ccache.c index d1696da88..e7dd1d30a 100644 --- a/CCache/ccache.c +++ b/CCache/ccache.c @@ -712,12 +712,13 @@ static void from_cache(int first) passfail = retrieve_from_cache(hashname, output_file, hardlink); } - free(stderr_file); if (passfail == -1) { close(fd_stderr); unlink(stderr_file); + free(stderr_file); return; } + free(stderr_file); } /* get rid of the intermediate preprocessor file */ diff --git a/CCache/configure.in b/CCache/configure.ac similarity index 100% rename from CCache/configure.in rename to CCache/configure.ac diff --git a/CHANGES b/CHANGES index f243ff7c6..8b1945ad9 100644 --- a/CHANGES +++ b/CHANGES @@ -3,6 +3,1403 @@ SWIG (Simplified Wrapper and Interface Generator) See the CHANGES.current file for changes in the current version. See the RELEASENOTES file for a summary of changes in each release. +Version 2.0.9 (16 December 2012) +================================ + +2012-12-16: wsfulton + Fix garbage line number / empty file name reporting for some missing + '}' or ')' error messages. + +2012-12-15: kkaempf + [Ruby] Apply patch 3530444, Class#methods and Class#constants returns array of + symbols in Ruby 1.9+ + +2012-12-14: kkaempf + [Ruby] Apply patch 3530439 and finally replace all occurrences of the STR2CSTR() macro + with StringValuePtr(). STR2CSTR was deprecated since years and got removed in Ruby 1.9 + +2012-12-14: kkaempf + [Ruby] Applied patches #3530442 and 3530443 to adapt compile and runtime include + paths to match Ruby 1.9+ + +2012-12-14: wsfulton + [CFFI] Fix #3161614 - Some string constants are incorrect + +2012-12-13: wsfulton + [CFFI] Fix #3529690 - Fix incorrect constant names. + +2012-12-12: drjoe + [R] add fix to finalizer that was missed earlier + +2012-12-11: wsfulton + [Python] Apply patch #3590522 - fully qualified package paths for Python 3 even if a module is in the + same package. + +2012-12-08: wsfulton + [Python] Bug #3563647 - PyInt_FromSize_t unavailable prior to Python 2.5 for unsigned int types. + +2012-12-08: wsfulton + [Perl] Fix bug #3571361 - C++ comment in C wrappers. + +2012-12-07: wsfulton + [C#] Apply patch #3571029 which adds missing director support for const unsigned long long &. + +2012-11-28: kwwette + [Octave] Simplified module loading: now just the syntax + $ example; + is accepted, which loads functions globally but constants and variables relative to the current scope. + This make module loading behaviour reliably consistent, and reduces problems when loading modules which + depend on other modules which may not have been previously loaded. + +2012-11-27: wsfulton + [cffi] Fix junk output when wrapping single character literal constants. + +2012-11-17: wsfulton + [Tcl, Modula3] Add missing support for -outdir. + +2012-11-17: wsfulton + Fix segfaults when using filename paths greater than 1024 characters in length. + +2012-11-14: wsfulton + [ccache-swig] Apply patch #3586392 from Frederik Deweerdt to fix some error cases - incorrectly using + memory after it has been deleted. + +2012-11-09: vzeitlin + [Python] Fix overflow when passing values greater than LONG_MAX from Python 3 for parameters with unsigned long C type. + +2012-11-09: wsfulton + Fix some feature matching issues for implicit destructors and implicit constructors and implicit + copy constructors added with %copyctor. Previously a feature for these had to be fully qualified + in order to match. Now the following will also match: + + %feature("xyz") ~XXX(); + struct XXX {}; + +2012-11-09: wsfulton + Further consistency in named output typemap lookups for implicit constructors and destructors and + implicit copy constructors added with %copyctor. Previously only the fully qualified name was being + used, now the unqualified name will also be used. For example, previously: + + example.i:38: Searching for a suitable 'out' typemap for: void Space::More::~More + Looking for: void Space::More::~More + Looking for: void + + Now the unqualified name is also used: + + example.i:38: Searching for a suitable 'out' typemap for: void Space::More::~More + Looking for: void Space::More::~More + Looking for: void ~More + Looking for: void + +2012-11-02: wsfulton + Fix some subtle named output typemap lookup misses, the fully qualified name was not always being + used for variables, for example: + + struct Glob { + int MyVar; + }; + + Previously the search rules (as shown by -debug-tmsearch) for the getter wrapper were: + + example.i:44: Searching for a suitable 'out' typemap for: int MyVar + Looking for: int MyVar + Looking for: int + + Now the scope is named correctly: + + example.i:44: Searching for a suitable 'out' typemap for: int Glob::MyVar + Looking for: int Glob::MyVar + Looking for: int MyVar + Looking for: int + +2012-10-26: wsfulton + Fix director typemap searching so that a typemap specified with a name will be correctly matched. Previously + the name was ignored during the typemap search. Applies to the following list of typemaps: + directorout, csdirectorout, cstype, imtype, ctype, ddirectorout, dtype, gotype, jtype, jni, javadirectorout. + +2012-10-11: wsfulton + Most of the special variables available for use in %exception are now also available for expansion in + %extend blocks. These are: $name $symname $overname $decl $fulldecl $parentname $parentsymname, see docs + on "Class extension" in SWIGPlus.html. Patch based on submission from Kris Thielemans. + +2012-10-10: wsfulton + Additional new special variables in %exception are expanded as follows: + $parentname - The parent class name (if any) for a method. + $parentsymname - The target language parent class name (if any) for a method. + +2012-10-08: iant + [Go] Generating Go code now requires using the -intgosize option to + indicate the size of the 'int' type in Go. This is because the + size of the type is changing from Go 1.0 to Go 1.1 for x86_64. + +2012-09-14: wsfulton + Add new warning if the empty template instantiation is used as a base class, for example: + + template class Base {}; + %template() Base; + class Derived : public Base {}; + + gives the following warning instead of silently ignoring the base: + + cpp_inherit.i:52: Warning 401: Base class 'Base< int >' has no name as it is an empty template instantiated with '%template()'. Ignored. + cpp_inherit.i:51: Warning 401: The %template directive must be written before 'Base< int >' is used as a base class and be declared with a name. + + +2012-09-11: wsfulton + [Java] Fix #3535304 - Direct use of a weak global reference in directors + sometimes causing seg faults especially on Android. + +2012-09-06: wsfulton + [Java] Fix (char *STRING, size_t LENGTH) typemaps to accept NULL string. + +2012-08-26: drjoe + [R] make ExternalReference slot ref to contain reference + +2012-08-26: drjoe + [R] fix Examples/Makefile to use C in $(CC) rather than $(CXX) + +Version 2.0.8 (20 August 2012) +============================== + +2012-08-15: wsfulton + [Perl] Add size_type, value_type, const_reference to the STL containers. + +2012-08-15: wsfulton + [Python] Add discard and add methods to std::set wrappers so that pyabc.i can be used ensuring + MutableSet is a valid abstract base class for std::set. As reported by Alexey Sokolov. + Similarly for std::multiset. + +2012-08-15: wsfulton + [Python] Fix #3541744 - Missing PyInt_FromSize_t calls for Python 3. + +2012-08-13: wsfulton + [Java] Patch from David Baum to add the assumeoverride feature for Java directors to + improve performance when all overridden methods can be assumed to be overridden. + +2012-08-05: wsfulton + [Python] #3530021 Fix unused variable warning. + +2012-08-05: wsfulton + [C#] Fix #3536360 - Invalid code sometimes being generated for director methods + with many arguments. + +2012-08-05: wsfulton + [Perl] #3545877 - Don't undefine bool if defined by C99 stdbool.h - problem using + Perl 5.16 and later. + +2012-08-04: wsfulton + Remove incorrect warning (314) about target language keywords which were triggered + by using declarations and using directives. For example 'string' is a keyword in C#: + namespace std { class string; } + using std::string; + +2012-07-21: wsfulton + Fix display of pointers in various places on 64 bit systems - only 32 bits were being shown. + +2012-07-21: wsfulton + Fix gdb debugger functions 'swigprint' and 'locswigprint' to display to the gdb output window + rather than stdout. This fixes display problems in gdbtui and the ensures the output + appears where expected in other gdb based debuggers such as Eclipse CDT. + +2012-07-20: kwwette + [Octave] segfault-on-exit prevention hack now preserves exit status, and uses C99 _Exit(). + +2012-07-02: wsfulton + Fix Debian bug http://bugs.debian.org/672035, typemap copy failure - regression introduced + in swig-2.0.5: + %include + using std::pair; + %template(StrPair) pair; + +2012-07-02: wsfulton + Fix using declarations combined with using directives with forward class declarations so that + types are correctly found in scope for templates. Example: + + namespace Outer2 { + namespace Space2 { + template class Thing2; + } + } + using namespace Outer2; + using Space2::Thing2; + template class Thing2 {}; + // STILL BROKEN void useit2(Thing2 t) {} + void useit2a(Outer2::Space2::Thing2 t) {} + void useit2b(::Outer2::Space2::Thing2 t) {} + void useit2c(Space2::Thing2 t) {} + namespace Outer2 { + void useit2d(Space2::Thing2 t) {} + } + + %template(Thing2Int) Thing2; + + +2012-06-30: wsfulton + Fix template namespace problems for symbols declared with a forward class declarations, such as: + + namespace Space1 { + namespace Space2 { + template struct YYY; + } + template struct Space2::YYY { + T yyy(T h) { + return h; + } + }; + void testYYY1(Space1::Space2::YYY yy) {} + void testYYY2(Space2::YYY yy) {} + void testYYY3(::Space1::Space2::YYY yy) {} + } + + %template(YYYInt) Space1::Space2::YYY; + +2012-06-30: wsfulton + Fix namespace problems for symbols declared with a forward class declarations, such as: + + namespace Space1 { + namespace Space2 { + struct XXX; + struct YYY; + } + + struct Space2::YYY {}; + struct Space1::Space2::XXX {}; + + void testXXX2(Space2::XXX xx) {} + void testYYY2(Space2::YYY yy) {} + } + + where xx and yy were not recognised as the proxy classes XXX and YYY. + +2012-06-30: wsfulton + Fix using declarations combined with using directives with forward class declarations so that + types are correctly found in scope. + + namespace Outer2 { + namespace Space2 { + class Thing2; + } + } + using namespace Outer2; + using Space2::Thing2; + class Thing2 {}; + // None of the methods below correctly used the Thing2 proxy class + void useit2(Thing2 t) {} + void useit2a(Outer2::Space2::Thing2 t) {} + void useit2b(::Outer2::Space2::Thing2 t) {} + void useit2c(Space2::Thing2 t) {} + namespace Outer2 { + void useit2d(Space2::Thing2 t) {} + } + +2012-06-25: wsfulton + Fix using declarations combined with using directives so that types are correctly found in scope. + Example: + + namespace Outer2 { + namespace Space2 { + class Thing2 {}; + } + } + using namespace Outer2; // using directive + using Space2::Thing2; // using declaration + void useit2(Thing2 t) {} + + Similarly for templated classes. + +2012-05-29: wsfulton + Fix #3529601 - seg fault when a protected method has the "director" + feature but the parent class does not. Also fix similar problems with + the allprotected feature. + +2012-05-28: wsfulton + Fix seg fault when attempting to warn about an illegal destructor - #3530055, 3530078 and #3530118. + +Version 2.0.7 (26 May 2012) +=========================== +2012-05-26: wsfulton + std::string typemap modifications so they can be used with %apply for other string + classes. + +2012-05-25: wsfulton + [Lua] Fixes for -external-runtime to work again. + +2012-05-22: szager + [python] Disambiguate SWIG_From_unsigned_SS_int and SWIG_From_unsigned_SS_long. + +2012-05-18: olly + [PHP] Fix getters for template members. (SF#3428833, SF#3528035) + +2012-05-14: wsfulton + Fix some language's std::map wrappers to recognise difference_type, size_type, key_type + and mapped_type. + +2012-05-14: kwwette (signed off by xavier98) + [Octave] Prevent Octave from seg-faulting at exit when SWIG + modules are loaded, due to bugs in Octave's cleanup code: + * Wrapping functions now declared with Octave DEFUN_DLD macro, + and loaded through Octave's dynamic module loader + * Global variables of swigref type are now assigned a new() + copy of the swigref class, to prevent double-free errors + * SWIG module at-exit cleanup function now created in Octave + through eval(), so not dependent on loaded .oct library + * For Octave versions 3.1.* to 3.3.*, register C-level at-exit + function which terminates Octave immediately (with correct + status code) without performing memory cleanup. This function + can be controlled with macros in Lib/octave/octruntime.swg + + [Octave] New syntax for determing whether SWIG module should be + loaded globally or non-globally. To load module "example" globally, + type the module name + $ example; + as before; to load module non-globally, assign it to a variable: + $ example = example; + or + $ ex = example; + for a shorter (local) module name. -global/-noglobal command-line + options and module command line are deprecated. Added usage info + to module, so typing + $ help example + or incorrect usage should display proper usage, with examples. + + *** POTENTIAL INCOMPATIBILITY *** + +2012-05-12: olly + [PHP] Fix memory leak in code generated for a callback. Patch from + SF bug #3510806. + +2012-05-12: olly + [PHP] Avoid using zend_error_noreturn() as it doesn't work with all + builds of PHP (SF bug #3166423). Instead we now wrap it in a + SWIG_FAIL() function which we annotate as "noreturn" for GCC to + avoids warnings. This also reduces the size of the compiled + wrapper (e.g. the stripped size is reduced by 6% for Xapian's PHP + bindings). + +2012-05-11: wsfulton + [Java] SF patch #3522855 Fix unintended uninitialised memory access in OUTPUT typemaps. + +2012-05-11: wsfulton + [Java] SF patch #3522674 Fix possible uninitialised memory access in char **STRING_OUT + typemap. + +2012-05-11: wsfulton + [Java] SF patch #3522611 Fix uninitialised size regression in char **STRING_ARRAY + introduced in swig-2.0.6. + +2012-05-11: wsfulton + SF bug #3525050 - Fix regression introduced in swig-2.0.5 whereby defining one typemap + method such as an 'out' typemap may hide another typemap method such as an 'in' typemap - + only occurs when the type is a template type where the template parameters are the same + via a typedef. + +2012-05-10: olly + [PHP] Fix the constant typemaps for SWIGTYPE, etc - previously + these used the wrong name for renamed constants. Add + autodoc_runme.php to the testsuite as a regression test for this. + +2012-05-02: ianlancetaylor + [Go] Remove compatibility support for gccgo 4.6. Using + SWIG with gccgo will now require gccgo 4.7. Using SWIG + with the more commonly used gc compiler is unaffected. + +2012-05-01: wsfulton + Fix generated code for C forward enum declarations in some languages. + +Version 2.0.6 (30 April 2012) +============================= + +2012-04-25: wsfulton + [Lua] Fix uninitialised variable in SWIGTYPE **OUTPUT typemaps as reported by Jim Anderson. + +2012-04-28: wsfulton + [Python] Fix compilation errors when wrapping STL containers on Mac OSX and possibly other systems. + +2012-04-28: wsfulton + [Java] Patch 3521811 from Leo Davis - char **STRING_ARRAY typemaps fixed to handle + null pointers. + +Version 2.0.5 (19 April 2012) +============================= + +2012-04-14: wsfulton + [Lua] Apply patch #3517435 from Miles Bader - prefer to use Lua_pushglobaltable + +2012-04-14: wsfulton + [Ruby] Apply patch #3517769 from Robin Stocker to fix compile error on MacRuby using RSTRING_PTR. + +2012-04-13: wsfulton + Apply patch #3511009 from Leif Middelschulte for slightly optimised char * variable wrappers. + +2012-04-13: wsfulton + [Lua] Apply #3219676 from Shane Liesegang which adds: + - support for %factory + - a __tostring method + - a __disown method + +2012-04-13: wsfulton + [Xml] Apply #3513569 which adds a catchlist to the xml output. + +2012-04-05: olly + [Lua] Add support for Lua 5.2 (patch SF#3514593 from Miles Bader) + +2012-03-26: xavier98 + [octave] Apply patch #3425993 from jgillis: add extra logic to the octave_swig_type::dims(void) method: it checks if the user has defined a __dims__ method and uses this in stead of returning (1,1) + [octave] Apply patch #3424833 from jgillis: make is_object return true for swig types + +2012-03-24: wsfulton + [D] Apply #3502431 to fix duplicate symbols in multiple modules. + +2012-03-21: wsfulton + Fix #3494791 - %$isglobal for %rename matching. + +2012-03-20: wsfulton + Fix #3487706 and #3391906 - missing stddef.h include for ptrdiff_t when using %import + for STL containers and compiling with g++-4.6. An include of stddef.h is now only + generated when SWIG generates STL helper templates which require ptrdiff_t. If you + were previously relying on "#include " always being generated when using a + %include of an STL header, you may now need to add this in manually. + +2012-03-16: wsfulton + Apply patch #3392264 from Sebastien Bine to parse (unsigned) long long types in enum value assignment. + +2012-03-16: wsfulton + Apply patch #3505530 from Karl Wette to allow custom allocators in STL string classes for the UTL languages. + +2012-03-13: wsfulton + Apply patch #3468362 from Karl Wette to fix %include inside %define. + +2012-03-13: wsfulton + [Python, Ruby, Octave, R] Fix #3475492 - iterating through std::vector wrappers of enumerations. + +2012-02-27: xavier98 (patches from Karl Wette) + [Octave] Use -globals . to load global variables in module namespace + [Octave] Comment declaration of unimplemented function swig_register_director + [Octave] Fix OCTAVE_PATH in octave Makefiles + [Octave] Add support for std::list - fix li_std_containers_int test + [Octave] Fix imports test + +2012-02-16: wsfulton + [Java] Make generated support functions in arrays_java.i static so that generated code + from multiple instances of SWIG can be compiled and linked together - problem reported by + Evan Krause. + +2012-01-24: wsfulton + Fix crash with bad regex - bug #3474250. + +2012-01-24: wsfulton + [Python] Add Python stepped slicing support to the STL wrappers (std::vector, std::list). + Assigning to a slice, reading a slice and deleting a slice with steps now work. + For example: + + %template(vector_i) std::vector + + vi = vector_i(range(10)) + print list(vi) + vi[1:4:2] = [111, 333] + print list(vi) + del vi[3:10:3] + print list(vi) + print list(vi[::-1]) + + gives (same behaviour as native Python sequences such as list): + + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + [0, 111, 2, 333, 4, 5, 6, 7, 8, 9] + [0, 111, 2, 4, 5, 7, 8] + [8, 7, 5, 4, 2, 111, 0] + +2012-01-23: klickverbot + [D] Correctly annotate function pointers with C linkage. + [D] Exception and Error have become blessed names; removed d_exception_name test case. + +2012-01-20: wsfulton + [Python] Fix some indexing bugs in Python STL wrappers when the index is negative, eg: + + %template(vector_i) std::vector + + iv=vector_i([0,1,2,3,4,5]) + iv[-7:] + + now returns [0, 1, 2, 3, 4, 5] instead of [5]. + + vv[7:9] = [22,33] + + now returns [0, 1, 2, 3, 4, 5, 22, 33] instead of "index out range" error. + + Also fix some segfaults when replacing ranges, eg when il is a std::list wrapper: + + il[0:2] = [11] + +2012-01-17: wsfulton + [Go] Fix forward class declaration within a class when used as a base. + +2012-01-07: wsfulton + [C#] Add support for %nspace when using directors. + +2012-01-06: wsfulton + [Java] Patch #3452560 from Brant Kyser - add support for %nspace when using directors. + +2011-12-21: wsfulton + The 'directorin' typemap now accepts $1, $2 etc expansions instead of having to use workarounds - + $1_name, $2_name etc. + +2011-12-20: wsfulton + [Java] Add (char *STRING, size_t LENGTH) director typemaps. + +2011-12-20: wsfulton + [C#, Go, Java, D] Add support for the 'directorargout' typemap. + +2011-12-20: wsfulton + [Ocaml, Octave, PHP, Python, Ruby] Correct special variables in 'directorargout' typemap. + This change will break any 'directorargout' typemaps you may have written. Please change: + $result to $1 + $input to $result + + Also fix the named 'directorargout' DIRECTOROUT typemaps for these languages which didn't + previously compile and add in $1, $2 etc expansion. + + *** POTENTIAL INCOMPATIBILITY *** + +2011-12-10: talby + [perl5] SWIG_error() now gets decorated with perl source file/line number. + [perl5] error handling now conforms to public XS api (fixes perl v5.14 issue). + +2011-12-10: wsfulton + [Android/Java] Fix directors to compile on Android. + + Added documentation and examples for Android. + +2011-12-08: vadz + Bug fix: Handle methods renamed or ignored in the base class correctly in the derived classes + (they could be sometimes mysteriously not renamed or ignored there before). + +2011-12-03: klickverbot + [D] Fix exception glue code for newer DMD 2 versions. + [D] Do not default to 32 bit glue code for DMD anymore. + [D] Use stdc.config.c_long/c_ulong to represent C long types. + +2011-12-01: szager + [python] Fixed bug 3447426: memory leak in vector.__getitem__. + +2011-11-30: wsfulton + [R] Remove C++ comments from generated C code. + +2011-11-27: olly + [Python] Fix some warnings when compiling generated wrappers with + certain GCC warning options (Debian bug #650246). + +2011-11-28: wsfulton + Fix #3433541 %typemap(in, numinputs=0) with 10+ arguments. + +2011-11-28: olly + [Perl] Fix warnings when compiling generated wrappers with certain + GCC warning options (Debian bug #436711). + +2011-11-28: olly + [PHP] Update keyword list to include keywords added in PHP releases up to 5.3. + +2011-11-25: wsfulton + [C#] Provide an easy way to override the default visibility for the proxy class pointer + constructors and getCPtr() method. The visibility is 'internal' by default and if multiple + SWIG modules are being used and compiled into different assemblies, then they need to be + 'public' in order to use the constructor or getCPtr() method from a different assembly. + Use the following macros to change the visibilities in the proxy and type wrapper class: + + SWIG_CSBODY_PROXY(public, public, SWIGTYPE) + SWIG_CSBODY_TYPEWRAPPER(public, public, public, SWIGTYPE) + + [Java] Provide an easy way to override the default visibility for the proxy class pointer + constructors and getCPtr() method. The visibility is 'protected' by default and if multiple + SWIG modules are being used and compiled into different packages, then they need to be + 'public' in order to use the constructor or getCPtr() method from a different package. + Use the following macros to change the visibilities in the proxy and type wrapper class: + + SWIG_JAVABODY_PROXY(public, public, SWIGTYPE) + SWIG_JAVABODY_TYPEWRAPPER(public, public, public, SWIGTYPE) + + The default for Java has changed from public to protected for the proxy classes. Use the + SWIG_JAVABODY_PROXY macro above to restore to the previous visibilities. + + *** POTENTIAL INCOMPATIBILITY *** + +2011-11-22: szager + [python] Bug 3440044: #ifdef out SWIG_Python_NonDynamicSetAttr if -builtin + isn't being used, to avoid unnecessary binary incompatibilities between + python installations. + +2011-11-17: wsfulton + Bug fix: Remove root directory from directory search list in Windows. + +2011-11-13: wsfulton + [Ruby] Apply patch #3421876 from Robin Stocker to fix #3416818 - same class name in + different namespaces confusion when using multiple modules. + +2011-11-11: wsfulton + Fix pcre-build.sh to work with non-compressed tarballs - problem reported by Adrian Blakely. + +2011-11-03: wsfulton + Expand special variables in typemap warnings, eg: + + %typemap(in, warning="1000:Test warning for 'in' typemap for $1_type $1_name") int "..." + +2011-11-01: wsfulton + Fix named output typemaps not being used when the symbol uses a qualifier and contains + a number, eg: + + %typemap(out) double ABC::m1 "..." + +2011-10-24: talby + [perl5] SF bug #3423119 - overload dispatch stack corruption fix. Better, but more research + is needed on a stable path for tail calls in XS. + + Also, fix for large long longs in 32 bit perl. + +2011-10-13: xavier98 + [octave] Allow Octave modules to be re-loaded after a "clear all". + +2011-09-19: wsfulton + Fix regression introduced in swig-2.0.1 reported by Teemu Ikonone leading to uncompilable code + when using typedef and function pointer references, for example: + + typedef int FN(const int &a, int b); + void *typedef_call1(FN *& precallback, FN * postcallback); + +2011-09-14: wsfulton + [Lua] Patch #3408012 from Raman Gopalan - add support for embedded Lua (eLua) + including options for targeting Lua Tiny RAM (LTR). + +2011-09-14: wsfulton + [C#] Add boost_intrusive_ptr.i library contribution from patch #3401571. + +2011-09-13: wsfulton + Add warnings for badly named destructors, eg: + + struct KStruct { + ~NOT_KStruct() {} + }; + + cpp_extend_destructors.i:92: Warning 521: Illegal destructor name ~NOT_KStruct. Ignored. + +2011-09-13: wsfulton + Fix %extend and destructors for templates. The destructor in %extend was not always wrapped, + for example: + + %extend FooT { + ~FooT() { delete $self; } // was not wrapped as expected + }; + template class FooT {}; + %template(FooTi) FooT; + +2011-09-13: wsfulton + Fix special variables such as "$decl" and "$fulldecl" in destructors to include the ~ character. + +2011-09-10: talby + [perl5] SF bug #1481958 - Improve range checking for integer types. + Enhance li_typemaps_runme.pl + +2011-09-08: wsfulton + Fix %extend on typedef classes in a namespace using the typedef name, for example: + namespace Space { + %extend CStruct { + ... + } + typedef struct tagCStruct { ... } CStruct; + } + +2011-08-31: xavier98 + [octave] patches from Karl Wette: improvements to module loading behavior; + added example of friend operator to operator example; fixed octave panic/crash in 3.0.5; + documentation improvements + +2011-08-30: szager + [python] Bug 3400486, fix error signalling for built-in constructors. + +2011-08-26: wsfulton + [Go] Fix file/line number display for "gotype" when using typemap debugging options + -tmsearch and -tmused. + +2011-08-26: wsfulton + [C#, D] Fix %callback which was generating uncompileable code. + +2011-08-25: wsfulton + Fix constructors in named typedef class declarations as reported by Gregory Bronner: + + typedef struct A { + A(){} // Constructor which was not accepted by SWIG + B(){} // NOT a constructor --illegal, but was accepted by SWIG + } B; + + For C code, the fix now results in the use of 'struct A *' instead of just 'B *' in + the generated code when wrapping members in A, but ultimately this does not matter, as + they are the same thing. + +2011-08-23: wsfulton + Fix %newobject when used in conjunction with %feature("ref") as reported by Jan Becker. The + code from the "ref" feature was not always being generated for the function specified by %newobject. + Documentation for "ref" and "unref" moved from Python to the C++ chapter. + +2011-08-22: szager + [python] Fixed memory leak with --builtin option (bug 3385089). + +2011-08-22: wsfulton + [Lua] SF patch #3394339 from Torsten Landschoff - new option -nomoduleglobal to disable installing + the module table into the global namespace. Require call also returns the module table instead + of a string. + +2011-08-09: xavier98 + Fix bug 3387394; Octave patches for 3.4.0 compatibility, etc. (from Karl Wette) + +2011-08-04: wsfulton + Add in $symname expansion for director methods. + +2011-07-29: olly + [PHP] Don't generate "return $r;" in cases where $r hasn't been set. + This was basically harmless, except it generated a PHP E_NOTICE if + the calling code had enabled them. + +2011-07-26: wsfulton + Fix scoping of forward class declarations nested within a class (for C++). Previously the symbol + was incorrectly put into the outer namespace, eg + + namespace std { + template struct map { + class iterator; + }; + } + + iterator was scoped as std::iterator, but now it is correctly std::map::iterator; + + Also fixed is %template and template parameters that are a typedef when the template contains + default template parameters, eg: + + namespace Std { + template struct Map { + typedef Key key_type; + typedef T mapped_type; + }; + } + typedef double DOUBLE; + %template(MM) Std::Map; + + All symbols within Map will be resolved correctly, eg key_type and mapped_type no matter if the + wrapped code uses Std::Map or std::Map or Std::Map + + Also fixes bug #3378145 - regression introduced in 2.0.4 - %template using traits. + +2011-07-20 szager + [python] Fix closure for tp_call slot. + +2011-07-16: wsfulton + [python] Fix director typemap using PyObject *. + +2011-07-13: szager + [python] SF patch #3365908 - Add all template parameters to map support code in std_map.i + +2011-07-13: szager + [python] Fix for bug 3324753: %rename member variables with -builtin. + +2011-07-01: wsfulton + Fix some scope and symbol lookup problems when template default parameters are being + used with typedef. For example: + + template struct Foo { + typedef XX X; + typedef TT T; + }; + template struct UsesFoo { + void x(typename Foo::T, typename Foo::X); + }; + + Also fixes use of std::vector::size_type for Python as reported by Aubrey Barnard. + +2011-06-23: olly + [PHP] Fix director code to work when PHP is built with ZTS enabled, + which is the standard configuration on Microsoft Windows. + +2011-06-21: mutandiz + [allegrocl] + - various small tweaks and bug fixes. + - Avoid name conflicts between smart pointer wrappers and the wrappers for + the actual class. + - Fix default typemaps for C bindings, which were incorrectly attempting to + call non-existent destructors on user-defined types. + - New feature, feature:aclmixins, for adding superclass to the foreign class + wrappers. + - Improve longlong typemaps. + +2011-06-19: wsfulton + Fix incorrect typemaps being used for a symbol within a templated type, eg: + A::value_type would incorrectly use a typemap for type A. + +2011-06-18: olly + [Tcl] Fix variable declarations in middle of blocks which isn't + permitted in C90 (issue probably introduced in 2.0.3 by patch #3224663). + Reported by Paul Obermeier in SF#3288586. + +2011-06-17: wsfulton + [Java] SF #3312505 - slightly easier to wrap char[] or char[ANY] with a Java byte[] + using arrays_java.i. + +2011-06-13: wsfulton + [Ruby, Octave] SF #3310528 Autodoc fixes similar to those described below for Python. + +2011-06-10: wsfulton + [Python] Few subtle bugfixes in autodoc documentation generation, + - Unnamed argument names fix for autodoc levels > 0. + - Display of template types fixed for autodoc levels > 1. + - Fix SF #3310528 - display of typedef structs for autodoc levels > 1. + - Add missing type for self for autodoc levels 1 and 3. + - autodoc levels 2 and 3 documented. + - Minor tweaks to autodoc style to conform with PEP8. + +2011-05-30: olly + [PHP] Fix handling of directors when -prefix is used. + +2011-05-24: olly + [PHP] Fix handling of methods of classes with a virtual base class (SF#3124665). + +Version 2.0.4 (21 May 2011) +=========================== + +2011-05-19: wsfulton + [Guile] Patch #3191625 fixing overloading of integer types. + +2011-05-19: wsfulton + [Perl] Patch #3260265 fixing overloading of non-primitive types and integers in + Perl 5.12 and later. + +2011-05-19: wsfulton + [Ruby] Fix %import where one of the imported files %include one of the STL include + files such as std_vector.i. + +2011-05-17: wsfulton + [Java] Apply #3289851 from Alan Harder to fix memory leak in directors when checking + for pending exceptions. + +2011-05-17: wsfulton + [Tcl] Apply #3300072 from Christian Delbaere to fix multiple module loading not + always sharing variables across modules. + +2011-05-16: xavier98 + [octave] Fix an incompatibility with never versions of Octave. Case on Octave + API >= 40 to handle rename of Octave_map to octave_map. + [octave] Add support for y.__rop__(x) operators when x.__op__(y) doesn't exist. + [octave] Allow global operators to be defined by SWIG-wrapped functions. + [octave] Fix several bugs around module namespaces; add -global, -noglobal, + -globals command line options to the module. + +2011-05-14: wsfulton + %varargs when used with a numeric argument used to create an additional argument + which was intended to provide a guaranteed sentinel value. This never worked and now + the additional argument is not generated. + +2011-05-13: wsfulton + [python] Additional fixes for python3.2 support. + +2011-05-07: szager + [python] Fixed PyGetSetDescr for python3.2. + +2011-05-05: wsfulton + [Lua, Python, Tcl] C/C++ prototypes shown in error message when calling an overloaded + method with incorrect arguments improved to show always show fully qualified name + and if a const method. + + Also fixed other Lua error messages in generated code which weren't consistently + using the fully qualified C++ name - requested by Gedalia Pasternak. + +2011-04-29: szager + Bug 2635919: Convenience method to convert std::map to a python dict. + +2011-04-29: szager + [Python] Fixed bug 2811549: return non-const iterators from STL + methods begin(), end(), rbegin(), rend(). + +2011-04-25: szager + [Python] Fixed bug 1498929: Access to member fields in map elements + +2011-04-23: klickverbot + [D] nspace: Correctly generate identifiers for base classes when + not in split proxy mode. + +2011-04-13: szager + Fixed bug 3286333: infinite recursion with mutual 'using namespace' clauses. + +2011-04-12: szager + Fixed bug 1163440: vararg typemaps. + +2011-04-12: szager + Fixed bug #3285386: parse error from 'operator T*&()'. Added operator_pointer_ref + test case to demonstrate. + +2011-04-11: szager + [Python] Fixed PyVarObject_HEAD_INIT to eliminate VC++ compiler errors about + static initialization of struct members with pointers. + +2011-04-11: wsfulton + [Tcl] Apply patch #3284326 from Colin McDonald to fix some compiler warnings. + +2011-04-11: szager + [Python] Fixed PyVarObject_HEAD_INIT to eliminate VC++ compiler errors about + static initialization of struct members with pointers. + +2011-04-10: klickverbot + [D] Fixed wrapping of enums that are type char, for example: + enum { X = 'X'; } (this was already in 2.0.3 for C# and Java) + +2011-04-10: klickverbot + [D] nspace: Fixed referencing types in the root namespace when + not in split proxy mode. + +2011-04-09: szager + [Python] Applied patch #1932484: migrate PyCObject to PyCapsule. + +2011-04-09: szager + [Python] Added preprocessor guards for python functions PyUnicode_AsWideChar and + PySlice_GetIndices, which changed signatures in python3.2. + +2011-04-07: wsfulton + Fix wrapping of const array typedefs which were generating uncompileable code as + reported by Karl Wette. + +2011-04-03: szager + [Python] Fixed the behavior of %pythonnondynamic to conform to the spec in Lib/pyuserdir.swg. + +2011-04-03: szager + [Python] Merged in the szager-python-builtin branch, adding the -builtin feature + for python. The -builtin option may provide a significant performance gain + in python wrappers. For full details and limitations, refer to Doc/Manual/Python.html. + A small test suite designed to demonstrate the performance gain is in + Examples/python/performance. + +2011-04-01: wsfulton + Add in missing wrappers for friend functions for some target languages, mostly + the non-scripting languages like Java and C#. + +Version 2.0.3 (29 March 2011) +============================= + +2011-03-29: wsfulton + [R] Apply patch #3239076 from Marie White fixing strings for R >= 2.7.0 + +2011-03-29: wsfulton + [Tcl] Apply patch #3248280 from Christian Delbaere which adds better error messages when + the incorrect number or type of arguments are passed to overloaded methods. + +2011-03-29: wsfulton + [Tcl] Apply patch #3224663 from Christian Delbaere. + 1. Fix when function returns a NULL value, a "NULL" command will be created in the Tcl interpreter + and calling this command will cause a segmentation fault. + + 2. Previous implementation searches for class methods using a linear search causing performance issues + in wrappers for classes with many member functions. The patch adds a method hash table to classes and + changes method name lookup to use the hash table instead of doing a linear search. + +2011-03-26: wsfulton + [C#, Java] SF bug #3195112 - fix wrapping of enums that are type char, for example: + enum { X = 'X'; } + +2011-03-21: vadz + Allow setting PCRE_CFLAGS and PCRE_LIBS during configuration to override the values returned by + pcre-config, e.g. to allow using a static version of PCRE library. + +2011-03-17: wsfulton + [UTL] Add missing headers in generated STL wrappers to fix compilation with gcc-4.6. + +2011-03-17: wsfulton + Fix regression introduced in swig-2.0.2 where filenames with spaces were not found + when used with %include and %import. Reported by Shane Liesegang. + +2011-03-15: wsfulton + [UTL] Fix overloading when using const char[], problem reported by David Maxwell. + Similarly for char[ANY] and const char[ANY]. + +2011-03-15: wsfulton + [C#] Apply patch #3212624 fixing std::map Keys property. + +2011-03-14: olly + [PHP] Fix handling of overloaded methods/functions where some + return void and others don't - whether this worked or not depended + on the order they were encountered in (SF#3208299). + +2011-03-13: klickverbot + [D] Extended support for C++ namespaces (nspace feature). + +2011-03-12: olly + [PHP] Fix sharing of type information between multiple SWIG-wrapped + modules (SF#3202463). + +2011-03-09: wsfulton + [Python] Fix SF #3194294 - corner case bug when 'NULL' is used as the default value + for a primitive type parameter in a method declaration. + +2011-03-07: olly + [PHP] Don't use zend_error_noreturn() for cases where the function + returns void - now this issue can only matter if you have a function + or method which is directed and returns non-void. + +2011-03-06: olly + [PHP] Add casts to the typemaps for long long and unsigned long + long to avoid issues when they are used with shorter types via + %apply. + +2011-03-02: wsfulton + Templated smart pointers overloaded with both const and non const operator-> generated uncompilable + code when the pointee was a class with either public member variables or static methods. + Regression in 2.0.x reported as working in 1.3.40 by xantares on swig-user mailing list. + +Version 2.0.2 (20 February 2011) +================================ + +2011-02-19: wsfulton + [PHP] Add missing INPUT, OUTPUT and INOUT typemaps in the typemaps.i library + for primitive reference types as well as signed char * and bool *. + +2011-02-19: olly + [PHP] Address bug in PHP on some platforms/architectures which + results in zend_error_noreturn() not being available using + SWIG_ZEND_ERROR_NORETURN which defaults to zend_error_noreturn but + can be overridden when building the module by passing + -DSWIG_ZEND_ERROR_NORETURN=zend_error to the compiler. This may + result in compiler warnings, but should at least allow a module + to be built on those platforms/architectures (SF#3166423). + +2011-02-18: wsfulton + Fix #3184549 - vararg functions and function overloading when using the -fastdispatch option. + +2011-02-18: olly + [PHP] An overloaded method which can return an object or a + primitive type no longer causes SWIG to segfault. Reported by Paul + Colby in SF#3168531. + +2011-02-18: olly + [PHP] Fix invalid erase during iteration of std::map in generated + director code. Reported by Cory Bennett in SF#3175820. + +2011-02-17: wsfulton + Preprocessing now warns if extra tokens appear after #else and #end. + +2011-02-16: wsfulton + Fix #1653092 Preprocessor does not error out when #elif is missing an expression. + This and other cases of missing preprocessor expressions now result in an error. + +2011-02-14: wsfulton + [Ocaml] Apply patch #3151788 from Joel Reymont. Brings Ocaml support up to date + (ver 3.11 and 3.12), including std::string. + +2011-02-13: wsfulton + [Ruby] Apply patch #3176274 from James Masters - typecheck typemap for time_t. + +2011-02-13: wsfulton + Apply patch #3171793 from szager - protected director methods failing when -fvirtual is used. + +2011-02-13: wsfulton + Fix #1927852 - #include directives don't preprocess the file passed to it. The fix is for + #include with -importall or -includeall, %include and %import, for example: + #define FILENAME "abc.h" + %include FILENAME + +2011-02-12: wsfulton + Fix #1940536, overactive preprocessor which was expanding defined(...) outside of #if and #elif + preprocessor directives. + +2011-02-05: wsfulton + [MzScheme] SF #2942899 Add user supplied documentation to help getting started with MzScheme. + Update chapter name to MzScheme/Racket accounting for the rename of MzScheme to Racket. + +2011-02-05: wsfulton + [C#] SF #3085906 - Possible fix running test-suite on Mac OSX. + +2011-02-05: wsfulton + SF #3173367 Better information during configure about Boost prerequisite for running + the test-suite. + +2011-02-05: wsfulton + SF #3127633 Fix infinite loop in recursive typedef resolution. + +2011-02-04: wsfulton + [R] SF #3168676 Fix %rename not working for member variables and methods. + +2011-02-04: wsfulton + [clisp] SF #3148200 Fix segfault parsing nested unions. + +2011-02-01: wsfulton + [C#] Directors - a call to a method being defined in the base class, not + overridden in a subclass, but again overridden in a class derived from + the first subclass was not being dispatched correctly to the most derived class. + See director_alternating.i for an example. + +2011-02-01: wsfulton + [C#, Java] Any 'using' statements in the protected section of a class were previously + ignored with director protected (dirprot) mode. + +2011-01-30: wsfulton + Fix overloading with const pointer reference (SWIGTYPE *const&) parameters for a + number of scripting languages. + +2011-01-17: wsfulton + New warning for smart pointers if only some of the classes in the inheritance + chain are marked as smart pointer, eg, %shared_ptr should be used for all classes + in an inheritance hierarchy, so this new warning highlights code where this is + not the case. + + example.i:12: Warning 520: Base class 'A' of 'B' is not similarly marked as a smart pointer. + example.i:16: Warning 520: Derived class 'C' of 'B' is not similarly marked as a smart pointer. + +2011-01-14: wsfulton + Added some missing multi-argument typemaps: (char *STRING, size_t LENGTH) and + (char *STRING, int LENGTH). Documentation for this updated. Java patch from + Volker Grabsch. + +2011-01-11: iant + Require Go version 7077 or later. + +2010-12-30: klickverbot + [C#, D, Java] Check for collision of parameter names with target + language keywords when generating the director glue code. + + The situation in which the generated could would previously be + invalid is illustrated in the new 'director_keywords' test case. + +2010-12-23: wsfulton + [C#] Fix $csinput special variable not being expanded for csvarin typemaps + when used for global variables. Reported by Vadim Zeitlin. + +2010-12-14: wsfulton + Fix $basemangle expansion in array typemaps. For example if type is int *[3], + $basemangle expands to _p_int. + +2010-12-07: iant + Check that we are using a sufficiently new version of the + 6g or 8g Go compiler during configure time. If not, disable Go. + Minimum version is now 6707. + + *** POTENTIAL INCOMPATIBILITY *** + +2010-12-06: wsfulton + Fix #3127394 - use of network paths on Windows/MSys. + +2010-11-18: klickverbot + [D] Added the D language module. + +2010-11-12: vadz + Fix handling of multiple regex-using %renames attached to the same + declaration. For example, now + + %rename("%(regex/^Set(.*)/put\\1/)s") ""; + %rename("%(regex/^Get(.*)/get\\1/)s") ""; + + works as expected whereas before only the last anonymous rename was + taken into account. + +2010-10-17: drjoe + [R] Fix failure in overloaded functions which was breaking + QuantLib-SWIG + +2010-10-14: olly + [PHP] Allow compilation on non-conforming Microsoft C++ compilers + which don't accept: return function_returning_void(); + Reported by Frank Vanden Berghen on the SWIG mailing list. + +2010-10-12: wsfulton + Fix unary scope operator (::) (global scope) regression introduced in 2.0.0, reported by + Ben Walker. The mangled symbol names were incorrect, sometimes resulting in types being + incorrectly treated as opaque types. + + Also fixes #2958781 and some other type problems due to better typedef resolution, eg + std::vector::value_type didn't resolve to T * when it should have. The mangled type + was incorrectly SWIGTYPE_std__vectorT_Test_p_std__allocatorT_Test_p_t_t__value_type and now + it is correctly SWIGTYPE_p_Test. + +Version 2.0.1 (4 October 2010) +============================== + +2010-10-03: wsfulton + Apply patch #3066958 from Mikael Johansson to fix default smart pointer + handling when the smart pointer contains both a const and non-const operator->. + +2010-10-01: wsfulton + Add -pcreversion option to display PCRE version information. + +2010-10-01: olly + [Ruby] Avoid segfault when a method node has no parentNode + (SF#3034054). + +2010-10-01: olly + [Python] Allow reinitialisation to work with an embedded Python + interpreter (patch from Jim Carroll in SF#3075178). + +2010-09-28: wsfulton + [C#] Apply patch from Tomas Dirvanauskas for std::map wrappers to avoid + throwing exceptions with normal usage of iterators. + +2010-09-27: olly + [Python] Improve error message given when a parameter of the wrong + type is passed to an overloaded method (SF#3027355). + +2010-09-25: wsfulton + Apply SF patch #3075150 - Java directors using static variables in + named namespace. + +2010-09-24: wsfulton + More file and line error/warning reporting fixes where SWIG macros + are used within {} braces (where the preprocessor expands macros), + for example macros within %inline {...} and %fragment(...) {...} + and nested structs. + +2010-09-18: wsfulton + More file and line error/warning reporting fixes for various inherited + class problems. + +2010-09-15: wsfulton + A much improved debugging of SWIG source experience is now available and + documented in the "Debugging SWIG" section in the Doc/Devel/internals.html + file, including a swig.dbg support file for the gdb debugger. + +2010-09-11: wsfulton + Fix incorrect line number reporting in errors/warnings when a macro + definition ends with '/' and it is not the end of a C comment. + +2010-09-11: wsfulton + Fix incorrect line number reporting in errors/warnings after parsing + macro invocations with parameters given over more than one line. + +2010-09-10: wsfulton + Remove extraneous extra line in preprocessed output after including files + which would sometimes lead to error/warning messages two lines after the + end of the file. + +2010-09-10: wsfulton + Fix #2149523 - Incorrect line number reporting in errors after parsing macros + containing C++ comments. + +2010-09-08: olly + [PHP] Fix handling of OUTPUT typemaps (Patch from Ryan in SF#3058394). + +2010-09-03: wsfulton + Fix erroneous line numbers in error messages for macro expansions, for example, + the error message now points to instantiation of the macro, ie the last line here: + + #define MACRO2(a, b) + + #define MACRO1(NAME) MACRO2(NAME,2,3) + + MACRO1(abc) + +2010-09-02: wsfulton + Fix line numbers in error and warning messages for preprocessor messages within + %inline, for example: + + %inline %{ + #define FOOBAR 1 + #define FOOBAR "hi" + %} + +2010-09-02: wsfulton + Fix line numbers in error and warning messages which were cumulatively one + less than they should have been after parsing each %include/%import - bug + introduced in swig-1.3.32. Also fix line numbers in error and warning messages + when new line characters appear between the %include / %import statement and + the filename. + +2010-08-30: wsfulton + Fix line number and file name reporting for some macro preprocessor warnings. + The line number of the macro argument has been corrected and the line number + of the start of the macro instead of one past the end of the macro is used. + Some examples: + file.h:11: Error: Illegal macro argument name '..' + file.h:19: Error: Macro 'DUPLICATE' redefined, + file.h:15: Error: previous definition of 'DUPLICATE'. + file.h:25: Error: Variable-length macro argument must be last parameter + file.h:32: Error: Illegal character in macro argument name + file.i:37: Error: Macro 'SIT' expects 2 arguments + +2010-08-26: wsfulton + Fix __LINE__ and __FILE__ expansion reported by Camille Gillot. Mostly this + did not work at all. Also fixes SF #2822822. + +2010-08-17: wsfulton + [Perl] Fix corner case marshalling of doubles - errno was not being correctly + set before calling strtod - patch from Justin Vallon - SF Bug #3038936. + +2010-08-17: wsfulton + Fix make distclean when some of the more obscure languages are detected by + configure - fixes from Torsten Landschoff. + +2010-07-28: wsfulton + Restore configuring out of source for the test-suite since it broke in 1.3.37. + As previously, if running 'make check-test-suite' out of source, it needs to be + done by invoking configure with a relative path. Invoking configure with an + absolute path will not work. Running the full 'make check' still needs to be + done in the source tree. + +2010-07-16: wsfulton + Fix wrapping of function pointers and member function pointers when the function + returns by reference. + +2010-07-13: vadz + Removed support for the old experimental "rxspencer" encoder and + "[not]rxsmatch" in %rename (see the 01/16/2006 entry). The new and + officially supported "regex" encoder and "[not]regexmatch" checks + should be used instead (see the two previous entries). Please + replace "%(rxspencer:[pat][subst])s" with "%(regex:/pat/subst/)s" + when upgrading. Notice that you will also need to replace the back- + references of form "@1" with the more standard "\\1" and may need to + adjust your regular expressions syntax as the new regex encoder uses + Perl-compatible syntax and not (extended) POSIX syntax as the old one. + + *** POTENTIAL INCOMPATIBILITY *** + +2010-07-13: vadz + Add "regexmatch", "regextarget" and "notregexmatch" which can be + used to apply %rename directives to the declarations matching the + specified regular expression only. The first two can be used + interchangeably, both of the %renames below do the same thing: + + %rename("$ignore", regexmatch$name="Old$") ""; + %rename("$ignore", regextarget=1) "Old$"; + + (namely ignore the declarations having "Old" suffix). + + "notregexmatch" restricts the match to only the declarations which + do not match the regular expression, e.g. here is how to rename to + lower case versions all declarations except those consisting from + capital letters only: + + %rename("$(lowercase)s", notregexmatch$name="^[A-Z]+$") ""; + +2010-07-13: vadz + Add the new "regex" encoder that can be used in %rename, e.g. + + %rename("regex:/(\\w+)_(.*)/\\2/") ""; + + to remove any alphabetical prefix from all identifiers. The syntax + of the regular expressions is Perl-like and PCRE library + (http://www.pcre.org/) is used to implement this feature but notice + that backslashes need to be escaped as usual inside C strings. + + Original patch from Torsten Landschoff. + +2010-07-08: wsfulton + Fix #3024875 - shared_ptr of classes with non-public destructors. This also fixes + the "unref" feature when used on classes with non-public destructors. + +2010-06-17: ianlancetaylor + [Go] Add the Go language module. + +2010-06-10: wsfulton + [Lua] Fix SWIG_lua_isnilstring multiply defined when using multiple + modules and wrapping strings. Patch from 'Number Cruncher'. + +2010-06-10: olly + [PHP] Fix directors to correctly call a method with has a + different name in PHP to C++ (we were always using the C++ name + in this case). + +2010-06-03: wsfulton + Fix uncompileable code when %rename results in two enum items + with the same name. Reported by Vadim Zeitlin. + Version 2.0.0 (2 June 2010) =========================== @@ -2218,7 +3615,7 @@ Version 1.3.32 (November 15, 2007) [C#] Added missing support for C++ class member pointers. 08/09/2007: wsfulton - [C#, Java] Add support for $owner in the "out" typemaps like in the the scripting + [C#, Java] Add support for $owner in the "out" typemaps like in the scripting language modules. Note that $owner has always been supported in the "javaout" / "csout" typemaps. @@ -2918,7 +4315,7 @@ Version 1.3.30 (November 13, 2006) 10/12/2006: wsfulton [Java] Remove potential race condition on the proxy class' delete() method (it is now a synchronized method, but is now customisable by changing the - methodmodifiers attribute in the the javadestruct or javadestruct_derived typemap) + methodmodifiers attribute in the javadestruct or javadestruct_derived typemap) [C#] Remove potential race condition on the proxy class' Dispose() method, similar to Java's delete() above. @@ -3726,7 +5123,7 @@ Version 1.3.28 (February 12, 2006) %naturalvar std::string; %include - that will tell swig to use the the 'natural' wrapping + that will tell swig to use the 'natural' wrapping mechanism to all std::string global and member variables. @@ -7233,7 +8630,7 @@ Version 1.3.23 (November 11, 2004) b = B() b.bar(1) - note the the methods are emitted inside the classes, + note the methods are emitted inside the classes, and hence, the %template name refers to the 'member' method name, not a global namespace name. @@ -10747,7 +12144,7 @@ Version 1.3.20 (December 17, 2003) 06/25/2003: mrose (Mark Rose) [Python] Director typemap marshalling checks for null pointers when walking the parameter list instead of relying soley on the parameter - count. Cures a segfault that occured for multiple argument inv typemaps. + count. Cures a segfault that occurred for multiple argument inv typemaps. Someone with more Swig experience should probably review this code. 06/24/2003: mkoeppe (Matthias Koeppe) @@ -15181,7 +16578,7 @@ Version 1.3.12 (June 2, 2002) %feature, %rename, %ignore, %exception, and related directives: - Namespaces are fully integrated into the the renaming and declaration + Namespaces are fully integrated into the renaming and declaration matcher. For example: %rename(display) Foo::print; // Rename in namespace Foo @@ -16222,7 +17619,7 @@ Version 1.3.10 (December 10, 2001) shadow classes. In early implementations, shadow classes were merely Python wrappers around typed pointer objects. However, some users actually wanted to receive the shadow class object in C. - To accomodate this, the dereferencing of the "this" pointer in + To accommodate this, the dereferencing of the "this" pointer in a shadow class was moved to C as described in CHANGES [8/8/99]. However, the process of returning pointers to Python was still somewhat problematic. Specifically, shadow classes never worked @@ -18136,7 +19533,7 @@ Version 1.3.6 (July 9, 2001) [Java] destructor (_delete()) was not aware of %name renaming [Java] extends baseclass did not know about %name renaming [Java] extends baseclass did extend even when the baseclass was not known to swig - [Java] sometimes enum-declarations occured before the Java class declaration + [Java] sometimes enum-declarations occurred before the Java class declaration [Java] unrelated enum initialisations no longer appear in Java class [Java] if module ends in '_' correct JNI names are now produced @@ -19289,7 +20686,7 @@ Version 1.3 Alpha 1 (February 11, 2000) names or use %apply to map typemaps to alternate names. 8/8/99 : Handling of the 'this' pointer has been changed in Python shadow - classes. Previously, dereferencing of '.this' occured in the + classes. Previously, dereferencing of '.this' occurred in the Python shadow class itself. Now, this step occurs in the C wrappers using the following function: @@ -19846,7 +21243,7 @@ Version 1.1 Patch 1 (August 27, 1997) Would generate completely bogus code with garbage replacing the '%d'. Caused by one faulty use of printf (wasn't able to find - any other occurences). + any other occurrences). 7/7/97 : Fixed bug in Python shadow class generation with non-member functions that are returning more than one value. @@ -19962,7 +21359,7 @@ Version 1.1 (June 24, 1997) .... later ... int OldName(int); - Unlike %name, %rename will rename any occurence of the old name. + Unlike %name, %rename will rename any occurrence of the old name. This applies to functions, variables, class members and so forth. There is no way to disable %rename once set, but you can change the name by redeclaring it to something else. diff --git a/CHANGES.current b/CHANGES.current index 63af7206d..ad2f1e764 100644 --- a/CHANGES.current +++ b/CHANGES.current @@ -1,27 +1,53 @@ -This file contains the changes for the current release. +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.1 (in progress) -=========================== +Version 2.0.10 (in progress) +============================ -2010-07-16: wsfulton - Fix wrapping of function pointers and member function pointers when the function - returns by reference. +2013-01-18: Brant Kyser + [Java] Patch #15 - Allow the use of the nspace feature without the -package commandline option. + This works as long and the new jniclasspackage pragma is used to place the JNI intermediate class + into a package and the nspace feature is used to place all exposed types into a package. -2010-07-08: wsfulton - Fix #3024875 - shared_ptr of classes with non-public destructors. This also fixes - the "unref" feature when used on classes with non-public destructors. +2013-01-15: wsfulton + Fix Visual Studio examples to work when SWIG is unzipped into a directory containing spaces. -2010-06-10: wsfulton - [Lua] Fix SWIG_lua_isnilstring multiply defined when using multiple - modules and wrapping strings. Patch from 'Number Cruncher'. +2013-01-15: wsfulton + [C#] Fix cstype typemap lookup for member variables so that a fully qualified variable name + matches. For example: + %typemap(cstype) bool MVar::mvar "MyBool" + struct MVar { + bool mvar; + }; -2010-06-10: olly - [PHP] Fix directors to correctly call a method with has a - different name in PHP to C++ (we were always using the C++ name - in this case). +2013-01-11: Brant Kyser + [Java, C#, D] SF Bug #1299 - Fix generated names for when %nspace is used on + classes with the same name in two different namespaces. + +2013-01-11: Vladimir Kalinin + [C#] Add support for csdirectorin 'pre', 'post' and 'terminator' attributes. + +2013-01-08: olly + [PHP] Fix to work with a ZTS build of PHP (broken in 2.0.7). + +2013-01-07: olly + Fix bashism in configure, introduced in 2.0.9. + +2013-01-06: wsfulton + Pull patch #4 from ptomulik to fix SF Bug #1296 - Fix incorrect warning for virtual destructors + in templates, such as: + Warning 521: Illegal destructor name B< A >::~B(). Ignored. + +2013-01-05: wsfulton + [Python] Pull patch #3 from ptomulik to fix SF Bug #1295 - standard exceptions as + classes using the SWIG_STD_EXCEPTIONS_AS_CLASSES macro. + +2013-01-04: wsfulton + [Java] Pull patch #2 from BrantKyser to fix SF Bug #1283 - fix smart pointers in conjuction + with directors. + +2013-01-03: wsfulton + [Java] Pull patch #1 from BrantKyser to fix SF Bug #1278 - fix directors and nspace feature when + multilevel namespaces are used. -2010-06-03: wsfulton - Fix uncompileable code when %rename results in two enum items - with the same name. Reported by Vadim Zeitlin. diff --git a/COPYRIGHT b/COPYRIGHT index 40d09a1d6..3f4711a47 100644 --- a/COPYRIGHT +++ b/COPYRIGHT @@ -1,7 +1,7 @@ SWIG Copyright and Authors -------------------------- -Copyright (c) 1995-2010 The SWIG Developers +Copyright (c) 1995-2011 The SWIG Developers Copyright (c) 2005-2006 Arizona Board of Regents (University of Arizona). Copyright (c) 1998-2005 University of Chicago. Copyright (c) 1995-1998 The University of Utah and the Regents of the University of California @@ -15,6 +15,7 @@ Active SWIG Developers: Olly Betts (olly@survex.com) (PHP) Joseph Wang (joequant@gmail.com) (R) Xavier Delacour (xavier.delacour@gmail.com) (Octave) + David Nadlinger (code@klickverbot.at) (D) Past SWIG developers and major contributors include: Dave Beazley (dave-swig@dabeaz.com) (SWIG core, Python, Tcl, Perl) @@ -42,7 +43,7 @@ Past SWIG developers and major contributors include: Tiger Feng (songyanf@cs.uchicago.edu) (SWIG core) Mark Rose (mrose@stm.lbl.gov) (Directors) Jonah Beckford (beckford@usermail.com) (CHICKEN) - Ahmon Dancy (dancy@franz.com) (Allegro CL) + Ahmon Dancy (dancy@franz.com) (Allegro CL) Dirk Gerrits (Allegro CL) Neil Cawse (C#) Harco de Hilster (Java) @@ -53,19 +54,23 @@ Past SWIG developers and major contributors include: Duncan Temple Lang (R) Miklos Vajna (PHP directors) Mark Gossage (mark@gossage.cjb.net) (Lua) + Raman Gopalan (ramangopalan@gmail.com) (eLua) Gonzalo Garramuno (ggarra@advancedsl.com.ar) (Ruby, Ruby's UTL) John Lenz (Guile, MzScheme updates, Chicken module, runtime system) + Ian Lance Taylor (Go) + Vadim Zeitlin (PCRE) + Stefan Zager (szager@gmail.com) (Python) Past contributors include: James Michael DuPont, Clark McGrew, Dustin Mitchell, Ian Cooke, Catalin Dumitrescu, Baran Kovuk, Oleg Tolmatcev, Tal Shalif, Lluis Padro, Chris Seatory, Igor Bely, Robin Dunn, Edward Zimmermann, David Ascher, Dominique Dumont, Pier Giorgio Esposito, Hasan Baran Kovuk, - Klaus Wiederänders + Klaus Wiederänders, Richard Beare, Hans Oesterholt. (See CHANGES and CHANGES.current and the bug tracker for a more complete list). Past students: Songyan Feng (Chicago). - Xinghua Shi (Chicago). + Xinghua Shi (Chicago). Jing Cao (Chicago). Aquinas Hobor (Chicago). @@ -95,5 +100,5 @@ Mike Weiblen, Paul Brannan, Ram Bhamidipaty, Reinhard Fobbe, Rich Wales, Richard Salz, Roy Lecates, Rudy Albachten, Scott Drummonds Scott Michel, Shaun Lowry, Steve Galser, Tarn Weisner Burton, Thomas Weidner, Tony Seward, Uwe Steinmann, Vadim Chugunov, Wyss Clemens, -Zhong Ren. +Zhong Ren. diff --git a/Doc/Devel/engineering.html b/Doc/Devel/engineering.html index 7dfef2ad3..c12eb1328 100644 --- a/Doc/Devel/engineering.html +++ b/Doc/Devel/engineering.html @@ -25,7 +25,7 @@
  • 8. Naming Conventions
  • 9. Visibility
  • 10. Miscellaneous Coding Guidelines -
  • 11. SVN Tagging Conventions +
  • 11. Git Tagging Conventions @@ -119,8 +119,8 @@ are case-insensitive on Windows so this convention will prevent you from inadver creating two files that differ in case-only.

    -Each file should include a short abstract, license information and -a SVN revision tag like this: +Each file should include a short abstract and license information +like this:

    @@ -137,8 +137,6 @@ a SVN revision tag like this:
      * This file defines ...
      * ----------------------------------------------------------------------------- */
     
    -static char cvs[] = "$Id$ xxx.c";
    -
     #include "swig.h"
     
     /* Declarations */
    @@ -159,12 +157,6 @@ static int  avariable;
     
    -The SVN revision tag should be placed into a static string as shown -above mangled with the name of the file. -This adds the revision information to the SWIG executable and -makes it possible to extract version information from a raw binary -(sometimes useful in debugging). -

    As a general rule, files start to get unmanageable once they exceed about 2000 lines. Files larger than this should be broken up into @@ -379,10 +371,10 @@ making your changes. These are largely covered in the main documentation in the Extending.html file. -

    11. SVN Tagging Conventions

    +

    11. Git Tagging Conventions

    -Use svn tag to declare some set of file revisions as related in some +Use git tag to declare some set of file revisions as related in some symbolic way. This eases reference, retrieval and manipulation of these files later. At the moment (2001/01/16 14:02:53), the conventions are very simple; let's hope they stay that way! @@ -390,10 +382,10 @@ let's hope they stay that way!

    There are two types of tags, internal (aka personal) and external. Internal tags are used by SWIG developers primarily, whereas external -tags are used when communicating with people w/ anonymous svn access. +tags are used when communicating with people w/ anonymous git access.

    • Internal tags should start with the developer name and a hyphen. -
    • External tags should start with "v-". +
    • External tags should start with "rel-".
    That's all there is to it. Some example tags: @@ -402,10 +394,8 @@ That's all there is to it. Some example tags:
  • ttn-pre-xml-patch
  • ttn-post-xml-patch
  • ttn-going-on-vacation-so-dutifully-tagging-now -
  • v-1-3-a37-fixes-bug-2432 -
  • v-1-3-a37-fixes-bug-2433 -
  • v-1-3-a37-fixes-bug-2432-again -
  • v-1-3-a37-release +
  • rel-1.3.40 +
  • rel-2.0.9
    diff --git a/Doc/Devel/index.html b/Doc/Devel/index.html index 55c612ec3..4ddc63a76 100644 --- a/Doc/Devel/index.html +++ b/Doc/Devel/index.html @@ -21,6 +21,7 @@ The following documentation describe the internal APIs used by SWIG. These may
  • Parameter and Parameter list handling functions
  • Generic C/C++ Scanner interface
  • Wrapper objects. +
  • SWIG Runtime.
    diff --git a/Doc/Devel/internals.html b/Doc/Devel/internals.html index 6ac3947f7..94a82519d 100644 --- a/Doc/Devel/internals.html +++ b/Doc/Devel/internals.html @@ -7,11 +7,6 @@

    SWIG Internals Manual

    -Thien-Thi Nguyen
    - -

    -David M. Beazley
    -

    @@ -45,6 +40,10 @@ David M. Beazley
  • 5. C/C++ Wrapper Support Functions
  • 6. Symbol Naming Guidelines for Generated C/C++ Code
  • 7. Debugging SWIG + @@ -1015,15 +1014,139 @@ In the past SWIG has generated many symbols which flout the standard especially

    7. Debugging SWIG

    -Warning. Debugging SWIG is for the very patient. + +

    +The DOH types used in the SWIG source code are all typedefined to void. +Consequently, it is impossible for debuggers to automatically extract any information about DOH objects. +The easiest approach to debugging and viewing the contents of DOH objects is to make a call into one of the family of SWIG print functions from the debugger. +The "Debugging Functions" section in SWIG Parse Tree Handling lists them. +It is sometimes easier to debug by placing a few calls to these functions in code of interest and recompile, especially if your debugger cannot easily make calls into functions within a debugged binary. +

    + +

    +The SWIG distribution comes with some additional support for the gdb debugger in the Tools/swig.gdb file. +Follow the instructions in this file for 'installing'. +This support file provides an easy way to call into some of the family of SWIG print functions via additional user-defined gdb commands. +Some usage of the swigprint and locswigprint user-defined commands are demonstrated below. +

    + +

    +More often than not, a parse tree node needs to be examined. +The session below displays the node n in one of the Java language module wrapper functions. +The swigprint method is used to show the symbol name (symname - a DOH String type) and the node (n - a DOH Hash type). +

    +
    +
    +Breakpoint 1, JAVA::functionWrapper (this=0x97ea5f0, n=0xb7d2afc8) at Modules/java.cxx:799
    +799	    String *symname = Getattr(n, "sym:name");
    +(gdb) next
    +800	    SwigType *t = Getattr(n, "type");
    +(gdb) swigprint symname
    +Shape_x_set
    +(gdb) swigprint n
    +Hash(0xb7d2afc8) {
    +  'membervariableHandler:view' : variableHandler, 
    +  'feature:except' : 0, 
    +  'name' : x, 
    +  'ismember' : 1, 
    +  'sym:symtab' : Hash(0xb7d2aca8) {......}, 
    +  'nodeType' : cdecl, 
    +  'nextSibling' : Hash(0xb7d2af98) {.............}, 
    +  'kind' : variable, 
    +  'variableHandler:feature:immutable' : <Object 'VoidObj' at 0xb7cfa008>, 
    +  'sym:name' : Shape_x_set, 
    +  'view' : membervariableHandler, 
    +  'membervariableHandler:sym:name' : x, 
    +  'membervariableHandler:type' : double, 
    +  'membervariableHandler:parms' : <Object 'VoidObj' at 0xb7cfa008>, 
    +  'parentNode' : Hash(0xb7d2abc8) {..............................}, 
    +  'feature:java:enum' : typesafe, 
    +  'access' : public, 
    +  'parms' : Hash(0xb7cb9408) {......}, 
    +  'wrap:action' : if (arg1) (arg1)->x = arg2;, 
    +  'type' : void, 
    +  'memberset' : 1, 
    +  'sym:overname' : __SWIG_0, 
    +  'membervariableHandler:name' : x, 
    +}
    +
    +
    + +

    +Note that all the attributes in the Hash are shown, including the 'sym:name' attribute which was assigned to the symname variable. +

    + +

    +Hash types can be shown either expanded or collapsed. +When a Hash is shown expanded, all the attributes are displayed along with their values, otherwise a '.' replaces each attribute when collapsed. +Therefore a count of the dots provides the number of attributes within an unexpanded Hash. +Below shows the 'parms' Hash being displayed with the default Hash expansion of 1, then with 2 provided as the second argument to swigprint to expand to two Hash levels in order to view the contents of the collapsed 'nextSibling' Hash. +

    + +
    +
    +(gdb) swigprint 0xb7cb9408
    +Hash(0xb7cb9408) {
    +  'name' : self, 
    +  'type' : p.Shape, 
    +  'self' : 1, 
    +  'nextSibling' : Hash(0xb7cb9498) {...}, 
    +  'hidden' : 1, 
    +  'nodeType' : parm, 
    +}
    +(gdb) swigprint 0xb7cb9408 2
    +Hash(0xb7cb9408) {
    +  'name' : self, 
    +  'type' : p.Shape, 
    +  'self' : 1, 
    +  'nextSibling' : Hash(0xb7cb9498) {
    +    'name' : x, 
    +    'type' : double, 
    +    'nodeType' : parm, 
    +  }, 
    +  'hidden' : 1, 
    +  'nodeType' : parm, 
    +}
    +
    +
    + +

    +The same Hash can also be displayed with file and line location information via the locswigprint command. +

    + +
    +
    +(gdb) locswigprint 0xb7cb9408
    +example.h:11: [Hash(0xb7cb9408) {
    +Hash(0xb7cb9408) {
    +  'name' : self, 
    +  'type' : p.Shape, 
    +  'self' : 1, 
    +  'nextSibling' : Hash(0xb7cb9498) {...}, 
    +  'hidden' : 1, 
    +  'nodeType' : parm, 
    +}]
    +
    +
    + +

    +Tip: Commands in gdb can be shortened with whatever makes them unique and can be command completed with the tab key. +Thus swigprint can usually be shortened to sw and locswigprint to loc. +The help for each command can also be obtained within the debugging session, for example, 'help swigprint'. +

    + +

    +The sub-section below gives pointers for debugging DOH objects using casts and provides an insight into why it can be hard to debug SWIG without the family of print functions.

    -The DOH types are all typedefined to void. -Consequently, it is impossible for debuggers to extract any information about DOH objects. -Most debuggers will be able to display useful variable information when an object is cast to the appropriate type. -Below are some tips for displaying some of the DOH objects. -Be sure to compile with compiler optimisations turned off before attempting the casts shown in a debugger window else they are unlikely to work. -Even displaying the underlying string in a String* doesn't work straight off in all debuggers due to the multiple definition of String as a struct and a void. + +

    7.1 Debugging DOH Types The Hard Way

    + +The DOH types used in SWIG are all typedefined to void and hence the lack of type information for inspecting types within a debugger. +Most debuggers will however be able to display useful variable information when an object is cast to the appropriate type. +Getting at the underlying C string within DOH types is cumbersome, but possible with appropriate casts. +The casts below can be used in a debugger windows, but be sure to compile with compiler optimisations turned off before attempting the casts else they are unlikely to work. +Even displaying the underlying string in a String * doesn't work straight off in all debuggers due to the multiple definitions of String as a struct and a void.

    Below are a list of common SWIG types. @@ -1033,34 +1156,56 @@ With each is the cast that can be used in the debugger to extract the underlying

  • String *s;
  • -
    -(struct String *)((DohBase *)s)->data +(struct String *)((DohBase *)s)->data
    The underlying char * string can be displayed with
    -(*(struct String *)(((DohBase *)s)->data)).str +(*(struct String *)(((DohBase *)s)->data)).str

  • SwigType *t;
  • -
    -(struct String *)((DohBase *)t)->data +(struct String *)((DohBase *)t)->data
    The underlying char * string can be displayed with
    -(*(struct String *)(((DohBase *)t)->data)).str +(*(struct String *)(((DohBase *)t)->data)).str

  • const_String_or_char_ptr sc;
  • Either
    -(*(struct String *)(((DohBase *)sc)->data)).str +(*(struct String *)(((DohBase *)sc)->data)).str
    or
    -(char *)sc +(char *)sc
    will work depending on whether the underlying type is really a String * or char *. + +

    7.2 Debugging DOH memory allocation problems

    +
    +

    -Please also read the Debugging Functions section in SWIG Parse Tree Handling for the Swig_print_node(), Swig_print_tree() and Swig_print_tags() functions for displaying node contents. It is often easier to place a few calls to these functions in code of interest and recompile than use the debugger. +The DOH objects are reference counted and use pools for memory allocation. +The implementation is in memory.c. When there are memory corruption problems, +various memory allocator tools are normally used to diagnose problems. These can be used +on SWIG and can be very useful. However, they won't necessarily find use of stale DOH objects, +that is, DOH objects +that are used after they have been deleted. This is because the DOH memory allocator +grabs a chunk of memory from the C memory allocator and manages the usage internally. +Stale DOH object usage can be checked for by defining DOH_DEBUG_MEMORY_POOLS in +memory.c. If an attempt to use an object is made after the reference count is +zero, an assertion is triggered instead of quietly re-using the stale object... +

    + +
    +
    +swig: DOH/memory.c:91: DohCheck: Assertion `!DOH_object_already_deleted' failed.
    +
    +
    + +

    +This can be memory intensive as previously used memory in the pool is not re-used so is +only recommended for diagnosing memory corruption problems.


    diff --git a/Doc/Devel/tree.html b/Doc/Devel/tree.html index 43ad191f6..db3c6fee4 100644 --- a/Doc/Devel/tree.html +++ b/Doc/Devel/tree.html @@ -6,13 +6,6 @@

    SWIG Parse Tree Handling

    - -

    -David M. Beazley
    -dave-swig@dabeaz.com
    -December, 2006
    - -

    Introduction

    @@ -210,7 +203,33 @@ This function restores a node to the state it was in prior to the last Swig_

    Debugging Functions

    -The following functions are used to help debug SWIG parse trees. +

    +The following functions can be used to help debug any SWIG DOH object. +

    + +void Swig_print(DOH *object, int count = -1) + +
    +Prints to stdout a string representation of any DOH type. +The number of nested Hash types to expand is set by count (default is 1 if count<0). See Swig_set_max_hash_expand() to change default. +
    +
    +
    + +void Swig_print_with_location(DOH *object, int count = -1) + +
    +Prints to stdout a string representation of any DOH type, within [] brackets +for Hash and List types, prefixed by line and file information. +The number of nested Hash types to expand is set by count (default is 1 if count<0). See Swig_set_max_hash_expand() to change default. +
    +
    +
    + + +

    +The following functions can be used to help debug SWIG parse trees. +

    void Swig_print_tags(Node *node, String_or_char *prefix) diff --git a/Doc/Manual/Allegrocl.html b/Doc/Manual/Allegrocl.html index 5d00c4cd0..283ff7e2c 100644 --- a/Doc/Manual/Allegrocl.html +++ b/Doc/Manual/Allegrocl.html @@ -1118,7 +1118,7 @@ namespace BAR { function that returns an object (or pointer/reference) of C/C++ type X, the wrapping defun (or defmethod) on the Lisp side will automatically wrap the pointer returned in an instance - of the apropriate class. This makes it much easier to write and + 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.

    diff --git a/Doc/Manual/Android.html b/Doc/Manual/Android.html new file mode 100644 index 000000000..4d1be3944 --- /dev/null +++ b/Doc/Manual/Android.html @@ -0,0 +1,781 @@ + + + +SWIG and Android + + + +

    18 SWIG and Android

    + + + + + + +

    +This chapter describes SWIG's support of Android. +

    + + + +

    18.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 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

    + + +

    +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): +

    + +
    +
    +$ 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
    +
    +
    + +

    +The examples use a target id of 1. This might need changing depending on your setup. +After installation of the Android SDK, the available target ids can be viewed by running the command below. +Please adjust the id to suit your target device. +

    + +
    +
    +$ 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

    + + +

    +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 built into the app. +First create and build an app called SwigSimple in a subdirectory called simple using the commands below. +Adjust the --target id as mentioned earlier in the Examples introduction. +Managing Projects from the Command Line on the Android developer's site is a useful reference for these steps. +

    + +
    +
    +$ android create project --target 1 --name SwigSimple --path ./simple --activity SwigSimple --package org.swig.simple
    +$ cd simple
    +$ ant debug
    +
    +
    + +

    +Modify src/org/swig/simple/SwigSimple.java from the default to: +

    + +
    +
    +package org.swig.simple;
    +
    +import android.app.Activity;
    +import android.os.Bundle;
    +import android.view.View;
    +import android.widget.Button;
    +import android.widget.TextView;
    +import android.widget.ScrollView;
    +import android.text.method.ScrollingMovementMethod;
    +
    +public class SwigSimple extends Activity
    +{
    +    TextView outputText = null;
    +    ScrollView scroller = null;
    +
    +    /** Called when the activity is first created. */
    +    @Override
    +    public void onCreate(Bundle savedInstanceState)
    +    {
    +        super.onCreate(savedInstanceState);
    +        setContentView(R.layout.main);
    +
    +        outputText = (TextView)findViewById(R.id.OutputText);
    +        outputText.setText("Press 'Run' to start...\n");
    +        outputText.setMovementMethod(new ScrollingMovementMethod());
    +
    +        scroller = (ScrollView)findViewById(R.id.Scroller);
    +    }
    +
    +    public void onRunButtonClick(View view)
    +    {
    +      outputText.append("Started...\n");
    +      nativeCall();
    +      outputText.append("Finished!\n");
    +      
    +      // Ensure scroll to end of text
    +      scroller.post(new Runnable() {
    +        public void run() {
    +          scroller.fullScroll(ScrollView.FOCUS_DOWN);
    +        }
    +      });
    +    }
    +
    +    /** Calls into C/C++ code */
    +    public void nativeCall()
    +    {
    +        // TODO
    +    }
    +}
    +
    +
    + +

    +The above simply adds a Run button and scrollable text view as the GUI aspects of the program. +The associated resources need to be created, modify res/layout/main.xml as follows: +

    + +
    +
    +<?xml version="1.0" encoding="utf-8"?>
    +<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    +    android:orientation="vertical"
    +    android:layout_width="fill_parent"
    +    android:layout_height="fill_parent"
    +    >
    +<Button
    +    android:id="@+id/RunButton"  
    +    android:layout_width="wrap_content"  
    +    android:layout_height="wrap_content"  
    +    android:text="Run..."  
    +    android:onClick="onRunButtonClick"
    +    />
    +<ScrollView
    +    android:id="@+id/Scroller"
    +    android:layout_width="fill_parent"
    +    android:layout_height="fill_parent"
    +    >
    +<TextView
    +    android:id="@+id/OutputText"
    +    android:layout_width="wrap_content"
    +    android:layout_height="wrap_content"
    +    />
    +</ScrollView>
    +</LinearLayout>
    +
    +
    + +

    +Rebuild the project with your changes: +

    + +
    +
    +$ ant debug
    +
    +
    + +

    +Although there are no native function calls in the code, yet, you may want to check that this simple pure +Java app runs before adding in the native calls. +First, set up your Android device for hardware debugging, see Using hardware devices on the Android developer's site. +When complete your device should be listed in those attached, something like: +

    + +
    +
    +$ adb devices
    +List of devices attached 
    +A32-6DBE0001-9FF80000-015D62C3-02018028	device
    +
    +
    + +

    +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
    +Success
    +
    +
    + +

    +The newly installed 'SwigSimple' app will be amongst all your other applications on the home screen. Run the app and it will show a Run button text box below it. +Press the Run button to see the simple text output. +

    + +

    +The application can be uninstalled like any other application and in fact must be uninstalled before installing an updated version. Uninstalling is quite easy too from your host computer: +

    + +
    +
    +$ adb uninstall org.swig.simple
    +Success
    +
    +
    + +

    +Now that you have a pure Java Android app working, let's add some JNI code generated from SWIG. +

    + +

    +First create a jni subdirectory and then create some C source code in jni/example.c: +

    + +
    +
    +/* File : example.c */
    +
    +/* A global variable */
    +double Foo = 3.0;
    +
    +/* Compute the greatest common divisor of positive integers */
    +int gcd(int x, int y) {
    +  int g;
    +  g = y;
    +  while (x > 0) {
    +    g = x;
    +    x = y % x;
    +    y = g;
    +  }
    +  return g;
    +}
    +
    +
    + +

    +Create a SWIG interface file for this C code, jni/example.i: +

    + +
    +
    +/* File : example.i */
    +%module example
    +
    +%inline %{
    +extern int    gcd(int x, int y);
    +extern double Foo;
    +%}
    +
    +
    + +

    +Invoke SWIG as follows: +

    + +
    +
    +$ swig -java -package org.swig.simple -outdir src/org/swig/simple -o jni/example_wrap.c jni/example.i
    +
    +
    + +

    +SWIG generates the following files: +

    +
      +
    • src/org/swig/simple/exampleJNI.java
    • +
    • src/org/swig/simple/example.java
    • +
    • jni/example_wrap.c
    • +
    + +

    +Next we need to create a standard Android NDK build system file jni/Android.mk: +

    + +
    +
    +# File: Android.mk
    +LOCAL_PATH := $(call my-dir)
    +
    +include $(CLEAR_VARS)
    +
    +LOCAL_MODULE    := example
    +LOCAL_SRC_FILES := example_wrap.c example.c
    +
    +include $(BUILD_SHARED_LIBRARY)
    +
    +
    + +

    +See the Android NDK documentation for more on the NDK build system and getting started with the NDK. +A simple invocation of ndk-build will compile the .c files and generate a shared object/system library. Output will be similar to: +

    + +
    +
    +$ ndk-build
    +Compile thumb  : example <= example_wrap.c
    +Compile thumb  : example <= example.c
    +SharedLibrary  : libexample.so
    +Install        : libexample.so => libs/armeabi/libexample.so
    +
    +
    + +

    +Now that the C JNI layer has been built, we can write Java code to call into the this layer. +Modify the nativeCall method in src/org/swig/simple/SwigSimple.java to call the JNI code as follows and add the static constructor to load the system library containing the compiled JNI C code: +

    + +
    +
    +    /** Calls into C/C++ code */
    +    public void nativeCall()
    +    {
    +      // Call our gcd() function
    +      
    +      int x = 42;
    +      int y = 105;
    +      int g = example.gcd(x,y);
    +      outputText.append("The greatest common divisor of " + x + " and " + y + " is " + g + "\n");
    +
    +      // Manipulate the Foo global variable
    +
    +      // Output its current value
    +      double foo = example.getFoo();
    +      outputText.append("Foo = " + foo + "\n");
    +
    +      // Change its value
    +      example.setFoo(3.1415926);
    +
    +      // See if the change took effect
    +      outputText.append("Foo = " + example.getFoo() + "\n");
    +
    +      // Restore value
    +      example.setFoo(foo);
    +    }
    +
    +    /** static constructor */
    +    static {
    +        System.loadLibrary("example");
    +    }
    +
    +
    + +

    +Compile the Java code as usual, uninstall the old version of the app if still installed and re-install the new app: +

    + +
    +
    +$ ant debug
    +$ adb uninstall org.swig.simple
    +$ adb install bin/SwigSimple-debug.apk 
    +
    +
    + +

    +Run the app again and this time you will see the output pictured below, showing the result of calls into the C code: +

    + +
    Android screenshot of SwigSimple example
    + + +

    18.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. +

    + +

    +First create an Android project called SwigClass in a subdirectory called class. +The steps below create and build a the JNI C++ app. +Adjust the --target id as mentioned earlier in the Examples introduction. +

    + +
    +
    +$ android create project --target 1 --name SwigClass --path ./class --activity SwigClass --package org.swig.classexample
    +$ cd class
    +
    +
    + +

    +Now create a jni subdirectory and then create a C++ header file jni/example.h which defines our +hierarchy of shape classes: +

    + +
    +
    +/* File : example.h */
    +
    +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);
    +};
    +
    +
    + +

    +and create the implementation in the jni/example.cpp file: +

    + +
    +
    +/* File : example.cpp */
    +
    +#include "example.h"
    +#define M_PI 3.14159265358979323846
    +
    +/* Move the shape to a new location */
    +void Shape::move(double dx, double dy) {
    +  x += dx;
    +  y += dy;
    +}
    +
    +int Shape::nshapes = 0;
    +
    +double Circle::area(void) {
    +  return M_PI*radius*radius;
    +}
    +
    +double Circle::perimeter(void) {
    +  return 2*M_PI*radius;
    +}
    +
    +double Square::area(void) {
    +  return width*width;
    +}
    +
    +double Square::perimeter(void) {
    +  return 4*width;
    +}
    +
    +
    + +

    +Create a SWIG interface file for this C++ code in jni/example.i: +

    + +
    +
    +/* File : example.i */
    +%module example
    +
    +%{
    +#include "example.h"
    +%}
    +
    +/* Let's just grab the original header file here */
    +%include "example.h"
    +
    +
    + +

    +Invoke SWIG as follows, note that the -c++ option is required for C++ code: +

    + +
    +
    +$ swig -c++ -java -package org.swig.classexample -outdir src/org/swig/classexample -o jni/example_wrap.cpp jni/example.i
    +
    +
    + +

    +SWIG generates the following files: +

    +
      +
    • src/org/swig/classexample/Square.java
    • +
    • src/org/swig/classexample/exampleJNI.java
    • +
    • src/org/swig/classexample/example.java
    • +
    • src/org/swig/classexample/Circle.java
    • +
    • src/org/swig/classexample/Shape.java
    • +
    • jni/example_wrap.cpp
    • +
    + +

    +Next we need to create an Android NDK build system file for compiling the C++ code jni/Android.mk. +The -frtti compiler flag isn't strictly needed for this example, but is needed for any code that uses C++ RTTI: +

    + +
    +
    +# File: Android.mk
    +LOCAL_PATH := $(call my-dir)
    +
    +include $(CLEAR_VARS)
    +
    +LOCAL_MODULE    := example
    +LOCAL_SRC_FILES := example_wrap.cpp example.cpp
    +LOCAL_CFLAGS    := -frtti
    +
    +include $(BUILD_SHARED_LIBRARY)
    +
    +
    + + +

    +A simple invocation of ndk-build will compile the .cpp files and generate a shared object/system library. Output will be similar to: +

    + +
    +
    +$ ndk-build
    +Compile++ thumb  : example <= example_wrap.cpp
    +Compile++ thumb  : example <= example.cpp
    +StaticLibrary  : libstdc++.a
    +SharedLibrary  : libexample.so
    +Install        : libexample.so => libs/armeabi/libexample.so
    +
    +
    + +

    +Now that the C JNI layer has been built, we can write Java code to call into this layer. +Modify src/org/swig/classexample/SwigClass.java from the default to: +

    + +
    +
    +package org.swig.classexample;
    +
    +import android.app.Activity;
    +import android.os.Bundle;
    +import android.view.View;
    +import android.widget.Button;
    +import android.widget.TextView;
    +import android.widget.ScrollView;
    +import android.text.method.ScrollingMovementMethod;
    +
    +public class SwigClass extends Activity
    +{
    +    TextView outputText = null;
    +    ScrollView scroller = null;
    +
    +    /** Called when the activity is first created. */
    +    @Override
    +    public void onCreate(Bundle savedInstanceState)
    +    {
    +        super.onCreate(savedInstanceState);
    +        setContentView(R.layout.main);
    +
    +        outputText = (TextView)findViewById(R.id.OutputText);
    +        outputText.setText("Press 'Run' to start...\n");
    +        outputText.setMovementMethod(new ScrollingMovementMethod());
    +
    +        scroller = (ScrollView)findViewById(R.id.Scroller);
    +    }
    +
    +    public void onRunButtonClick(View view)
    +    {
    +      outputText.append("Started...\n");
    +      nativeCall();
    +      outputText.append("Finished!\n");
    +      
    +      // Ensure scroll to end of text
    +      scroller.post(new Runnable() {
    +        public void run() {
    +          scroller.fullScroll(ScrollView.FOCUS_DOWN);
    +        }
    +      });
    +    }
    +
    +    /** Calls into C/C++ code */
    +    public void nativeCall()
    +    {
    +      // ----- Object creation -----
    +
    +      outputText.append( "Creating some objects:\n" );
    +      Circle c = new Circle(10);
    +      outputText.append( "    Created circle " + c + "\n");
    +      Square s = new Square(10);
    +      outputText.append( "    Created square " + s + "\n");
    +
    +      // ----- Access a static member -----
    +
    +      outputText.append( "\nA total of " + Shape.getNshapes() + " shapes were created\n" );
    +
    +      // ----- Member data access -----
    +
    +      // Notice how we can do this using functions specific to
    +      // the 'Circle' class.
    +      c.setX(20);
    +      c.setY(30);
    +
    +      // Now use the same functions in the base class
    +      Shape shape = s;
    +      shape.setX(-10);
    +      shape.setY(5);
    +
    +      outputText.append( "\nHere is their current position:\n" );
    +      outputText.append( "    Circle = (" + c.getX() + " " + c.getY() + ")\n" );
    +      outputText.append( "    Square = (" + s.getX() + " " + s.getY() + ")\n" );
    +
    +      // ----- Call some methods -----
    +
    +      outputText.append( "\nHere are some properties of the shapes:\n" );
    +      Shape[] shapes = {c,s};
    +      for (int i=0; i<shapes.length; i++)
    +      {
    +        outputText.append( "   " + shapes[i].toString() + "\n" );
    +        outputText.append( "        area      = " + shapes[i].area() + "\n" );
    +        outputText.append( "        perimeter = " + shapes[i].perimeter() + "\n" );
    +      }
    +
    +      // Notice how the area() and perimeter() functions really
    +      // invoke the appropriate virtual method on each object.
    +
    +      // ----- Delete everything -----
    +
    +      outputText.append( "\nGuess I'll clean up now\n" );
    +
    +      // Note: this invokes the virtual destructor
    +      // You could leave this to the garbage collector
    +      c.delete();
    +      s.delete();
    +
    +      outputText.append( Shape.getNshapes() + " shapes remain\n" );
    +      outputText.append( "Goodbye\n" );
    +    }
    +
    +    /** static constructor */
    +    static {
    +        System.loadLibrary("example");
    +    }
    +}
    +
    +
    + +

    +Note the static constructor and the interesting JNI code is in the nativeCall method. +The remaining code deals with the GUI aspects which are identical to the previous C simple example. Modify res/layout/main.xml to contain the xml for the 'Run' button and scrollable text view: +

    + +
    +
    +<?xml version="1.0" encoding="utf-8"?>
    +<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    +    android:orientation="vertical"
    +    android:layout_width="fill_parent"
    +    android:layout_height="fill_parent"
    +    >
    +<Button
    +    android:id="@+id/RunButton"  
    +    android:layout_width="wrap_content"  
    +    android:layout_height="wrap_content"  
    +    android:text="Run..."  
    +    android:onClick="onRunButtonClick"
    +    />
    +<ScrollView
    +    android:id="@+id/Scroller"
    +    android:layout_width="fill_parent"
    +    android:layout_height="fill_parent"
    +    >
    +<TextView
    +    android:id="@+id/OutputText"
    +    android:layout_width="wrap_content"
    +    android:layout_height="wrap_content"
    +    />
    +</ScrollView>
    +</LinearLayout>
    +
    +
    + + +

    +Compile the Java code as usual, uninstall the old version of the app if installed and re-install the new app: +

    + +
    +
    +$ ant debug
    +$ adb uninstall org.swig.classexample
    +$ adb install bin/SwigClass-debug.apk 
    +
    +
    + +

    +Run the app to see the result of calling the C++ code from Java: +

    + +
    Android screenshot of SwigClass example
    + +

    18.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

    + + +

    +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 to use. +See the NDK documentation in the $NDKROOT/docs folder especially CPLUSPLUS-SUPPORT.html. +Below is an example of the Application.mk file to make the STLport static library available for use: +

    + +
    +
    +# File: Application.mk
    +APP_STL := gnustl_static
    +
    +
    + + + + + diff --git a/Doc/Manual/CSharp.html b/Doc/Manual/CSharp.html index 909357f37..6df2594c4 100644 --- a/Doc/Manual/CSharp.html +++ b/Doc/Manual/CSharp.html @@ -5,12 +5,13 @@ -

    18 SWIG and C#

    +

    19 SWIG and C#

    -

    18.3.2 Managed arrays using P/Invoke default array marshalling

    +

    19.4.2 Managed arrays using P/Invoke default array marshalling

    @@ -575,7 +620,8 @@ marshalling for the arrays:

     [DllImport("example", EntryPoint="CSharp_myArrayCopy")]
     public static extern void myArrayCopy([In, MarshalAs(UnmanagedType.LPArray)]int[] jarg1, 
    -                                      [Out, MarshalAs(UnmanagedType.LPArray)]int[] jarg2, int jarg3);
    +                                      [Out, MarshalAs(UnmanagedType.LPArray)]int[] jarg2,
    +                                       int jarg3);
     
    @@ -617,19 +663,20 @@ This results in the module class method

    -and intermediate class method +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, int jarg3);
    +                                        [In, Out, MarshalAs(UnmanagedType.LPArray)]int[] jarg2,
    +                                         int jarg3);
     
    -

    18.3.3 Managed arrays using pinning

    +

    19.4.3 Managed arrays using pinning

    @@ -696,7 +743,8 @@ 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, nitems); + examplePINVOKE.myArrayCopy((IntPtr)swig_ptrTo_sourceArray, (IntPtr)swig_ptrTo_targetArray, + nitems); } } } @@ -710,7 +758,7 @@ marshalling is the "unsafe" quantifier, which is required because we are handlin

    -Also the intermediate class method looks a little different from the default marshalling +Also the intermediary class method looks a little different from the default marshalling example - the method is expecting an IntPtr as the parameter type.

    @@ -723,7 +771,7 @@ public static extern void myArrayCopy(IntPtr jarg1, IntPtr jarg2, int jarg3); -

    18.4 C# Exceptions

    +

    19.5 C# Exceptions

    @@ -820,7 +868,7 @@ set so should only be used when a C# exception is not created.

    -

    18.4.1 C# exception example using "check" typemap

    +

    19.5.1 C# exception example using "check" typemap

    @@ -1002,7 +1050,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.

    -

    18.4.2 C# exception example using %exception

    +

    19.5.2 C# exception example using %exception

    @@ -1067,7 +1115,7 @@ The managed code generated does check for the pending exception as mentioned ear -

    18.4.3 C# exception example using exception specifications

    +

    19.5.3 C# exception example using exception specifications

    @@ -1124,7 +1172,7 @@ SWIGEXPORT void SWIGSTDCALL CSharp_evensonly(int jarg1) { Multiple catch handlers are generated should there be more than one exception specifications declared.

    -

    18.4.4 Custom C# ApplicationException example

    +

    19.5.4 Custom C# ApplicationException example

    @@ -1258,7 +1306,7 @@ try { -

    18.5 C# Directors

    +

    19.6 C# Directors

    @@ -1271,7 +1319,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.

    -

    18.5.1 Directors example

    +

    19.6.1 Directors example

    @@ -1392,7 +1440,7 @@ CSharpDerived - UIntMethod(123) -

    18.5.2 Directors implementation

    +

    19.6.2 Directors implementation

    @@ -1578,7 +1626,7 @@ void SwigDirector_Base::BaseBoolMethod(Base const &b, bool flag) { -

    18.5.3 Director caveats

    +

    19.6.3 Director caveats

    @@ -1626,7 +1674,42 @@ 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.

    -

    18.6 C# Typemap examples

    +

    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: +

    + +
    +
    +  SWIG_CSBODY_PROXY(public, public, SWIGTYPE)
    +  SWIG_CSBODY_TYPEWRAPPER(public, public, public, SWIGTYPE)
    +
    +
    + +

    +Alternatively, instead of exposing these as public, consider +using the [assembly:InternalsVisibleTo("Name")] attribute available in the .NET framework when you +know which assemblies these can be exposed to. +Another approach would be to make these public, but also to hide them from intellisense by using +the [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

    This section includes a few examples of typemaps. For more examples, you @@ -1634,7 +1717,7 @@ might look at the files "csharp.swg" and "typemaps.i" in the SWIG library. -

    18.6.1 Memory management when returning references to member variables

    +

    19.8.1 Memory management when returning references to member variables

    @@ -1758,7 +1841,7 @@ public class Bike : IDisposable { Note the addReference call.

    -

    18.6.2 Memory management for objects passed to the C++ layer

    +

    19.8.2 Memory management for objects passed to the C++ layer

    @@ -1877,7 +1960,7 @@ The 'cscode' typemap simply adds in the specified code into the C# proxy class. -

    18.6.3 Date marshalling using the csin typemap and associated attributes

    +

    19.8.3 Date marshalling using the csin typemap and associated attributes

    @@ -1974,13 +2057,13 @@ The typemaps to achieve this are shown below.

    -%typemap(cstype) const CDate& "System.DateTime"
    +%typemap(cstype) const CDate & "System.DateTime"
     %typemap(csin, 
              pre="    CDate temp$csinput = new CDate($csinput.Year, $csinput.Month, $csinput.Day);"
             ) const CDate &
              "$csclassname.getCPtr(temp$csinput)"
     
    -%typemap(cstype) CDate& "out System.DateTime"
    +%typemap(cstype) CDate & "out System.DateTime"
     %typemap(csin, 
              pre="    CDate temp$csinput = new CDate();", 
              post="      $csinput = new System.DateTime(temp$csinput.getYear(),"
    @@ -2109,7 +2192,8 @@ public class example {
         try {
           examplePINVOKE.addYears(CDate.getCPtr(temppDate), years);
         } finally {
    -      pDate = new System.DateTime(temppDate.getYear(), temppDate.getMonth(), temppDate.getDay(), 0, 0, 0);
    +      pDate = new System.DateTime(temppDate.getYear(), temppDate.getMonth(), temppDate.getDay(),
    +                                  0, 0, 0);
         }
       }
       ...
    @@ -2126,13 +2210,13 @@ The subtractYears method is nearly identical to the above addYears<
     
     %typemap(csin,
    -         pre="    using (CDate temp$csinput = new CDate($csinput.Year, $csinput.Month, $csinput.Day)) {",
    -         post="      $csinput = new System.DateTime(temp$csinput.getYear(),"
    -              " temp$csinput.getMonth(), temp$csinput.getDay(), 0, 0, 0);", 
    -         terminator="    } // terminate temp$csinput using block",
    -         cshin="ref $csinput"
    -        ) CDate *
    -         "$csclassname.getCPtr(temp$csinput)"
    +  pre="    using (CDate temp$csinput = new CDate($csinput.Year, $csinput.Month, $csinput.Day)) {",
    +  post="      $csinput = new System.DateTime(temp$csinput.getYear(),"
    +       " temp$csinput.getMonth(), temp$csinput.getDay(), 0, 0, 0);", 
    +  terminator="    } // terminate temp$csinput using block",
    +  cshin="ref $csinput"
    + ) CDate *
    +  "$csclassname.getCPtr(temp$csinput)"
     
     void subtractYears(CDate *pDate, int years) {
       *pDate = CDate(pDate->getYear() - years, pDate->getMonth(), pDate->getDay());
    @@ -2152,7 +2236,8 @@ public class example {
         try {
           examplePINVOKE.subtractYears(CDate.getCPtr(temppDate), years);
         } finally {
    -      pDate = new System.DateTime(temppDate.getYear(), temppDate.getMonth(), temppDate.getDay(), 0, 0, 0);
    +      pDate = new System.DateTime(temppDate.getYear(), temppDate.getMonth(), temppDate.getDay(),
    +                                  0, 0, 0);
         }
         } // terminate temppDate using block
       }
    @@ -2161,7 +2246,7 @@ public class example {
     
    -

    18.6.4 A date example demonstrating marshalling of C# properties

    +

    19.8.4 A date example demonstrating marshalling of C# properties

    @@ -2189,7 +2274,7 @@ Console.WriteLine("Important date: " + importantDate);

    -When SWIG wraps a variable that is a class/struct/union, it is wrapped using a pointer to the type for the reasons given in Stucture data members. +When SWIG wraps a variable that is a class/struct/union, it is wrapped using a pointer to the type for the reasons given in Structure data members. The typemap type required is thus CDate *. Given that the previous section already designed CDate * typemaps, we'll use those same typemaps plus the 'csvarin' and 'csvarout' typemaps.

    @@ -2261,8 +2346,69 @@ Some points to note:
  • The 'csin' typemap has 'pre', 'post' and 'cshin' attributes, and these are all ignored in the property set. The code in these attributes must instead be replicated within the 'csvarin' typemap. The line 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

    -

    18.6.5 Turning wrapped classes into partial classes

    + +

    +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 example like this: +

    + +
    +class CDate {
    +  ...
    +  void setYear(int);
    +  void setMonth(int);
    +  void setDay(int);
    +};
    +struct Action {
    +  virtual void someCallback(CDate &date);
    +  virtual ~Action();
    +  ...
    +};
    +
    + +

    +and declare %feature ("director") for the Action class, we would have to define additional +marshalling rules for CDate & parameter. The typemap may look like this: +

    + +
    +%typemap(csdirectorin,
    +         pre="System.DateTime temp$iminput = new System.DateTime();",
    +         post="CDate temp2$iminput = new CDate($iminput, false);\n"
    +              "temp2$iminput.setYear(tempdate.Year);\n"
    +              "temp2$iminput.setMonth(tempdate.Month);\n"
    +              "temp2$iminput.setDay(tempdate.Day);"
    +         ) CDate &date "out temp$iminput"
    +
    + +

    +The generated proxy class code will then contain the following wrapper for calling user-overloaded someCallback(): +

    + +
    +...
    +  private void SwigDirectorsomeCallback(IntPtr date) {
    +    System.DateTime tempdate = new System.DateTime();
    +    try {
    +      someCallback(out tempdate);
    +    } finally {
    +      // we create a managed wrapper around the existing C reference, just for convenience
    +      CDate temp2date = new CDate(date, false);
    +      temp2date.setYear(tempdate.Year);
    +      temp2date.setMonth(tempdate.Month);
    +      temp2date.setDay(tempdate.Day);
    +    }
    +  }
    +...
    +
    +

    +Pay special attention to the memory management issues, using these attributes. +

    + + +

    19.8.6 Turning wrapped classes into partial classes

    @@ -2362,7 +2508,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.

    -

    18.6.6 Extending proxy classes with additional C# code

    +

    19.8.7 Extending proxy classes with additional C# code

    @@ -2401,7 +2547,7 @@ public class ExtendMe : IDisposable {

  • -

    18.6.7 Underlying type for enums

    +

    19.8.8 Underlying type for enums

    diff --git a/Doc/Manual/Chicken.html b/Doc/Manual/Chicken.html index 006b648d6..4e43b9b90 100644 --- a/Doc/Manual/Chicken.html +++ b/Doc/Manual/Chicken.html @@ -8,7 +8,7 @@ -

    19 SWIG and Chicken

    +

    20 SWIG and Chicken

      @@ -72,7 +72,7 @@

      -

      19.1 Preliminaries

      +

      20.1 Preliminaries

      @@ -89,7 +89,7 @@ directory for the basic steps to run SWIG CHICKEN.

      -

      19.1.1 Running SWIG in C mode

      +

      20.1.1 Running SWIG in C mode

      @@ -122,7 +122,7 @@ object files and linked into your project.

      -

      19.1.2 Running SWIG in C++ mode

      +

      20.1.2 Running SWIG in C++ mode

      @@ -151,10 +151,10 @@ object files and linked into your project.

      -

      19.2 Code Generation

      +

      20.2 Code Generation

      -

      19.2.1 Naming Conventions

      +

      20.2.1 Naming Conventions

      @@ -170,7 +170,7 @@ %rename SWIG directive in the SWIG interface file.

      -

      19.2.2 Modules

      +

      20.2.2 Modules

      @@ -192,7 +192,7 @@ (uses modulename)) CHICKEN Scheme form.

      -

      19.2.3 Constants and Variables

      +

      20.2.3 Constants and Variables

      @@ -229,7 +229,7 @@ for info on how to apply the %feature.

      -

      19.2.4 Functions

      +

      20.2.4 Functions

      @@ -248,7 +248,7 @@ parameters). The return values can then be accessed with (call-with-values).

      -

      19.2.5 Exceptions

      +

      20.2.5 Exceptions

      The SWIG chicken module has support for exceptions thrown from @@ -290,7 +290,7 @@

    -

    19.3 TinyCLOS

    +

    20.3 TinyCLOS

    @@ -333,7 +333,7 @@

    -

    19.4 Linkage

    +

    20.4 Linkage

    @@ -354,7 +354,7 @@

    -

    19.4.1 Static binary or shared library linked at compile time

    +

    20.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.

    -

    19.4.2 Building chicken extension libraries

    +

    20.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.

    -

    19.4.3 Linking multiple SWIG modules with TinyCLOS

    +

    20.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.

    -

    19.5 Typemaps

    +

    20.5 Typemaps

    @@ -486,7 +486,7 @@ all the modules.

    Lib/chicken/chicken.swg.

    -

    19.6 Pointers

    +

    20.6 Pointers

    @@ -519,7 +519,7 @@ all the modules.

    type. flags is either zero or SWIG_POINTER_DISOWN (see below).

    -

    19.6.1 Garbage collection

    +

    20.6.1 Garbage collection

    If the owner flag passed to SWIG_NewPointerObj is 1, NewPointerObj will add a @@ -550,7 +550,7 @@ all the modules.

    must be called manually.

    -

    19.7 Unsupported features and known problems

    +

    20.7 Unsupported features and known problems

    -

    19.7.1 TinyCLOS problems with Chicken version <= 1.92

    +

    20.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 66bf41264..42e135140 100644 --- a/Doc/Manual/Contents.html +++ b/Doc/Manual/Contents.html @@ -5,7 +5,7 @@ SWIG Users Manual -

    SWIG Users Manual

    +

    SWIG Users Manual

    @@ -152,6 +152,12 @@

  • Arrays
  • Creating read-only variables
  • Renaming and ignoring declarations +
  • Default/optional arguments
  • Pointers to functions and callbacks @@ -237,6 +243,7 @@
  • Exception handling with %catches
  • Pointers to Members
  • Smart pointers and operator->() +
  • C++ reference counted objects - ref/unref feature
  • Using declarations and inheritance
  • Nested classes
  • A brief rant about const-correctness @@ -256,8 +263,11 @@
  • Macro Expansion
  • SWIG Macros
  • C99 and GNU Extensions +
  • Preprocessing and delimiters +
  • Preprocessor and Typemaps
  • Viewing preprocessor output
  • The #error and #warning directives @@ -391,6 +401,7 @@
  • Typemaps for multiple target languages
  • Optimal code generation when returning by value
  • Multi-argument typemaps +
  • Typemap warnings
  • Typemap fragments
  • History @@ -623,13 +634,32 @@ -

    18 SWIG and C#

    +

    18 SWIG and Android

    + + + + + +

    19 SWIG and C#

    -

    19 SWIG and Chicken

    +

    20 SWIG and Chicken

    @@ -701,7 +733,41 @@
    -

    20 SWIG and Go

    +

    21 SWIG and D

    + + + + + +

    22 SWIG and Go

    @@ -725,12 +791,14 @@
  • Go Templates
  • Go Director Classes
  • Default Go primitive type mappings +
  • Output arguments +
  • Adding additional go code -

    21 SWIG and Guile

    +

    23 SWIG and Guile

    @@ -765,7 +833,7 @@
    -

    22 SWIG and Java

    +

    24 SWIG and Java

    @@ -847,6 +915,7 @@
  • Overhead and code bloat
  • Simple directors example
  • Director threading issues +
  • Director performance tuning
  • Accessing protected members
  • Common customization features @@ -862,6 +931,7 @@
  • Simple pointers
  • Wrapping C arrays with Java arrays
  • Unbounded C Arrays +
  • Binary data vs Strings
  • Overriding new and delete to allocate from Java heap
  • Java typemaps @@ -902,12 +972,12 @@
  • Performance concerns and hints
  • Debugging -
  • Examples +
  • Java Examples -

    23 SWIG and Common Lisp

    +

    25 SWIG and Common Lisp

    @@ -930,7 +1000,7 @@
    -

    24 SWIG and Lua

    +

    26 SWIG and Lua

    @@ -938,6 +1008,7 @@
  • Preliminaries
  • Running SWIG -
  • Typemaps +
  • Typemaps -
  • Writing typemaps +
  • Writing typemaps -
  • Customization of your Bindings +
  • Customization of your Bindings -
  • Details on the Lua binding +
  • Details on the Lua binding -

    25 SWIG and Modula-3

    +

    27 SWIG and Modula-3

    @@ -1025,17 +1097,19 @@
    -

    26 SWIG and MzScheme

    +

    28 SWIG and MzScheme/Racket

    -

    27 SWIG and Ocaml

    +

    29 SWIG and Ocaml

    @@ -1086,7 +1160,7 @@
    -

    28 SWIG and Octave

    +

    30 SWIG and Octave

    @@ -1094,6 +1168,7 @@
  • Preliminaries
  • Running SWIG @@ -1121,7 +1196,7 @@ -

    29 SWIG and Perl5

    +

    31 SWIG and Perl5

    @@ -1188,7 +1263,7 @@
    -

    30 SWIG and PHP

    +

    32 SWIG and PHP

    @@ -1228,7 +1303,7 @@
    -

    31 SWIG and Pike

    +

    33 SWIG and Pike

    @@ -1252,7 +1327,7 @@
    -

    32 SWIG and Python

    +

    34 SWIG and Python

    @@ -1285,11 +1360,16 @@
  • C++ namespaces
  • C++ templates
  • C++ Smart Pointers -
  • C++ Reference Counted Objects (ref/unref) +
  • C++ reference counted objects
  • Further details on the Python class interface @@ -1340,6 +1420,8 @@
  • %feature("docstring") @@ -1355,7 +1437,23 @@ -

    33 SWIG and Ruby

    +

    35 SWIG and R

    + + + + + +

    36 SWIG and Ruby

    @@ -1489,7 +1587,7 @@
    -

    34 SWIG and Tcl

    +

    37 SWIG and Tcl

    @@ -1555,23 +1653,7 @@
    -

    35 SWIG and R

    - - - - - -

    36 Extending SWIG to support new languages

    +

    38 Extending SWIG to support new languages

    diff --git a/Doc/Manual/Customization.html b/Doc/Manual/Customization.html index 7f164ac57..b75eda9c4 100644 --- a/Doc/Manual/Customization.html +++ b/Doc/Manual/Customization.html @@ -454,6 +454,11 @@ variables are replaced with. 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 @@ -479,6 +484,16 @@ variables are replaced with. 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. + +

    @@ -704,6 +719,11 @@ 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: diff --git a/Doc/Manual/D.html b/Doc/Manual/D.html new file mode 100644 index 000000000..43fa69196 --- /dev/null +++ b/Doc/Manual/D.html @@ -0,0 +1,454 @@ + + + +SWIG and D + + + + +

    21 SWIG and D

    + + + + + + +

    21.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?

    + +

    Well, besides the obvious downside that the C header files have to be manually converted to D modules for this to work, there is one major inconvenience with this approach: D code usually is on a higher abstraction level than C, and many of the features that make D interesting are simply not available when dealing with C libraries, requiring you e.g. to manually convert strings between pointers to \0-terminated char arrays and D char arrays, making the algorithms from the D2 standard library unusable with C arrays and data structures, and so on.

    + +

    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).

    + + +

    21.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:

    + +
    +
    -d2
    +
    +

    By default, SWIG generates code for D1/Tango. Use the -d2 flag to target D2/Phobos instead.

    +
    + +
    -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.

    +
    + +
    -package <pkg>
    +
    +

    By default, the proxy D modules and the intermediary D module are written to the root package. Using this option, you can specify another target package instead.

    +
    + +
    -wrapperlibrary <wl>
    +
    +

    The code SWIG generates to dynamically load the C/C++ wrapper layer looks for a library called $module_wrap by default. With this switch, you can override the name of the file the wrapper code loads at runtime (the lib prefix and the suffix for shared libraries are appended automatically, depending on the OS).

    +

    This might especially be useful if you want to invoke SWIG several times on separate modules, but compile the resulting code into a single shared library.

    +
    +
    + + +

    21.3 Typemaps

    + + +

    21.3.1 C# <-> D name comparison

    + + +

    If you already know the SWIG C# module, you might find the following name comparison table useful:

    + +
    + ctype                  <->  ctype
    + imtype                 <->  imtype
    + cstype                 <->  dtype
    + csin                   <->  din
    + csout                  <->  dout
    + csdirectorin           <->  ddirectorin
    + csdirectorout          <->  ddirectorout
    + csinterfaces           <->  dinterfaces
    + csinterfaces_derived   <->  dinterfaces_derived
    + csbase                 <->  dbase
    + csclassmodifiers       <->  dclassmodifiers
    + cscode                 <->  dcode
    + csimports              <->  dimports
    + csbody                 <->  dbody
    + csfinalize             <->  ddestructor
    + csdestruct             <->  ddispose
    + csdestruct_derived     <->  ddispose_derived
    +
    + + +

    21.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.

    + +

    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

    + + +

    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 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

    + + +

    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 full chain of type conversions when a director callback is invoked looks like this:

    + +
    +      type              CPPClass::method(type a)
    +        ↑                       ↓
    +   <directorout>          <directorin>
    +        ↑                       ↓
    +      ctype             methodCallback(ctype a)           C++
    + :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
    +      imtype            methodCallback(imtype a)           D
    +        ↑                       ↓
    +  <ddirectorout>          <ddirectorin>
    +        ↑                       ↓
    +      dtype             DClass.method(dtype a)
    + + +

    21.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

    + + +

    These typemaps are used for generating the skeleton of proxy classes for C++ types.

    + +

    By overriding dbase, dinterfaces or dinterfaces_derived, the inheritance chain of the generated proxy class for a type can be modified. dclassmodifiers allows you to add any custom modifiers around the class keyword.

    + +

    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.

    + + +

    21.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.

    + +

    When generating D wrappers, a few additional macros are available:

    +
    +
    $dclassname (C#: $csclassname)
    +
    +

    This special variable works similar to $n_type in that it returns the name of a type - it expands to the D proxy class name of the type being wrapped. If the type does not have an associated proxy class, it expands to the type wrapper class name, for example, SWIGTYPE_p_p_SomeCppClass is generated when wrapping SomeCppClass **.

    +

    There are two other variants available, $&dclassname and $*dclassname. The former adds a level of indirection, while the latter removes one. For instance, when wrapping Foo **, $*dclassname would be replaced by the proxy class name corresponding to Foo *.

    +
    + +
    $dclazzname (C#: $csclazzname)
    +
    +

    This special variable 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 might be useful for calling certain functions in the wrapper layer (e.g. upcast wrappers) which are mangled like this.

    +
    + +
    $null
    +

    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;).

    + +
    $dinput (C#: $csinput)
    +
    +

    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

    +
    +%typemap(din) SomeClass * "SomeClass.getCPointer($dinput)"
    +
    +%inline %{
    +  class SomeClass {};
    +  void foo(SomeClass *arg);
    +%}
    +

    leads to the following D proxy code being generated:

    +
    +void foo(SomeClass arg) {
    +  example_im.foo(SomeClass.getCPointer(arg));
    +}
    + +
    $imcall and $owner (C#: $imcall)
    +
    +

    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:

    +
    +%typemap(dout) SomeClass * {
    +  return new SomeClass($imcall, $owner);
    +}
    +
    +%inline %{
    +  class SomeClass;
    +  SomeClass *foo();
    +
    +  %newobject bar();
    +  SomeClass *bar();
    +%}
    +

    The code generated for foo() and bar() looks like this:

    +
    +SomeClass foo() {
    +  return new SomeClass(example_im.foo(), false);
    +}
    +
    +SomeClass bar() {
    +  return new SomeClass(example_im.bar(), true);
    +}
    +
    +
    + +
    $dcall and $winput (C#: $cscall, $iminput)
    +

    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++.

    + +
    $excode
    +

    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.

    + +
    $dbaseclass
    +

    Currently for internal use only, it contains the D name of the C++ base class (if any) inside proxy classes.

    + +
    $directorconnect
    +
    +

    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.

    +

    This is how the default dconstructor typemap looks like (you usually do not want to specify a custom one):

    +
    +%typemap(dconstructor, excode=SWIGEXCODE,
    +         directorconnect="\n  swigDirectorConnect();") SWIGTYPE {
    +  this($imcall, true);$excode$directorconnect
    +}
    +
    +
    + +
    $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.

    +

    Consider the following code snippet:

    +
    +%typemap(dinterfaces) SomeClass "AnInterface, AnotherInterface";
    +
    +

    This causes SWIG to add AnInterface and AnotherInterface to the base class list of SomeClass:

    +
    +class SomeClass : AnInterface, AnotherInterface {
    +  ...
    +}
    +
    +

    For this to work, AnInterface and AnotherInterface have to be in scope. If SWIG is not in split proxy mode, this is already the case, but it it is, they have to be added to the import list via the dimports typemap. Additionally, the import statement depends on the package SWIG is configured to emit the modules to.

    +

    The $importtype macro helps you to elegantly solve this problem:

    +
    +%typemap(dimports) RemoteMpe %{
    +$importtype(AnInterface)
    +$importtype(AnotherInterface)
    +%}
    +
    +

    If SWIG is in split proxy mode, it expands to an import statement for the specified type, to nothing if not.

    +
    + +
    $module
    +

    Expands to the name of the main proxy D module.

    + +
    $imdmodule
    +

    Contains the fully qualified name of the intermediary D module.

    +
    + + +

    21.4 %features

    + + +

    The D module defines a number of directives which modify the SWIG features set globally or for a specific declaration:

    + + +
    +
    %dmanifestconst and %dconstvalue(value)
    +
    +

    Out of the box, SWIG generates accessor methods for C #defines and C++ constants. The %dmanifestconst directive enables wrapping these constants as D manifest constants (const in D1, enum in D2).

    +

    For this to work, the C/C++ code for the constant value must directly compile as D code, though. If this is not the case, you can manually override the expression written to the D proxy module using the %dconstvalue directive, passing the new value as parameter.

    +

    For enums, again %dconstvalue can be used to override the value of an enum item if the initializer should not compile in D.

    +
    + +
    %dmethodmodifiers
    +
    +

    This directive can be used to override the modifiers for a proxy function. For instance, you could make a public C++ member function private in D like this:

    +
    +%dmethodmodifiers A::foo "private";
    +
    +%inline %{
    +struct A {
    +  void foo();
    +};
    +%}
    +
    +
    +
    + + +

    21.5 Pragmas

    + + +

    There are a few SWIG pragmas specific to the D module, which you can use to influence the D code SWIG generates:

    + +
    +
    %pragma(d) imdmodulecode
    +

    The passed text (D code) is copied verbatim to the intermediary D module. For example, it can be (and is, internally) used to emit additional private helper code for the use by proxy typemaps.

    + +
    %pragma(d) imdmoduleimports
    +

    Additional code to be emitted to the imports section of the 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).

    + +
    %pragma(d) globalproxyimports
    +
    +

    The D module currently does not support specifying dependencies on external modules (e.g. from the standard library) for the D typemaps. To add the import statements to the proxy modules (resp. to all proxy modules if in split proxy mode), you can use the globalproxyimports directive.

    +

    For example:

    +
    +%typemap(din) char[] "($dinput ? tango.stdc.stringz.toStringz($dinput) : null)"
    +%pragma(d) globalproxyimports = "static import tango.stdc.stringz;";
    +
    +
    + +
    %pragma(d) wrapperloadercode
    +
    +

    The D code for loading the wrapper library (it is copied to the intermediary D module). The $wrapperloaderbindcode variable is replaced by the list of commands for binding the functions from the wrapper library to the symbols in the intermediary D module.

    +

    Each time this pragma is specified, the previous value is overwritten.

    +
    + +
    %pragma(d) wrapperloaderbindcommand
    +
    +

    The D command to use for binding the wrapper functions from the C/C++ library to the symbols in the intermediary D module. The $function variable contains the name of the D function in the wrap module, the $symbol variable is replaced by the name of the symbol in the library.

    +

    Each time this pragma is specified, the previous value is overwritten.

    +
    +
    + + +

    21.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: 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.

    + +

    The implementation details of this are a bit crude, but the SWIG D module automatically takes care of this, as long as it is able to detect that an exception could potentially be thrown (e.g. because the C++ method has a throw(...) exception specification).

    + +

    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

    + + +

    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++.

    + +

    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)

    + + +

    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.

    + + +

    21.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, 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.

    + +

    Central to this custom pointer handling scheme are two typemap attributes: the cprimitive attribute on the dtype typemap and the nativepointer attribute on all the typemaps which influence the D side of the code (dtype, din, dout, ...). When a D typemap is looked up, the following happens behind the scenes:

    + +

    First, the matching typemap is determined by the usual typemap lookup rules. Then, it is checked if the result has the nativepointer attribute set. If it is present, it means that its value should replace the typemap value if and only if the actual type the typemap is looked up for is a primitive type, a pointer to a primitive type (through an arbitrary level of indirections), or a function pointer with only primitive types in its signature.

    + +

    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 *).

    + + +

    21.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:

    + +

    The first key difference is that C++ supports free functions as operators (along with argument-dependent lookup), while D requires operators to be member functions of the class they are operating on. SWIG can only automatically generate wrapping code for member function operators; if you want to use operators defined as free functions in D, you need to handle them manually.

    + +

    Another set of differences between C++ and D concerns individual operators. For example, there are quite a few operators which are overloadable in C++, but not in D, for example && and ||, but also !, and prefix increment/decrement operators in D1 resp. their postfix pendants in D2.

    + +

    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.

    + + +

    21.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 D_VERSION variable, e.g. make check-d-test-suite D_VERSION=2.

    + +

    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.

    + + +

    21.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

    + + +

    There are a couple of features which are not implemented yet, but would be very useful and might be added in the near future:

    + +
      +
    • Static linking: Currently, the C wrapper code is compiled into a dynamic library, out of which the symbol addresses are looked up at runtime by the D part. If statically linking the different languages into one binary was supported, a tool-chain capable of performing IPO at link time could inline the wrapping code, effectively reducing the overhead for simple calls to zero.
    • +
    • C array handling: Many data structures in some C/C++ libraries contain array containing of a pointer to the first element and the element count. Currently, one must manually writing wrapper code to be able to access these from D. It should be possible to add a set of SWIG macros to semi-automatically generate conversion code.
    • +
    + +

    Some generated code might also be a bit rough around the edges, particularly in the following areas:

    + +
      +
    • Memory management: Although the currently generated wrapper code works fine with regard to the GC for the test-suite, there might be issues coming up in real-world multi-threaded usage.
    • +
    • D2 support: Originally, the module has been developed for the use with D1, D2/Phobos support has been added in later. The basic features should work equally well for both, but there could be issues concerning const-correctness etc.
    • +
    + + + + + diff --git a/Doc/Manual/Extending.html b/Doc/Manual/Extending.html index c554d9f05..059388717 100644 --- a/Doc/Manual/Extending.html +++ b/Doc/Manual/Extending.html @@ -6,7 +6,7 @@ -

    36 Extending SWIG to support new languages

    +

    38 Extending SWIG to support new languages

      @@ -75,7 +75,7 @@ -

      36.1 Introduction

      +

      38.1 Introduction

      @@ -91,7 +91,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.

      -

      36.2 Prerequisites

      +

      38.2 Prerequisites

      @@ -121,7 +121,7 @@ obvious, but almost all SWIG directives as well as the low-level generation of wrapper code are driven by C++ datatypes.

      -

      36.3 The Big Picture

      +

      38.3 The Big Picture

      @@ -158,7 +158,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.

      -

      36.4 Execution Model

      +

      38.4 Execution Model

      @@ -203,7 +203,7 @@ latter stage of compilation. The next few sections briefly describe some of these stages.

      -

      36.4.1 Preprocessing

      +

      38.4.1 Preprocessing

      @@ -284,7 +284,7 @@ been expanded as well as everything else that goes into the low-level construction of the wrapper code.

      -

      36.4.2 Parsing

      +

      38.4.2 Parsing

      @@ -385,7 +385,7 @@ returning a foo and taking types a and b as arguments).

      -

      36.4.3 Parse Trees

      +

      38.4.3 Parse Trees

      @@ -640,7 +640,7 @@ $ swig -c++ -python -debug-module 4 example.i

    -

    36.4.4 Attribute namespaces

    +

    38.4.4 Attribute namespaces

    @@ -659,7 +659,7 @@ that matches the name of the target language. For example, python:foo perl:foo.

    -

    36.4.5 Symbol Tables

    +

    38.4.5 Symbol Tables

    @@ -750,7 +750,7 @@ example.i:5. Previous declaration is foo_i(int )

    -

    36.4.6 The %feature directive

    +

    38.4.6 The %feature directive

    @@ -806,7 +806,7 @@ For example, the exception code above is simply stored without any modifications.

    -

    36.4.7 Code Generation

    +

    38.4.7 Code Generation

    @@ -928,7 +928,7 @@ public : The role of these functions is described shortly.

    -

    36.4.8 SWIG and XML

    +

    38.4.8 SWIG and XML

    @@ -941,7 +941,7 @@ internal data structures, it may be useful to keep XML in the back of your mind as a model.

    -

    36.5 Primitive Data Structures

    +

    38.5 Primitive Data Structures

    @@ -987,7 +987,7 @@ typedef Hash Typetab; -

    36.5.1 Strings

    +

    38.5.1 Strings

    @@ -1128,7 +1128,7 @@ Returns the number of replacements made (if any). -

    36.5.2 Hashes

    +

    38.5.2 Hashes

    @@ -1205,7 +1205,7 @@ Returns the list of hash table keys. -

    36.5.3 Lists

    +

    38.5.3 Lists

    @@ -1294,7 +1294,7 @@ If t is not a standard object, it is assumed to be a char * and is used to create a String object. -

    36.5.4 Common operations

    +

    38.5.4 Common operations

    The following operations are applicable to all datatypes. @@ -1349,7 +1349,7 @@ objects and report errors. Gets the line number associated with x. -

    36.5.5 Iterating over Lists and Hashes

    +

    38.5.5 Iterating over Lists and Hashes

    To iterate over the elements of a list or a hash table, the following functions are used: @@ -1394,7 +1394,7 @@ for (j = First(j); j.item; j= Next(j)) { -

    36.5.6 I/O

    +

    38.5.6 I/O

    Special I/O functions are used for all internal I/O. These operations @@ -1531,7 +1531,7 @@ Similarly, the preprocessor and parser all operate on string-files. -

    36.6 Navigating and manipulating parse trees

    +

    38.6 Navigating and manipulating parse trees

    Parse trees are built as collections of hash tables. Each node is a hash table in which @@ -1665,7 +1665,7 @@ Deletes a node from the parse tree. Deletion reconnects siblings and properly u the parent so that sibling nodes are unaffected. -

    36.7 Working with attributes

    +

    38.7 Working with attributes

    @@ -1782,7 +1782,7 @@ the attribute is optional. Swig_restore() must always be called after function. -

    36.8 Type system

    +

    38.8 Type system

    @@ -1791,7 +1791,7 @@ pointers, references, and pointers to members. A detailed discussion of type theory is impossible here. However, let's cover the highlights.

    -

    36.8.1 String encoding of types

    +

    38.8.1 String encoding of types

    @@ -1892,7 +1892,7 @@ make the final type, the two parts are just joined together using string concatenation.

    -

    36.8.2 Type construction

    +

    38.8.2 Type construction

    @@ -2061,7 +2061,7 @@ Returns the prefix of a type. For example, if ty is ty is unmodified. -

    36.8.3 Type tests

    +

    38.8.3 Type tests

    @@ -2148,7 +2148,7 @@ Checks if ty is a varargs type. Checks if ty is a templatized type. -

    36.8.4 Typedef and inheritance

    +

    38.8.4 Typedef and inheritance

    @@ -2250,7 +2250,7 @@ Fully reduces ty according to typedef rules. Resulting datatype will consist only of primitive typenames. -

    36.8.5 Lvalues

    +

    38.8.5 Lvalues

    @@ -2287,7 +2287,7 @@ Literal y; // type = 'Literal', ltype='p.char' -

    36.8.6 Output functions

    +

    38.8.6 Output functions

    @@ -2349,7 +2349,7 @@ SWIG, but is most commonly associated with type-descriptor objects that appear in wrappers (e.g., SWIGTYPE_p_double). -

    36.9 Parameters

    +

    38.9 Parameters

    @@ -2448,7 +2448,7 @@ included. Used to emit prototypes. Returns the number of required (non-optional) arguments in p. -

    36.10 Writing a Language Module

    +

    38.10 Writing a Language Module

    @@ -2463,7 +2463,7 @@ describes the creation of a minimal Python module. You should be able to extra this to other languages.

    -

    36.10.1 Execution model

    +

    38.10.1 Execution model

    @@ -2473,7 +2473,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.

    -

    36.10.2 Starting out

    +

    38.10.2 Starting out

    @@ -2581,7 +2581,7 @@ that activates your module. For example, swig -python foo.i. The messages from your new module should appear.

    -

    36.10.3 Command line options

    +

    38.10.3 Command line options

    @@ -2640,7 +2640,7 @@ to mark the option as valid. If you forget to do this, SWIG will terminate wit unrecognized command line option error.

    -

    36.10.4 Configuration and preprocessing

    +

    38.10.4 Configuration and preprocessing

    @@ -2689,7 +2689,7 @@ an implementation file python.cxx and a configuration file python.swg.

    -

    36.10.5 Entry point to code generation

    +

    38.10.5 Entry point to code generation

    @@ -2747,22 +2747,23 @@ int Python::top(Node *n) { -

    36.10.6 Module I/O and wrapper skeleton

    +

    38.10.6 Module I/O and wrapper skeleton

    -Within SWIG wrappers, there are four main sections. These are (in order) +Within SWIG wrappers, there are five main sections. These are (in order)

      -
    • runtime: This section has most of the common SWIG runtime code -
    • header: This section holds declarations and inclusions from the .i file -
    • wrapper: This section holds all the wrappering code +
    • begin: This section is a placeholder for users to put code at the beginning of the C/C++ wrapper file. +
    • runtime: This section has most of the common SWIG runtime code. +
    • header: This section holds declarations and inclusions from the .i file. +
    • wrapper: This section holds all the wrappering code.
    • init: This section holds the module initalisation function -(the entry point for the interpreter) +(the entry point for the interpreter).

    Different parts of the SWIG code will fill different sections, @@ -2895,7 +2896,7 @@ functionWrapper : void Shape_y_set(Shape *self,double y) -

    36.10.7 Low-level code generators

    +

    38.10.7 Low-level code generators

    @@ -2974,7 +2975,7 @@ There are a lot of issues to address.
     virtual int functionWrapper(Node *n) {
    -  /* get useful atributes */
    +  /* get useful attributes */
       String   *name   = Getattr(n,"sym:name");
       SwigType *type   = Getattr(n,"type");
       ParmList *parms  = Getattr(n,"parms");
    @@ -3049,7 +3050,7 @@ but without the typemaps, there is still work to do.
     

    -

    36.10.8 Configuration files

    +

    38.10.8 Configuration files

    @@ -3193,7 +3194,7 @@ politely displays the ignoring language message. -

    36.10.9 Runtime support

    +

    38.10.9 Runtime support

    @@ -3202,7 +3203,7 @@ Discuss the kinds of functions typically needed for SWIG runtime support (e.g. the SWIG files that implement those functions.

    -

    36.10.10 Standard library files

    +

    38.10.10 Standard library files

    @@ -3221,7 +3222,7 @@ The following are the minimum that are usually supported: Please copy these and modify for any new language.

    -

    36.10.11 User examples

    +

    38.10.11 User examples

    @@ -3250,7 +3251,7 @@ during this process, see the section on .

    -

    36.10.12 Test driven development and the test-suite

    +

    38.10.12 Test driven development and the test-suite

    @@ -3309,7 +3310,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.

    -

    36.10.12.1 Running the test-suite

    +

    38.10.12.1 Running the test-suite

    @@ -3477,7 +3478,25 @@ A debugger can also be invoked easily on an individual test, for example gdb: make ret_by_value.ctest RUNTOOL="gdb --args"

    -

    36.10.13 Documentation

    +

    +SWIG reads the SWIG_FEATURES environment variable to obtain options in addition to those passed on the command line. +This is particularly useful as the entire test-suite or a particular testcase can be run customized by using additional +arguments, for example the -O optimization flag can be added in, as shown below for the bash shell: +

    + +
    +env SWIG_FEATURES=-O make check-python-test-suite
    +
    + +

    +The syntax for setting environment variables varies from one shell to the next, but it also works as shown in the example below, where some typemap debugging is added in: +

    + +
    +make ret_by_value.ctest SWIG_FEATURES="-debug-tmsearch"
    +
    + +

    38.10.13 Documentation

    @@ -3509,7 +3528,7 @@ Some topics that you'll want to be sure to address include: if available. -

    36.10.14 Prerequisites for adding a new language module to the SWIG distribution

    +

    38.10.14 Prerequisites for adding a new language module to the SWIG distribution

    @@ -3517,7 +3536,7 @@ If you wish for a new language module to be distributed with SWIG, which we encourage for all popular languages, there are a few requirements. While we appreciate that getting all aspects of a new language working won't happen at the outset, there are a set of minimum requirements before -a module can be committed into the SVN repository for distribution with future +a module can be committed into the official Github repository for distribution with future versions of SWIG. The following are really a summary of this whole section with details being outlined earlier on.

    @@ -3559,14 +3578,14 @@ details being outlined earlier on.

    -Once accepted into SVN, development efforts should concentrate on +Once accepted into the official Git repository, development efforts should concentrate on getting the entire test-suite to work with plenty of runtime tests. Runtime tests should be for existing testcases and new test cases should be added should there be an area not already covered by the existing tests.

    -

    36.10.15 Coding style guidelines

    +

    38.10.15 Coding style guidelines

    @@ -3590,7 +3609,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.

    -

    36.11 Debugging Options

    +

    38.11 Debugging Options

    @@ -3609,13 +3628,15 @@ There are various command line options which can aid debugging a SWIG interface -debug-top <n> - Display entire parse tree at stages 1-4, <n> is a csv list of stages -debug-typedef - Display information about the types and typedefs in the interface -debug-typemap - Display information for debugging typemaps +-debug-tmsearch - Display typemap search debugging information +-debug-tmused - Display typemaps used debugging information

    The complete list of command line options for SWIG are available by running swig -help.

    -

    36.12 Guide to parse tree nodes

    +

    38.12 Guide to parse tree nodes

    @@ -4023,7 +4044,7 @@ extern "X" { ... } declaration. -

    36.13 Further Development Information

    +

    38.13 Further Development Information

    diff --git a/Doc/Manual/Go.html b/Doc/Manual/Go.html index 5e99a5156..7a55a4364 100644 --- a/Doc/Manual/Go.html +++ b/Doc/Manual/Go.html @@ -5,7 +5,7 @@ -

    20 SWIG and Go

    +

    22 SWIG and Go

    @@ -41,7 +43,7 @@ the Go programming language see golang.org.

    -

    20.1 Overview

    +

    22.1 Overview

    @@ -65,7 +67,7 @@ checking and runtime library are not used with Go. This should be borne in mind when reading the rest of the SWIG documentation.

    -

    20.2 Running SWIG with Go

    +

    22.2 Running SWIG with Go

    @@ -74,7 +76,7 @@ default SWIG will generate code for the gc compilers. To generate code for gccgo, you should also use the -gccgo option.

    -

    20.2.1 Additional Commandline Options

    +

    22.2.1 Additional Commandline Options

    @@ -91,10 +93,22 @@ 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. + + -gccgo Generate code for gccgo. The default is to generate code for - 6g/8g/6g. + 6g/8g/5g. @@ -103,6 +117,15 @@ swig -go -help package name is the SWIG module name. + +-soname %lt;name%gt; +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. + + -go-prefix <prefix> When generating code for gccgo, set the prefix to use. This @@ -118,7 +141,7 @@ swig -go -help -

    20.2.2 Go Output Files

    +

    22.2.2 Go Output Files

    When generating Go code, SWIG will generate the following @@ -163,7 +186,7 @@ A typical command sequence would look like this: % 6l main.6 -

    20.3 A tour of basic C/C++ wrapping

    +

    22.3 A tour of basic C/C++ wrapping

    @@ -173,7 +196,7 @@ modifications have to occur. This section briefly covers the essential aspects of this wrapping.

    -

    20.3.1 Go Package Name

    +

    22.3.1 Go Package Name

    @@ -183,7 +206,7 @@ directive. You may override this by using SWIG's -package command line option.

    -

    20.3.2 Go Names

    +

    22.3.2 Go Names

    @@ -215,7 +238,7 @@ followed by that name, and the destructor will be named Delete followed by that name.

    -

    20.3.3 Go Constants

    +

    22.3.3 Go Constants

    @@ -223,7 +246,7 @@ C/C++ constants created via #define or the %constant directive become Go constants, declared with a const declaration. -

    20.3.4 Go Enumerations

    +

    22.3.4 Go Enumerations

    @@ -233,7 +256,7 @@ usual). The values of the enumeration will become variables in Go; code should avoid modifying those variables.

    -

    20.3.5 Go Classes

    +

    22.3.5 Go Classes

    @@ -264,7 +287,7 @@ class.

    SWIG will represent static methods of C++ classes as ordinary Go -functions. SWIG will use names like ClassName_MethodName. +functions. SWIG will use names like ClassNameMethodName. SWIG will give static members getter and setter functions with names like GetClassName_VarName.

    @@ -280,7 +303,38 @@ to reinterpret_cast. This should only be used for very special cases, such as where C++ would use a dynamic_cast.

    -

    20.3.5.1 Go Class Inheritance

    +

    Note that C++ pointers to compound objects are represented in go as objects +themselves, not as go pointers. So, for example, if you wrap the following +function:

    +
    +
    +class MyClass {
    +  int MyMethod();
    +  static MyClass *MyFactoryFunction();
    +};
    +
    +
    +
    +

    You will get go code that looks like this:

    +
    +
    +type MyClass interface {
    +  Swigcptr() uintptr
    +  SwigIsMyClass()
    +  MyMethod() int
    +}
    +
    +MyClassMyFactoryFunction() MyClass {
    +  // swig magic here
    +}
    +
    +
    +

    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

    @@ -292,7 +346,7 @@ Doing the reverse will require an explicit type assertion, which will be checked dynamically.

    -

    20.3.6 Go Templates

    +

    22.3.6 Go Templates

    @@ -300,7 +354,7 @@ 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. -

    20.3.7 Go Director Classes

    +

    22.3.7 Go Director Classes

    @@ -343,7 +397,7 @@ 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++.

    -

    20.3.8 Default Go primitive type mappings

    +

    22.3.8 Default Go primitive type mappings

    @@ -450,5 +504,131 @@ that typemap, or add new values, to control how C/C++ types are mapped into Go types.

    +

    22.3.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 it where to +store the output value. In go, you supply a slice in the place of the output +argument.

    + +

    For example, suppose you were trying to wrap the modf() function in the +C math library which splits x into integral and fractional parts (and +returns the integer part in one of its parameters):

    +
    +
    +double modf(double x, double *ip);
    +
    +
    +

    You could wrap it with SWIG as follows:

    +
    +
    +%include <typemaps.i>
    +double modf(double x, double *OUTPUT);
    +
    +
    +

    or you can use the %apply directive:

    +
    +
    +%include <typemaps.i>
    +%apply double *OUTPUT { double *ip };
    +double modf(double x, double *ip);
    +
    +
    +

    In Go you would use it like this:

    +
    +
    +ptr := []float64{0.0}
    +fraction := modulename.Modf(5.0, ptr)
    +
    +
    +

    Since this is ugly, you may want to wrap the swig-generated API with +some additional functions written in go that +hide the ugly details.

    + +

    There are no char *OUTPUT typemaps. However you can +apply the signed char * typemaps instead:

    +
    +
    +%include <typemaps.i>
    +%apply signed char *OUTPUT {char *output};
    +void f(char *output);
    +
    +
    + +

    22.3.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), like this:

    +
    +
    +%include <typemaps.i>
    +// Change name of what swig generates to Wrapped_modf.  This function will
    +// have the following signature in go:
    +//   func Wrapped_modf(float64, []float64) float64
    +%rename(wrapped_modf) modf(double x, double *ip);
    +
    +%apply double *OUTPUT { double *ip };
    +double modf(double x, double *ip);
    +
    +%insert(go_wrapper) %{
    +
    +// The improved go interface to this function, which has two return values,
    +// in the more natural go idiom:
    +func Modf(x float64) (fracPart float64, intPart float64) {
    +  ip := []float64{0.0}
    +  fracPart = Wrapped_modf(x, ip)
    +  intPart = ip[0]
    +  return
    +}
    +
    +%}
    +
    +
    + +

    For classes, since swig generates an interface, you can add additional +methods by defining another interface that includes the swig-generated +interface. For example,

    +
    +
    +%rename(Wrapped_MyClass) MyClass;
    +%rename(Wrapped_GetAValue) MyClass::GetAValue(int *x);
    +%apply int *OUTPUT { int *x };
    +
    +class MyClass {
    + public:
    +  MyClass();
    +  int AFineMethod(const char *arg); // Swig's wrapping is fine for this one.
    +  bool GetAValue(int *x);
    +};
    +
    +%insert(go_wrapper) %{
    +
    +type MyClass interface {
    +  Wrapped_MyClass
    +  GetAValue() (int, bool)
    +}
    +
    +func (arg SwigcptrWrapped_MyClass) GetAValue() (int, bool) {
    +  ip := []int{0}
    +  ok := arg.Wrapped_GetAValue(ip)
    +  return ip[0], ok
    +}
    +
    +%}
    +
    +
    +

    Of course, if you have to rewrite most of the methods, instead of 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.

    diff --git a/Doc/Manual/Guile.html b/Doc/Manual/Guile.html index 75c3d3473..6f1300492 100644 --- a/Doc/Manual/Guile.html +++ b/Doc/Manual/Guile.html @@ -8,7 +8,7 @@ -

    21 SWIG and Guile

    +

    23 SWIG and Guile

      @@ -47,7 +47,7 @@

      This section details guile-specific support in SWIG. -

      21.1 Meaning of "Module"

      +

      23.1 Meaning of "Module"

      @@ -55,7 +55,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". -

      21.2 Using the SCM or GH Guile API

      +

      23.2 Using the SCM or GH Guile API

      The guile module can currently export wrapper files that use the guile GH interface or the @@ -103,7 +103,7 @@ for the specific API. Currently only the guile language module has created a ma but there is no reason other languages (like mzscheme or chicken) couldn't also use this. If that happens, there is A LOT less code duplication in the standard typemaps.

      -

      21.3 Linkage

      +

      23.3 Linkage

      @@ -111,7 +111,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. -

      21.3.1 Simple Linkage

      +

      23.3.1 Simple Linkage

      @@ -206,7 +206,7 @@ placed between the define-module form and the SWIG_init via a preprocessor define to avoid symbol clashes. For this case, however, passive linkage is available. -

      21.3.2 Passive Linkage

      +

      23.3.2 Passive Linkage

      Passive linkage is just like simple linkage, but it generates an @@ -216,7 +216,7 @@ package name (see below).

      You should use passive linkage rather than simple linkage when you are using multiple modules. -

      21.3.3 Native Guile Module Linkage

      +

      23.3.3 Native Guile Module Linkage

      SWIG can also generate wrapper code that does all the Guile module @@ -257,7 +257,7 @@ Newer Guile versions have a shorthand procedure for this:

    -

    21.3.4 Old Auto-Loading Guile Module Linkage

    +

    23.3.4 Old Auto-Loading Guile Module Linkage

    Guile used to support an autoloading facility for object-code @@ -283,7 +283,7 @@ option, SWIG generates an exported module initialization function with an appropriate name. -

    21.3.5 Hobbit4D Linkage

    +

    23.3.5 Hobbit4D Linkage

    @@ -308,7 +308,7 @@ my/lib/libfoo.so.X.Y.Z and friends. This scheme is still very experimental; the (hobbit4d link) conventions are not well understood.

    -

    21.4 Underscore Folding

    +

    23.4 Underscore Folding

    @@ -320,7 +320,7 @@ complained so far. %rename to specify the Guile name of the wrapped functions and variables (see CHANGES). -

    21.5 Typemaps

    +

    23.5 Typemaps

    @@ -412,7 +412,7 @@ constant will appear as a scheme variable. See Features and the %feature directive for info on how to apply the %feature.

    -

    21.6 Representation of pointers as smobs

    +

    23.6 Representation of pointers as smobs

    @@ -429,11 +429,11 @@ upper half of the CAR is read from this struct. To get the pointer represented by a smob, the wrapper code calls the function SWIG_ConvertPtr(), passing a pointer to a struct representing the expected pointer type. See also -The run-time type checker. +The run-time type checker. If the Scheme object passed was not a SWIG smob representing a compatible pointer, a wrong-type-arg exception is raised. -

    21.6.1 GH Smobs

    +

    23.6.1 GH Smobs

    @@ -462,7 +462,7 @@ that created them, so the first module we check will most likely be correct. Once we have a swig_type_info structure, we loop through the linked list of casts, using pointer comparisons.

    -

    21.6.2 SCM Smobs

    +

    23.6.2 SCM Smobs

    The SCM interface (using the "-scm" argument to swig) uses swigrun.swg. @@ -477,7 +477,7 @@ in the smob tag. If a generated GOOPS module has been loaded, smobs will be wra GOOPS class.

    -

    21.6.3 Garbage Collection

    +

    23.6.3 Garbage Collection

    Garbage collection is a feature of the new SCM interface, and it is automatically included @@ -491,7 +491,7 @@ is exactly like described in 21.7 Exception Handling +

    23.7 Exception Handling

    @@ -517,7 +517,7 @@ mapping: The default when not specified here is to use "swig-error". See Lib/exception.i for details. -

    21.8 Procedure documentation

    +

    23.8 Procedure documentation

    If invoked with the command-line option -procdoc @@ -553,7 +553,7 @@ like this: typemap argument doc. See Lib/guile/typemaps.i for details. -

    21.9 Procedures with setters

    +

    23.9 Procedures with setters

    For global variables, SWIG creates a single wrapper procedure @@ -581,7 +581,7 @@ struct members, the procedures (struct-member-get pointer) and (struct-member-set pointer value) are not generated. -

    21.10 GOOPS Proxy Classes

    +

    23.10 GOOPS Proxy Classes

    SWIG can also generate classes and generic functions for use with @@ -730,7 +730,7 @@ Notice that <Foo> is used before it is defined. The fix is to just put th %import "foo.h" before the %inline block.

    -

    21.10.1 Naming Issues

    +

    23.10.1 Naming Issues

    As you can see in the example above, there are potential naming conflicts. The default exported @@ -767,7 +767,7 @@ guile-modules. For example,

    (use-modules ((Test) #:renamer (symbol-prefix-proc 'goops:))) -

    21.10.2 Linking

    +

    23.10.2 Linking

    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 3bac9484e..a8d15a5c2 100644 --- a/Doc/Manual/Introduction.html +++ b/Doc/Manual/Introduction.html @@ -195,9 +195,9 @@ extern int my_mod(int n, int m);

    The interface file contains ANSI C function prototypes and variable declarations. The %module directive defines the name of the -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. +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

    @@ -372,9 +372,9 @@ Microsoft Visual Studio.

    If you are using the GNU Autotools -(Autoconf/ -Automake/ -Libtool) +(Autoconf/ +Automake/ +Libtool) to configure SWIG use in your project, the SWIG Autoconf macros can be used. The primary macro is ax_pkg_swig, see http://www.gnu.org/software/autoconf-archive/ax_pkg_swig.html#ax_pkg_swig. diff --git a/Doc/Manual/Java.html b/Doc/Manual/Java.html index f572ffa32..8245d46eb 100644 --- a/Doc/Manual/Java.html +++ b/Doc/Manual/Java.html @@ -5,7 +5,7 @@ -

    22 SWIG and Java

    +

    24 SWIG and Java

  • Accessing protected members
  • Common customization features @@ -101,6 +102,7 @@
  • Simple pointers
  • Wrapping C arrays with Java arrays
  • Unbounded C Arrays +
  • Binary data vs Strings
  • Overriding new and delete to allocate from Java heap
  • Java typemaps @@ -141,7 +143,7 @@
  • Performance concerns and hints
  • Debugging -
  • Examples +
  • Java Examples @@ -154,7 +156,7 @@ It covers most SWIG features, but certain low-level details are covered in less

    -

    22.1 Overview

    +

    24.1 Overview

    @@ -166,7 +168,7 @@ SWIG wraps C/C++ code using Java proxy classes and is very useful if you want to If only one or two JNI functions are needed then using SWIG may be overkill. SWIG enables a Java program to easily call into C/C++ code from Java. Historically, SWIG was not able to generate any code to call into Java code from C++. -However, SWIG now supports full cross language polymorphism and code is generated to call up from C++ to Java when wrapping C++ virtual methods. +However, SWIG now supports full cross language polymorphism and code is generated to call up from C++ to Java when wrapping C++ virtual methods via the director feature.

    @@ -189,7 +191,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.

    -

    22.2 Preliminaries

    +

    24.2 Preliminaries

    @@ -205,7 +207,11 @@ Run make -k check from the SWIG root directory after installing SWIG on 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.

    -

    22.2.1 Running SWIG

    +

    +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

    @@ -264,7 +270,7 @@ The following sections have further practical examples and details on how you mi compiling and using the generated files.

    -

    22.2.2 Additional Commandline Options

    +

    24.2.2 Additional Commandline Options

    @@ -301,7 +307,7 @@ swig -java -help Their use will become clearer by the time you have finished reading this section on SWIG and Java.

    -

    22.2.3 Getting the right header files

    +

    24.2.3 Getting the right header files

    @@ -316,17 +322,18 @@ They are usually in directories like this:

    The exact location may vary on your machine, but the above locations are typical.

    -

    22.2.4 Compiling a dynamic module

    +

    24.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. -To build a shared library file, you need to compile your module in a manner similar to the following (shown for Solaris):

    +Assuming you have code you need to link to in a file called example.c, in order to build a shared library file, you need to compile your module in a manner similar to the following (shown for Solaris):

     $ swig -java example.i
     $ gcc -c example_wrap.c  -I/usr/java/include -I/usr/java/include/solaris
    -$ ld -G example_wrap.o  -o libexample.so
    +$ gcc -c example.c
    +$ ld -G example_wrap.o example.o -o libexample.so
     

    @@ -352,7 +359,7 @@ 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.

    -

    22.2.5 Using your module

    +

    24.2.5 Using your module

    @@ -363,7 +370,7 @@ To load your shared native library module in Java, simply use Java's System. public class runme { static { -  System.loadLibrary("example"); + System.loadLibrary("example"); } public static void main(String argv[]) { @@ -387,7 +394,7 @@ $ If it doesn't work have a look at the following section which discusses problems loading the shared library.

    -

    22.2.6 Dynamic linking problems

    +

    24.2.6 Dynamic linking problems

    @@ -474,7 +481,7 @@ The following section also contains some C++ specific linking problems and solut

    -

    22.2.7 Compilation problems and compiling with C++

    +

    24.2.7 Compilation problems and compiling with C++

    @@ -527,7 +534,7 @@ Finally make sure the version of JDK header files matches the version of Java th

    -

    22.2.8 Building on Windows

    +

    24.2.8 Building on Windows

    @@ -536,7 +543,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.

    -

    22.2.8.1 Running SWIG from Visual Studio

    +

    24.2.8.1 Running SWIG from Visual Studio

    @@ -575,7 +582,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.

    -

    22.2.8.2 Using NMAKE

    +

    24.2.8.2 Using NMAKE

    @@ -634,7 +641,7 @@ Of course you may want to make changes for it to work for C++ by adding in the -

    -

    22.3 A tour of basic C/C++ wrapping

    +

    24.3 A tour of basic C/C++ wrapping

    @@ -644,7 +651,7 @@ variables are wrapped with JavaBean type getters and setters and so forth. This section briefly covers the essential aspects of this wrapping.

    -

    22.3.1 Modules, packages and generated Java classes

    +

    24.3.1 Modules, packages and generated Java classes

    @@ -680,7 +687,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.

    -

    22.3.2 Functions

    +

    24.3.2 Functions

    @@ -714,7 +721,7 @@ System.out.println(example.fact(4)); -

    22.3.3 Global variables

    +

    24.3.3 Global variables

    @@ -801,7 +808,7 @@ extern char *path; // Read-only (due to %immutable) -

    22.3.4 Constants

    +

    24.3.4 Constants

    @@ -941,7 +948,7 @@ Or if you decide this practice isn't so bad and your own class implements ex

    -

    22.3.5 Enumerations

    +

    24.3.5 Enumerations

    @@ -955,7 +962,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.

    -

    22.3.5.1 Anonymous enums

    +

    24.3.5.1 Anonymous enums

    @@ -1018,7 +1025,7 @@ As in the case of constants, you can access them through either the module class

    -

    22.3.5.2 Typesafe enums

    +

    24.3.5.2 Typesafe enums

    @@ -1112,7 +1119,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.

    -

    22.3.5.3 Proper Java enums

    +

    24.3.5.3 Proper Java enums

    @@ -1165,7 +1172,7 @@ The additional support methods need not be generated if none of the enum items h Simpler Java enums for enums without initializers section.

    -

    22.3.5.4 Type unsafe enums

    +

    24.3.5.4 Type unsafe enums

    @@ -1213,7 +1220,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.

    -

    22.3.5.5 Simple enums

    +

    24.3.5.5 Simple enums

    @@ -1232,7 +1239,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.

    -

    22.3.6 Pointers

    +

    24.3.6 Pointers

    @@ -1320,7 +1327,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.

    -

    22.3.7 Structures

    +

    24.3.7 Structures

    @@ -1488,7 +1495,7 @@ x.setA(3); // Modify x.a - this is the same as b.f.a -

    22.3.8 C++ classes

    +

    24.3.8 C++ classes

    @@ -1551,7 +1558,7 @@ int bar = Spam.getBar(); -

    22.3.9 C++ inheritance

    +

    24.3.9 C++ inheritance

    @@ -1612,7 +1619,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.

    -

    22.3.10 Pointers, references, arrays and pass by value

    +

    24.3.10 Pointers, references, arrays and pass by value

    @@ -1667,7 +1674,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).

    -

    22.3.10.1 Null pointers

    +

    24.3.10.1 Null pointers

    @@ -1691,7 +1698,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.

    -

    22.3.11 C++ overloaded functions

    +

    24.3.11 C++ overloaded functions

    @@ -1806,7 +1813,7 @@ void spam(unsigned short); // Ignored -

    22.3.12 C++ default arguments

    +

    24.3.12 C++ default arguments

    @@ -1849,7 +1856,7 @@ Further details on default arguments and how to restore this approach are given

    -

    22.3.13 C++ namespaces

    +

    24.3.13 C++ namespaces

    @@ -1916,18 +1923,30 @@ The default behaviour described above can be improved via the

    -example.i:16: Error: The nspace feature used on 'MyWorld::Material::Color' is not supported unless a package is specified
    -with -package - Java does not support types declared in a named package accessing types declared in an unnamed package.
    +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.
     
    -

    22.3.14 C++ templates

    +

    +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

    @@ -1976,7 +1995,7 @@ Obviously, there is more to template wrapping than shown in this example. More details can be found in the SWIG and C++ chapter.

    -

    22.3.15 C++ Smart Pointers

    +

    24.3.15 C++ Smart Pointers

    @@ -2060,7 +2079,7 @@ Foo f = p.__deref__(); // Returns underlying Foo * -

    22.4 Further details on the generated Java classes

    +

    24.4 Further details on the generated Java classes

    @@ -2075,7 +2094,7 @@ Finally enum classes are covered. First, the crucial intermediary JNI class is considered.

    -

    22.4.1 The intermediary JNI class

    +

    24.4.1 The intermediary JNI class

    @@ -2195,7 +2214,7 @@ If name is the same as modulename then the module class name g from modulename to modulenameModule.

    -

    22.4.1.1 The intermediary JNI class pragmas

    +

    24.4.1.1 The intermediary JNI class pragmas

    @@ -2211,6 +2230,9 @@ The intermediary JNI class can be tailored through the use of pragmas, but is no 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 @@ -2274,7 +2296,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.

    -

    22.4.2 The Java module class

    +

    24.4.2 The Java module class

    @@ -2305,7 +2327,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.

    -

    22.4.2.1 The Java module class pragmas

    +

    24.4.2.1 The Java module class pragmas

    @@ -2356,7 +2378,7 @@ See The intermediary JNI class pragmas secti

    -

    22.4.3 Java proxy classes

    +

    24.4.3 Java proxy classes

    @@ -2376,7 +2398,7 @@ public class Foo { swigCPtr = cPtr; } - public static long getCPtr(Foo obj) { + protected static long getCPtr(Foo obj) { return (obj == null) ? 0 : obj.swigCPtr; } @@ -2432,7 +2454,7 @@ int y = f.spam(5, new Foo()); -

    22.4.3.1 Memory management

    +

    24.4.3.1 Memory management

    @@ -2594,7 +2616,7 @@ and

    -

    22.4.3.2 Inheritance

    +

    24.4.3.2 Inheritance

    @@ -2627,7 +2649,7 @@ public class Base { swigCPtr = cPtr; } - public static long getCPtr(Base obj) { + protected static long getCPtr(Base obj) { return (obj == null) ? 0 : obj.swigCPtr; } @@ -2667,7 +2689,7 @@ public class Derived extends Base { swigCPtr = cPtr; } - public static long getCPtr(Derived obj) { + protected static long getCPtr(Derived obj) { return (obj == null) ? 0 : obj.swigCPtr; } @@ -2710,7 +2732,7 @@ However, true cross language polymorphism can be achieved using the 22.4.3.3 Proxy classes and garbage collection +

    24.4.3.3 Proxy classes and garbage collection

    @@ -2743,7 +2765,7 @@ Call the System.runFinalizersOnExit(true) or Runtime.getRuntime().r 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 Sun's Java web site and search for runFinalizersOnExit. +Have a look at Java web site and search for runFinalizersOnExit.

  • @@ -2793,7 +2815,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.

    -

    22.4.3.4 The premature garbage collection prevention parameter for proxy class marshalling

    +

    24.4.3.4 The premature garbage collection prevention parameter for proxy class marshalling

    @@ -2915,7 +2937,7 @@ For example: Compatibility note: The generation of this additional parameter did not occur in versions prior to SWIG-1.3.30.

    -

    22.4.3.5 Single threaded applications and thread safety

    +

    24.4.3.5 Single threaded applications and thread safety

    @@ -2946,7 +2968,7 @@ public class Test { swigCPtr = cPtr; } - public static long getCPtr(Test obj) { + protected static long getCPtr(Test obj) { return (obj == null) ? 0 : obj.swigCPtr; } @@ -3003,7 +3025,7 @@ for (int i=0; i<100000; i++) { -

    22.4.4 Type wrapper classes

    +

    24.4.4 Type wrapper classes

    @@ -3090,7 +3112,7 @@ public static void spam(SWIGTYPE_p_int x, SWIGTYPE_p_int y, int z) { ... } -

    22.4.5 Enum classes

    +

    24.4.5 Enum classes

    @@ -3099,7 +3121,7 @@ The Enumerations section discussed these but om The following sub-sections detail the various types of enum classes that can be generated.

    -

    22.4.5.1 Typesafe enum classes

    +

    24.4.5.1 Typesafe enum classes

    @@ -3183,7 +3205,7 @@ The swigValue method is used for marshalling in the other direction. The toString method is overridden so that the enum name is available.

    -

    22.4.5.2 Proper Java enum classes

    +

    24.4.5.2 Proper Java enum classes

    @@ -3261,7 +3283,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.

    -

    22.4.5.3 Type unsafe enum classes

    +

    24.4.5.3 Type unsafe enum classes

    @@ -3292,7 +3314,7 @@ public final class Beverage { -

    22.5 Cross language polymorphism using directors

    +

    24.5 Cross language polymorphism using directors

    @@ -3314,7 +3336,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.

    -

    22.5.1 Enabling directors

    +

    24.5.1 Enabling directors

    @@ -3342,9 +3364,6 @@ The %feature directive can be applied globally, to specific classes, and to spec // generate directors for all virtual methods in class Foo %feature("director") Foo; - -// generate a director for just Foo::bar() -%feature("director") Foo::bar; @@ -3385,7 +3404,7 @@ public: -

    22.5.2 Director classes

    +

    24.5.2 Director classes

    @@ -3412,7 +3431,7 @@ If the correct implementation is in Java, the Java API is used to call the metho

    -

    22.5.3 Overhead and code bloat

    +

    24.5.3 Overhead and code bloat

    @@ -3430,7 +3449,7 @@ This situation can be optimized by selectively enabling director methods (using

    -

    22.5.4 Simple directors example

    +

    24.5.4 Simple directors example

    @@ -3458,7 +3477,7 @@ void callup(DirectorBase *director) {

    The following DirectorDerived Java class is derived from the Java proxy class DirectorBase and overrides upcall_method(). When C++ code invokes upcall_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 intermediate class marshal and convert arguments between C++ and Java when needed. +Naturally, the SWIG generated C++ code and the generated Java intermediary class marshal and convert arguments between C++ and Java when needed.

    @@ -3495,7 +3514,7 @@ DirectorDerived::upcall_method() invoked.
    -

    22.5.5 Director threading issues

    +

    24.5.5 Director threading issues

    @@ -3515,7 +3534,29 @@ Macros can be defined on the commandline when compiling your C++ code, or altern -

    22.6 Accessing protected members

    +

    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 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

    @@ -3611,7 +3652,7 @@ class MyProtectedBase extends ProtectedBase -

    22.7 Common customization features

    +

    24.7 Common customization features

    @@ -3623,7 +3664,7 @@ be awkward. This section describes some common SWIG features that are used to improve the interface to existing C/C++ code.

    -

    22.7.1 C/C++ helper functions

    +

    24.7.1 C/C++ helper functions

    @@ -3689,7 +3730,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.

    -

    22.7.2 Class extension with %extend

    +

    24.7.2 Class extension with %extend

    @@ -3752,7 +3793,7 @@ Vector(2,3,4) in any way---the extensions only show up in the Java interface.

    -

    22.7.3 Exception handling with %exception and %javaexception

    +

    24.7.3 Exception handling with %exception and %javaexception

    @@ -3911,7 +3952,7 @@ to raise exceptions. See the SWIG Library ch The typemap example Handling C++ exception specifications as Java exceptions provides further exception handling capabilities.

    -

    22.7.4 Method access with %javamethodmodifiers

    +

    24.7.4 Method access with %javamethodmodifiers

    @@ -3937,7 +3978,7 @@ protected static void protect_me() { -

    22.8 Tips and techniques

    +

    24.8 Tips and techniques

    @@ -3947,7 +3988,7 @@ strings and arrays. This chapter discusses the common techniques for solving these problems.

    -

    22.8.1 Input and output parameters using primitive pointers and references

    +

    24.8.1 Input and output parameters using primitive pointers and references

    @@ -4121,7 +4162,7 @@ void foo(Bar *OUTPUT); will not have the intended effect since typemaps.i does not define an OUTPUT rule for Bar.

    -

    22.8.2 Simple pointers

    +

    24.8.2 Simple pointers

    @@ -4187,7 +4228,7 @@ System.out.println("3 + 4 = " + result); See the SWIG Library chapter for further details.

    -

    22.8.3 Wrapping C arrays with Java arrays

    +

    24.8.3 Wrapping C arrays with Java arrays

    @@ -4254,7 +4295,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.

    -

    22.8.4 Unbounded C Arrays

    +

    24.8.4 Unbounded C Arrays

    @@ -4399,7 +4440,51 @@ well suited for applications in which you need to create buffers, package binary data, etc.

    -

    22.8.5 Overriding new and delete to allocate from Java heap

    +

    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. +

    + + +
    +
    +%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");
    +}
    +%}
    +
    +
    + +

    +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: +

    + +
    +
    +byte[] data = "hi\0jk".getBytes();
    +example.binaryChar1(data);     
    +
    +
    + +

    +resulting in the output +

    + +
    +$ java runme
    +len: 5 data: 68 69 0 6a 6b
    +
    + + +

    24.8.6 Overriding new and delete to allocate from Java heap

    @@ -4516,7 +4601,7 @@ model and use these functions in place of malloc and free in your own code.

    -

    22.9 Java typemaps

    +

    24.9 Java typemaps

    @@ -4537,7 +4622,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. -

    22.9.1 Default primitive type mappings

    +

    24.9.1 Default primitive type mappings

    @@ -4689,7 +4774,7 @@ However, the mappings allow the full range of values for each C type from Java.

    -

    22.9.2 Default typemaps for non-primitive types

    +

    24.9.2 Default typemaps for non-primitive types

    @@ -4704,7 +4789,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.

    -

    22.9.3 Sixty four bit JVMs

    +

    24.9.3 Sixty four bit JVMs

    @@ -4717,7 +4802,7 @@ Unfortunately it won't of course hold true for JNI code.

    -

    22.9.4 What is a typemap?

    +

    24.9.4 What is a typemap?

    @@ -4840,7 +4925,7 @@ int c = example.count('e',"Hello World"); -

    22.9.5 Typemaps for mapping C/C++ types to Java types

    +

    24.9.5 Typemaps for mapping C/C++ types to Java types

    @@ -5100,7 +5185,7 @@ These are listed below: -

    22.9.6 Java typemap attributes

    +

    24.9.6 Java typemap attributes

    @@ -5146,7 +5231,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.

    -

    22.9.7 Java special variables

    +

    24.9.7 Java special variables

    @@ -5297,7 +5382,7 @@ This special variable expands to the intermediary class name. Usually this is th unless the jniclassname attribute is specified in the %module directive.

    -

    22.9.8 Typemaps for both C and C++ compilation

    +

    24.9.8 Typemaps for both C and C++ compilation

    @@ -5334,7 +5419,7 @@ If you do not intend your code to be targeting both C and C++ then your typemaps

    -

    22.9.9 Java code typemaps

    +

    24.9.9 Java code typemaps

    @@ -5406,12 +5491,28 @@ import statements for Java class: empty default

    %typemap(javainterfaces)

    -interfaces (extends) for Java class: empty default +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. +

    + +
    +%typemap(javafinalize) SWIGTYPE %{
    +   protected void finalize() {
    +     swig_delete();  // renamed to prevent conflict with existing delete method
    +   }
    +]%
    +
    +

    @@ -5503,15 +5604,8 @@ The typemap code is the same that is in "java.swg", barring the last tw 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. -There is a macro in java.swg that implements this and the above can instead be implemented using:

    -
    -
    -SWIG_JAVABODY_METHODS(protected, protected, SWIGTYPE)
    -
    -
    -

    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:

    @@ -5521,7 +5615,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; - public $javaclassname(long cPtr, boolean bFutureUse) { + protected $javaclassname(long cPtr, boolean bFutureUse) { swigCPtr = cPtr; } @@ -5529,7 +5623,7 @@ For the typemap to be used in all type wrapper classes, all the different types swigCPtr = 0; } - public static long getCPtr($javaclassname obj) { + protected static long getCPtr($javaclassname obj) { return (obj == null) ? 0 : obj.swigCPtr; } %} @@ -5540,7 +5634,30 @@ For the typemap to be used in all type wrapper classes, all the different types Again this is the same that is in "java.swg", barring the method modifier for getCPtr.

    -

    22.9.10 Director specific typemaps

    +

    +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)
    +
    +
    + +

    24.9.10 Director specific typemaps

    @@ -5765,7 +5882,7 @@ The basic strategy here is to provide a default package typemap for the majority -

    22.10 Typemap Examples

    +

    24.10 Typemap Examples

    @@ -5775,7 +5892,7 @@ the SWIG library.

    -

    22.10.1 Simpler Java enums for enums without initializers

    +

    24.10.1 Simpler Java enums for enums without initializers

    @@ -5854,7 +5971,7 @@ This would be done by using the original versions of these typemaps in "enums.sw

    -

    22.10.2 Handling C++ exception specifications as Java exceptions

    +

    24.10.2 Handling C++ exception specifications as Java exceptions

    @@ -5979,7 +6096,7 @@ We could alternatively have used %rename to rename what() into

    -

    22.10.3 NaN Exception - exception handling for a particular type

    +

    24.10.3 NaN Exception - exception handling for a particular type

    @@ -6134,7 +6251,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.

    -

    22.10.4 Converting Java String arrays to char **

    +

    24.10.4 Converting Java String arrays to char **

    @@ -6234,7 +6351,7 @@ public class runme { static { try { -  System.loadLibrary("example"); + System.loadLibrary("example"); } catch (UnsatisfiedLinkError e) { System.err.println("Native code library failed to load. " + e); System.exit(1); @@ -6278,7 +6395,7 @@ Lastly the "jni", "jtype" and "jstype" typemaps are also required to specify what Java types to use.

    -

    22.10.5 Expanding a Java object to multiple arguments

    +

    24.10.5 Expanding a Java object to multiple arguments

    @@ -6360,7 +6477,7 @@ example.foo(new String[]{"red", "green", "blue", "white"}); -

    22.10.6 Using typemaps to return arguments

    +

    24.10.6 Using typemaps to return arguments

    @@ -6453,7 +6570,7 @@ public class runme { static { try { -  System.loadLibrary("example"); + System.loadLibrary("example"); } catch (UnsatisfiedLinkError e) { System.err.println("Native code library failed to load. " + e); System.exit(1); @@ -6478,7 +6595,7 @@ $ java runme 1 12.0 340.0 -

    22.10.7 Adding Java downcasts to polymorphic return types

    +

    24.10.7 Adding Java downcasts to polymorphic return types

    @@ -6684,7 +6801,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.

    -

    22.10.8 Adding an equals method to the Java classes

    +

    24.10.8 Adding an equals method to the Java classes

    @@ -6728,7 +6845,7 @@ System.out.println("foo1? " + foo1.equals(foo2)); -

    22.10.9 Void pointers and a common Java base class

    +

    24.10.9 Void pointers and a common Java base class

    @@ -6787,7 +6904,7 @@ This example contains some useful functionality which you may want in your code.

  • 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. -

    22.10.10 Struct pointer to pointer

    +

    24.10.10 Struct pointer to pointer

    @@ -6967,7 +7084,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.

    -

    22.10.11 Memory management when returning references to member variables

    +

    24.10.11 Memory management when returning references to member variables

    @@ -7090,7 +7207,7 @@ public class Bike { Note the addReference call.

    -

    22.10.12 Memory management for objects passed to the C++ layer

    +

    24.10.12 Memory management for objects passed to the C++ layer

    @@ -7206,7 +7323,7 @@ The 'javacode' typemap simply adds in the specified code into the Java proxy cla -

    22.10.13 Date marshalling using the javain typemap and associated attributes

    +

    24.10.13 Date marshalling using the javain typemap and associated attributes

    @@ -7383,7 +7500,7 @@ A few things to note: -

    22.11 Living with Java Directors

    +

    24.11 Living with Java Directors

    @@ -7564,10 +7681,10 @@ public abstract class UserVisibleFoo extends Foo {

  • -

    22.12 Odds and ends

    +

    24.12 Odds and ends

    -

    22.12.1 JavaDoc comments

    +

    24.12.1 JavaDoc comments

    @@ -7623,7 +7740,7 @@ public class Barmy { -

    22.12.2 Functional interface without proxy classes

    +

    24.12.2 Functional interface without proxy classes

    @@ -7684,7 +7801,7 @@ All destructors have to be called manually for example the delete_Foo(foo) -

    22.12.3 Using your own JNI functions

    +

    24.12.3 Using your own JNI functions

    @@ -7734,7 +7851,7 @@ This directive is only really useful if you want to mix your own hand crafted JN

    -

    22.12.4 Performance concerns and hints

    +

    24.12.4 Performance concerns and hints

    @@ -7755,7 +7872,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.

    -

    22.12.5 Debugging

    +

    24.12.5 Debugging

    @@ -7777,7 +7894,7 @@ The -verbose:jni and -verbose:gc are also useful options for monitoring code beh

    -

    22.13 Examples

    +

    24.13 Java Examples

    @@ -7792,4 +7909,3 @@ Many of these have runtime tests in the java subdirectory. - diff --git a/Doc/Manual/Library.html b/Doc/Manual/Library.html index 285192d5e..1ae3c77a3 100644 --- a/Doc/Manual/Library.html +++ b/Doc/Manual/Library.html @@ -66,18 +66,19 @@ Library files are included using the %include directive. When searching for files, directories are searched in the following order:

    -
      +
      1. The current directory
      2. Directories specified with the -I command line option
      3. ./swig_lib
      4. SWIG library install location as reported by swig -swiglib, for example /usr/local/share/swig/1.3.30
      5. On Windows, a directory Lib relative to the location of swig.exe is also searched. -
    +

    -Within each directory, 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. +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.

    @@ -682,8 +683,12 @@ pointer.

    Copies all of the string data in s into the memory pointed to by -ptr. The string may contain embedded NULL bytes. The length of -the string is implicitly determined in the underlying wrapper code. +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.

    @@ -824,20 +829,20 @@ If you have a function that expects binary data,

    -int parity(char *str, int len, int initial);
    +size_t parity(char *str, size_t len, size_t initial);
     

    -you can wrap the parameters (char *str, int len) as a single +you can wrap the parameters (char *str, size_t len) as a single argument using a typemap. Just do this:

    -%apply (char *STRING, int LENGTH) { (char *str, int len) };
    +%apply (char *STRING, size_t LENGTH) { (char *str, size_t len) };
     ...
    -int parity(char *str, int len, int initial);
    +size_t parity(char *str, size_t len, size_t initial);
     
    @@ -854,6 +859,7 @@ Now, in the target language, you can use binary string data like this:

    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).

    8.3.3 Using %newobject to release memory

    @@ -1801,19 +1807,6 @@ struct DerivedIntValue : IntValue { -

    -Note that if the %shared_ptr macro is omitted for any class in the inheritance hierarchy, it will -result in a C++ compiler error. -For example if the above %shared_ptr(DerivedIntValue) is omitted, the following is typical of the compiler error that will result: -

    - -
    -
    -example_wrap.cxx: In function 'void Java_exampleJNI_delete_1DerivedIntValue(JNIEnv*, _jclass*, jlong)':
    -example_wrap.cxx:3169: error: 'smartarg1' was not declared in this scope
    -
    -
    -

    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++:

    @@ -1826,6 +1819,61 @@ int val4 = example.extractValueSmart(div); +

    +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: +

    + +
    +
    +%include "boost_shared_ptr.i"
    +%shared_ptr(Parent);
    +
    +%inline %{
    +  #include <boost/shared_ptr.hpp>
    +  struct GrandParent {
    +    virtual ~GrandParent() {}
    +  };
    +
    +  struct Parent : GrandParent {
    +    virtual ~Parent() {}
    +  };
    +
    +  struct Child : Parent {
    +    virtual ~Child() {}
    +  };
    +%}
    +
    +
    + +

    +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: +

    + +
    +
    +%include "boost_shared_ptr.i"
    +%shared_ptr(GrandParent);
    +%shared_ptr(Parent);
    +%shared_ptr(Child);
    +
    +... as before ...
    +
    +
    + +Note: There is currently no support for %shared_ptr and the director feature. +

    8.5 Utility Libraries

    diff --git a/Doc/Manual/Lisp.html b/Doc/Manual/Lisp.html index b9b5b6c1e..01ff3a3ec 100644 --- a/Doc/Manual/Lisp.html +++ b/Doc/Manual/Lisp.html @@ -6,7 +6,7 @@ -

    23 SWIG and Common Lisp

    +

    25 SWIG and Common Lisp

      @@ -41,7 +41,7 @@ Lisp, Common Foreign Function Interface(CFFI), CLisp and UFFI foreign function interfaces.

      -

      23.1 Allegro Common Lisp

      +

      25.1 Allegro Common Lisp

      @@ -50,7 +50,7 @@ here

      -

      23.2 Common Foreign Function Interface(CFFI)

      +

      25.2 Common Foreign Function Interface(CFFI)

      @@ -77,7 +77,7 @@ swig -cffi -module module-name file-name files and the various things which you can do with them.

      -

      23.2.1 Additional Commandline Options

      +

      25.2.1 Additional Commandline Options

      @@ -118,7 +118,7 @@ swig -cffi -help -

      23.2.2 Generating CFFI bindings

      +

      25.2.2 Generating CFFI bindings

      As we mentioned earlier the ideal way to use SWIG is to use interface @@ -392,7 +392,7 @@ The feature intern_function ensures that all C names are
    -

    23.2.3 Generating CFFI bindings for C++ code

    +

    25.2.3 Generating CFFI bindings for C++ code

    This feature to SWIG (for CFFI) is very new and still far from @@ -568,7 +568,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. -

    23.2.4 Inserting user code into generated files

    +

    25.2.4 Inserting user code into generated files

    @@ -608,7 +608,7 @@ Note that the block %{ ... %} is effectively a shortcut for

    -

    23.3 CLISP

    +

    25.3 CLISP

    @@ -638,7 +638,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.

    -

    23.3.1 Additional Commandline Options

    +

    25.3.1 Additional Commandline Options

    @@ -671,7 +671,7 @@ and global variables will be created otherwise only definitions for
    -

    23.3.2 Details on CLISP bindings

    +

    25.3.2 Details on CLISP bindings

    @@ -795,7 +795,7 @@ struct bar { -

    23.4 UFFI

    +

    25.4 UFFI

    diff --git a/Doc/Manual/Lua.html b/Doc/Manual/Lua.html index c07fe66c8..1fd41f907 100644 --- a/Doc/Manual/Lua.html +++ b/Doc/Manual/Lua.html @@ -6,13 +6,14 @@ -

    24 SWIG and Lua

    +

    26 SWIG and Lua

    @@ -65,15 +67,20 @@

    -Lua is an extension programming language designed to support general procedural programming with data description facilities. It also offers good support for object-oriented programming, functional programming, and data-driven programming. Lua is intended to be used as a powerful, light-weight configuration language for any program that needs one. Lua is implemented as a library, written in clean C (that is, in the common subset of ANSI C and C++). Its also a really tiny language, less than 6000 lines of code, which compiles to <100 kilobytes of binary code. It can be found at http://www.lua.org +Lua is an extension programming language designed to support general procedural programming with data description facilities. It also offers good support for object-oriented programming, functional programming, and data-driven programming. Lua is intended to be used as a powerful, light-weight configuration language for any program that needs one. Lua is implemented as a library, written in clean C (that is, in the common subset of ANSI C and C++). It's also a really tiny language, less than 6000 lines of code, which compiles to <100 kilobytes of binary code. It can be found at http://www.lua.org

    -

    24.1 Preliminaries

    +

    +eLua stands for Embedded Lua (can be thought of as a flavor of Lua) and offers the full implementation of the Lua programming language to the embedded world, extending it with specific features for efficient and portable software embedded development. eLua runs on smaller devices like microcontrollers and provides the full features of the regular Lua desktop version. More information on eLua can be found here: http://www.eluaproject.net +

    + +

    26.1 Preliminaries

    -The current SWIG implementation is designed to work with Lua 5.0.x and Lua 5.1.x. It should work with later versions of Lua, but certainly not with Lua 4.0 due to substantial API changes. ((Currently SWIG generated code has only been tested on Windows with MingW, though given the nature of Lua, is should not have problems on other OS's)). 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). +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.

    -

    24.2 Running SWIG

    + +

    26.2 Running SWIG

    @@ -103,9 +110,58 @@ $ swig -c++ -lua 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 wrappered module will export one function "int luaopen_example(lua_State* L)" which must be called to register the module with the Lua interpreter. The name "luaopen_example" depends upon the name of the 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 "int luaopen_example(lua_State* L)" which must be called to register the module with the Lua interpreter. The name "luaopen_example" depends upon the name of the module.

    -

    24.2.1 Compiling and Linking and Interpreter

    +

    +To build an eLua module, run SWIG using -lua and add either -elua or -eluac. +

    +
    +$ swig -lua -elua example.i
    +
    +

    +or +

    +
    +$ 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. +

    + +

    26.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: +

    + +
    +swig -lua -help 
    +
    + + + + + + + + + + + + + + + + + + + + + +
    Lua specific options
    -eluaGenerates LTR compatible wrappers for smaller devices running elua.
    -eluacLTR compatible wrappers in "crass compress" mode for elua.
    -nomoduleglobalDo not register the module name as a global variable but return the module table from calls to require.
    + +

    26.2.2 Compiling and Linking and Interpreter

    @@ -129,7 +185,7 @@ int main(int argc,char* argv[]) } L=lua_open(); luaopen_base(L); // load basic libs (eg. print) - luaopen_example(L); // load the wrappered module + 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 @@ -151,12 +207,36 @@ $ gcc -I/usr/include/lua -c example_wrap.c -o example_wrap.o $ gcc -c example.c -o example.o $ gcc -I/usr/include/lua -L/usr/lib/lua min.o example_wrap.o example.o -o my_lua +

    +For eLua, the source must be built along with the wrappers generated by SWIG. Make sure the eLua source files platform_conf.h and auxmods.h are updated with the entries of your new module. Please note: "mod" is the module name. +

    +
    +/* Sample platform_conf.h */
    +#define LUA_PLATFORM_LIBS_ROM\
    +  _ROM( AUXLIB_PIO, luaopen_pio, pio_map )\
    +  _ROM( AUXLIB_TMR, luaopen_tmr, tmr_map )\
    +  _ROM( AUXLIB_MOD, luaopen_mod, mod_map )\
    +  ....
    +
    -

    24.2.2 Compiling a dynamic module

    +
    +/* Sample auxmods.h */
    +#define AUXLIB_PIO       "pio"
    +LUALIB_API int ( luaopen_pio )(lua_State *L );
    +
    +#define AUXLIB_MOD       "mod"
    +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

    -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 same wrapper can be used. The commands will be something like this: +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 same wrapper can be used. Assuming you have code you need to link to in a file called example.c, the commands will be something like this:

     $ swig -lua example.i -o example_wrap.c
    @@ -165,7 +245,7 @@ $ gcc -c example.c -o example.o
     $ gcc -shared -I/usr/include/lua -L/usr/lib/lua example_wrap.o example.o -o example.so
     

    -The wrappers produced by SWIG can be compiled and linked with Lua 5.1.x. The loading is extremely simple. +The wrappers produced by SWIG can be compiled and linked with Lua 5.1.x and later. The loading is extremely simple.

     require("example")
    @@ -176,7 +256,7 @@ For those using Lua 5.0.x, you will also need an interpreter with the loadlib fu
     
     my_init=loadlib("example.so","luaopen_example") -- for Unix/Linux
     --my_init=loadlib("example.dll","luaopen_example") -- for Windows
    -assert(my_init) -- name sure its not nil
    +assert(my_init) -- make sure it's not nil
     my_init()       -- call the init fn of the lib
     

    @@ -197,10 +277,10 @@ print(a,b,c)

    Note: for Lua 5.0:
    -The loadlib() function is in the global namespace, not in package. So its just loadlib(). +The loadlib() function is in the global namespace, not in a package. So it's just loadlib().

    -if 'a' is a function, this its all working fine, all you need to do is call it +if 'a' is a function, this is all working fine, all you need to do is call it

       a()
    @@ -209,7 +289,7 @@ if 'a' is a function, this its all working fine, all you need to do is call it
     to load your library which will add a table 'example' with all the functions added.
     

    -If it doesn't work, look at the error messages, in particular mesage 'b'
    +If it doesn't work, look at the error messages, in particular message 'b'
    The specified module could not be found.
    Means that is cannot find the module, check your the location and spelling of the module.
    The specified procedure could not be found.
    @@ -220,7 +300,7 @@ Is quite obvious (Go back and consult the Lua documents on how to enable loadlib -

    24.2.3 Using your module

    +

    26.2.4 Using your module

    @@ -238,19 +318,19 @@ $ ./my_lua >

    -

    24.3 A tour of basic C/C++ wrapping

    +

    26.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.

    -

    24.3.1 Modules

    +

    26.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.

    -

    24.3.2 Functions

    +

    26.3.2 Functions

    @@ -288,7 +368,7 @@ It is also possible to rename the module with an assignment. 24 -

    24.3.3 Global variables

    +

    26.3.3 Global variables

    @@ -314,7 +394,7 @@ SWIG will effectively generate two functions example.Foo_set() and 4 5

    -Its is therefore not possible to 'move' the global variable into the global namespace as it is with functions. It is however, possible to rename the module with an assignment, to make it more convenient. +It is therefore not possible to 'move' the global variable into the global namespace as it is with functions. It is however, possible to rename the module with an assignment, to make it more convenient.

     > e=example
    @@ -325,7 +405,7 @@ Its is therefore not possible to 'move' the global variable into the global name
     4
     

    -If a variable is marked with the %immutable directive then any attempts to set this variable will cause an Lua error. Given a global variable: +If a variable is marked with the %immutable directive then any attempts to set this variable will cause a Lua error. Given a global variable:

    %module example
    @@ -361,8 +441,22 @@ nil
     > print(example.PI)
     3.142
     
    +

    +If you have used the -eluac option for your eLua module, you will have to follow a different approach while manipulating global variables. (This is not applicable for wrappers generated with -elua) +

    +
    +> -- Applicable only with -eluac. (num is defined)
    +> print(example.num_get())
    +20
    +> example.num_set(50) -- new value added
    +> print(example.num_get())
    +50
    +
    +

    +In general, functions of the form "variable_get()" and "variable_set()" are automatically generated by SWIG for use with -eluac. +

    -

    24.3.4 Constants and enums

    +

    26.3.4 Constants and enums

    @@ -385,7 +479,18 @@ example.SUNDAY=0

    Constants are not guaranteed to remain constant in Lua. The name of the constant could be accidentally reassigned to refer to some other object. Unfortunately, there is no easy way for SWIG to generate code that prevents this. You will just have to be careful.

    -

    24.3.5 Pointers

    +

    +If you're using eLua and have used -elua or -eluac to generate your wrapper, macro constants and enums should be accessed through a rotable called "const". In eLua, macro constants and enums are guaranteed to remain constants since they are all contained within a rotable. A regular C constant is accessed from eLua just as if it were a regular global variable, just that the property of value immutability is demonstrated if an attempt at modifying a C constant is made. +

    +
    +> print(example.ICONST)
    +10
    +> print(example.const.SUNDAY)
    +0
    +> print(example.const.SCONST)
    +Hello World
    +
    +

    26.3.5 Pointers

    @@ -406,13 +511,13 @@ When wrapped, you will be able to use the functions in a natural way from Lua. F > example.fclose(f)

    -Unlike many scripting languages, Lua has had support for pointers to C/C++ object built in for a long time. They are called 'userdata'. Unlike many other SWIG versions which use some kind of encoded character string, all objects will be represented as a userdata. The SWIG-Lua bindings provides a special function swig_type(), which if given a userdata object will return the type of object pointed to as a string (assuming it was a SWIG wrappered object). +Unlike many scripting languages, Lua has had support for pointers to C/C++ object built in for a long time. They are called 'userdata'. Unlike many other SWIG versions which use some kind of encoded character string, all objects will be represented as a userdata. The SWIG-Lua bindings provides a special function swig_type(), which if given a userdata object will return the type of object pointed to as a string (assuming it was a SWIG wrapped object).

     > print(f)
     userdata: 003FDA80
     > print(swig_type(f))
    -FILE * -- its a FILE*
    +FILE * -- it's a FILE*
     

    Lua enforces the integrity of its userdata, so it is virtually impossible to corrupt the data. But as the user of the pointer, you are responsible for freeing it, or closing any resources associated with it (just as you would in a C program). This does not apply so strictly to classes & structs (see below). One final note: if a function returns a NULL pointer, this is not encoded as a userdata, but as a Lua nil. @@ -423,7 +528,7 @@ Lua enforces the integrity of its userdata, so it is virtually impossible to cor nil -

    24.3.6 Structures

    +

    26.3.6 Structures

    @@ -456,10 +561,10 @@ If you print out the value of p in the above example, you will see something lik userdata: 003FA320

    -Like the pointer in the previous section, this is held as a userdata. However, additional features have been added to make this more usable. SWIG effectivly creates some accessor/mutator functions to get and set the data. These functions will be added to the userdata's metatable. This provides the natural access to the member variables that were shown above (see end of the document for full details). +Like the pointer in the previous section, this is held as a userdata. However, additional features have been added to make this more usable. SWIG effectively creates some accessor/mutator functions to get and set the data. These functions will be added to the userdata's metatable. This provides the natural access to the member variables that were shown above (see end of the document for full details).

    -const members of a structure are read-only. Data members can also be forced to be read-only using the immutable directive. As with other immutable's, setting attempts will be cause an error. For example: +const members of a structure are read-only. Data members can also be forced to be read-only using the immutable directive. As with other immutables, setting attempts will be cause an error. For example:

    struct Foo {
        ...
    @@ -508,8 +613,26 @@ Because the pointer points inside the structure, you can modify the contents and
     > x = b.f
     > x.a = 3                 -- Modifies the same structure
     
    +

    +For eLua with the -eluac option, structure manipulation has to be performed with specific structure functions generated by SWIG. Let's say you have the following structure definition: +

    +
    struct data {
    +   int x, y;
    +   double z;
    +};
     
    -

    24.3.7 C++ classes

    +> --From eLua +> a = example.new_data() +> example.data_x_set(a, 10) +> example.data_y_set(a, 20) +> print(example.data_x_get(a), example.data_y_get(a)) +10 20 +
    +

    +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) +

    + +

    26.3.7 C++ classes

    @@ -541,7 +664,7 @@ Stout >

    -(Note: for calling methods of a class, you use class:method(args), not class.method(args), its an easy mistake to make. However for data attributes it is class.attribute) +(Note: for calling methods of a class, you use class:method(args), not class.method(args), it's an easy mistake to make. However for data attributes it is class.attribute)

    Class data members are accessed in the same manner as C structures. Static class members present a special problem for Lua, as Lua doesn't have support for such features. Therefore, SWIG generates wrappers that try to work around some of these issues. To illustrate, suppose you have a class like this: @@ -550,7 +673,6 @@ Class data members are accessed in the same manner as C structures. Static class public: static void foo(); static int bar; - };

    @@ -565,12 +687,12 @@ In Lua, the static members can be accessed as follows: It is not (currently) possible to access static members of an instance:

    -> s=example.Spam()      -- s is a Spam instance
    +> s=example.Spam()              -- s is a Spam instance
     > s.foo()                       -- Spam::foo() via an instance
                                     -- does NOT work
     
    -

    24.3.8 C++ inheritance

    +

    26.3.8 C++ inheritance

    @@ -595,7 +717,7 @@ then the function spam() accepts a Foo pointer or a pointer to any clas

    It is safe to use multiple inheritance with SWIG.

    -

    24.3.9 Pointers, references, values, and arrays

    +

    26.3.9 Pointers, references, values, and arrays

    @@ -626,7 +748,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.

    -

    24.3.10 C++ overloaded functions

    +

    26.3.10 C++ overloaded functions

    @@ -712,7 +834,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.

    -

    24.3.11 C++ operators

    +

    26.3.11 C++ operators

    @@ -824,7 +946,7 @@ It is also possible to overload the operator[], but currently this cann }; -

    24.3.12 Class extension with %extend

    +

    26.3.12 Class extension with %extend

    @@ -879,7 +1001,32 @@ 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).

    -

    24.3.13 C++ templates

    + +

    26.3.13 Using %newobject to release memory

    + + +

    If you have a function that allocates memory like this,

    +
    +
    char *foo() {
    +   char *result = (char *) malloc(...);
    +   ...
    +   return result;
    +}
    +
    +
    +

    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.

    +
    +
    %newobject foo;
    +...
    +char *foo();
    +
    +
    +

    This will release the allocated memory.

    + +

    26.3.14 C++ templates

    @@ -914,7 +1061,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.

    -

    24.3.14 C++ Smart Pointers

    +

    26.3.15 C++ Smart Pointers

    @@ -966,7 +1113,7 @@ If you ever need to access the underlying pointer returned by operator->( > f = p:__deref__() -- Returns underlying Foo * -

    24.3.15 C++ Exceptions

    +

    26.3.16 C++ Exceptions

    @@ -985,13 +1132,13 @@ SWIG will automatically convert this to a Lua error.

    -> message()
    +> message()
     I died.
     stack traceback:
             [C]: in function 'message'
             stdin:1: in main chunk
             [C]: ?
    ->
    +>
     

    @@ -1000,13 +1147,13 @@ Using xpcall will allow you to obtain additional debug information (such as a st

    -> function a() b() end -- function a() calls function b()
    -> function b() message() end -- function b() calls C++ function message(), which throws 
    -> ok,res=pcall(a)  -- call the function
    -> print(ok,res)
    +> function a() b() end -- function a() calls function b()
    +> function b() message() end -- function b() calls C++ function message(), which throws 
    +> ok,res=pcall(a)  -- call the function
    +> print(ok,res)
     false   I died.
    -> ok,res=xpcall(a,debug.traceback)  -- call the function
    -> print(ok,res)
    +> ok,res=xpcall(a,debug.traceback)  -- call the function
    +> print(ok,res)
     false   I died.
     stack traceback:
             [C]: in function 'message'
    @@ -1018,12 +1165,12 @@ stack traceback:
     

    -SWIG is able to throw numeric types, enums, chars, char*'s and std::string's without problem. It has also written typemaps for std::exception and its derived classes, which convert the exception into and error string.

    +SWIG is able to throw numeric types, enums, chars, char*'s and std::string's without problem. It has also written typemaps for std::exception and its derived classes, which convert the exception into an error string.

    -However its not so simple for to throw other types of objects. +However it's not so simple to throw other types of objects. Thrown objects are not valid outside the 'catch' block. Therefore they cannot be returned to the interpreter. -The obvious ways to overcome this would be to either return a copy of the object, or so convert the object to a string and +The obvious ways to overcome this would be to either return a copy of the object, or to convert the object to a string and return that. Though it seems obvious to perform the former, in some cases this is not possible, most notably when SWIG has no information about the object, or the object is not copyable/creatable.

    @@ -1037,17 +1184,17 @@ void throw_A() throw(A*) { }

    -SWIG will just convert it (poorly) to a string and use that as its error. (Yes its not that useful, but it always works). +SWIG will just convert it (poorly) to a string and use that as its error. (This is not that useful, but it always works).

    -> throw_A()
    +> throw_A()
     object exception:A *
     stack traceback:
             [C]: in function 'unknown'
             stdin:1: in main chunk
             [C]: ?
    ->
    +>
     

    To get a more useful behaviour out of SWIG you must either: provide a way to convert your exceptions into strings, or @@ -1064,8 +1211,8 @@ If you have your own class which you want output as a string you will need to ad %}

    -If you wish your exception to be returned to the interpreter, it must firstly be copyable. Then you must have and additional -%apply statement, to inform SWIG to return a copy of this object to the interpreter. For example: +If you wish your exception to be returned to the interpreter, it must firstly be copyable. Then you must have an additional +%apply statement, to tell SWIG to return a copy of this object to the interpreter. For example:

     %apply SWIGTYPE EXCEPTION_BY_VAL {Exc}; // tell SWIG to return Exc by value to interpreter
    @@ -1088,14 +1235,14 @@ void throw_exc() throw(Exc) {
     Then the following code can be used (note: we use pcall to catch the error so we can process the exception).
     

    -> ok,res=pcall(throw_exc)
    -> print(ok)
    +> ok,res=pcall(throw_exc)
    +> print(ok)
     false
    -> print(res)
    +> print(res)
     userdata: 0003D880
    -> print(res.code,res.msg)
    +> print(res.code,res.msg)
     42      Hosed
    ->
    +>
     

    @@ -1110,12 +1257,12 @@ add exception specification to functions or globally (respectively).

    -

    24.4 Typemaps

    +

    26.4 Typemaps

    -

    This section explains what typemaps are and the usage of them. The default wrappering 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 wrappering. This section will be explaining how to use typemaps to best effect

    +

    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

    -

    24.4.1 What is a typemap?

    +

    26.4.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 Lua to C, you might define a typemap like this:

    @@ -1143,7 +1290,7 @@ Received an integer : 6 720
    -

    24.4.2 Using typemaps

    +

    26.4.2 Using typemaps

    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.

    @@ -1196,7 +1343,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).

    -

    24.4.3 Typemaps and arrays

    +

    26.4.3 Typemaps and arrays

    Arrays present a challenge for SWIG, because like pointers SWIG does not know whether these are input or output values, nor @@ -1209,8 +1356,8 @@ extern void sort_double(double* arr, int len);

    There are basically two ways that SWIG can deal with this. The first way, uses the <carrays.i> library -to create an array in C/C++ then this can be filled within Lua and passed into the function. It works, but its a bit tedious. -More details can be found in the carrays.i documention.

    +to create an array in C/C++ then this can be filled within Lua and passed into the function. It works, but it's a bit tedious. +More details can be found in the carrays.i documentation.

    The second and more intuitive way, would be to pass a Lua table directly into the function, and have SWIG automatically convert between Lua-table and C-array. Within the <typemaps.i> file there are typemaps ready written to perform this task. To use them is again a matter of using %appy in the correct manner.

    @@ -1230,7 +1377,7 @@ extern void sort_int(int* arr, int len); // the function to wrap extern void sort_double(double* arr, int len); // the function to wrap -

    Once wrappered, the functions can both be called, though with different ease of use:

    +

    Once wrapped, the functions can both be called, though with different ease of use:

    require "example"
     ARRAY_SIZE=10
    @@ -1260,7 +1407,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.

    -

    24.4.4 Typemaps and pointer-pointer functions

    +

    26.4.4 Typemaps and pointer-pointer functions

    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:

    @@ -1279,10 +1426,10 @@ ok=Create_Math(&ptr); free(ptr); // dispose of iMath
    -

    SWIG has a ready written typemap to deal with such a kind of function in <typemaps.i>. It provides the correct wrappering as well as setting the flag to inform Lua that the object in question should be garbage collected. Therefore the code is simply:

    +

    SWIG has a ready written typemap to deal with such a kind of function in <typemaps.i>. It provides the correct wrapping as well as setting the flag to inform Lua that the object in question should be garbage collected. Therefore the code is simply:

    %include <typemaps.i>
    -%apply SWIGTYPE** OUTPUT{iMath **pptr }; // tell SWIG its an output
    +%apply SWIGTYPE** OUTPUT{iMath **pptr }; // tell SWIG it's an output
     
     struct iMath;    // some structure
     int Create_Math(iMath** pptr); // its creator (assume it mallocs)
    @@ -1290,20 +1437,20 @@ int Create_Math(iMath** pptr); // its creator (assume it mallocs)
     
     

    The usage is as follows:

    -
    ok,ptr=Create_Math() -- ptr is a iMath* which is returned with the int (ok)
    +
    ok,ptr=Create_Math() -- ptr is an iMath* which is returned with the int (ok)
     ptr=nil -- the iMath* will be GC'ed as normal
     
    -

    24.5 Writing typemaps

    +

    26.5 Writing 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 Lua C API as well as the material in the "Typemaps" chapter.

    -

    Before proceeding, it should be stressed that writing typemaps is rarely needed unless you want to change some aspect of the wrappering, or to achieve an effect which in not available with the default bindings.

    +

    Before proceeding, it should be stressed that writing typemaps is rarely needed unless you want to change some aspect of the wrapping, or to achieve an effect which in not available with the default bindings.

    -

    Before proceeding, you should read the previous section on using typemaps, as well as read the ready written 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 a idea to base your worn on).

    +

    Before 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).

    -

    24.5.1 Typemaps you can write

    +

    26.5.1 Typemaps you can write

    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.

    @@ -1316,7 +1463,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). -

    24.5.2 SWIG's Lua-C API

    +

    26.5.2 SWIG's Lua-C API

    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.

    @@ -1324,7 +1471,7 @@ ptr=nil -- the iMath* will be GC'ed as normal

    int SWIG_ConvertPtr(lua_State* L,int index,void** ptr,swig_type_info *type,int flags);

    -This is the standard function used for converting a Lua userdata to a void*. It takes the value at the given index in the Lua state and converts it to a userdata. It will then provide the neccesary type checks, confirming that the pointer is compatible with the type given in 'type'. Then finally setting '*ptr' to the pointer. +This is the standard function used for converting a Lua userdata to a void*. It takes the value at the given index in the Lua state and converts it to a userdata. It will then provide the necessary type checks, confirming that the pointer is compatible with the type given in 'type'. Then finally setting '*ptr' to the pointer. If flags is set to SWIG_POINTER_DISOWN, this is will clear any ownership flag set on the object.
    The returns a value which can be checked with the macro SWIG_IsOK()
    @@ -1345,7 +1492,7 @@ This function is a version of SWIG_ConvertPtr(), except that it will either work

    SWIG_fail

    -This macro, when called within the context of a SWIG wrappered function, will jump to the error handler code. This will call any cleanup code (freeing any temp variables) and then triggers a lua_error.
    +This macro, when called within the context of a SWIG wrapped function, will jump to the error handler code. This will call any cleanup code (freeing any temp variables) and then triggers a lua_error.
    A common use for this code is:
     if (!SWIG_IsOK(SWIG_ConvertPtr( .....)){
      lua_pushstring(L,"something bad happened");
    @@ -1355,7 +1502,7 @@ if (!SWIG_IsOK(SWIG_ConvertPtr( .....)){
     

    SWIG_fail_arg(char* func_name,int argnum,char* type)

    -This macro, when called within the context of a SWIG wrappered function, will display the error message and jump to the error handler code. The error message is of the form +This macro, when called within the context of a SWIG wrapped function, will display the error message and jump to the error handler code. The error message is of the form
     "Error in func_name (arg argnum), expected 'type' got 'whatever the type was'"
     
    @@ -1365,7 +1512,7 @@ This macro, when called within the context of a SWIG wrappered function, will di
    Similar to SWIG_fail_arg, except that it will display the swig_type_info information instead.
    -

    24.6 Customization of your Bindings

    +

    26.6 Customization of your Bindings

    @@ -1374,11 +1521,11 @@ This section covers adding of some small extra bits to your module to add the la -

    24.6.1 Writing your own custom wrappers

    +

    26.6.1 Writing your own custom wrappers

    -Sometimes, it may be neccesary to add your own special functions, which bypass the normal SWIG wrappering method, and just use the native Lua API calls. These 'native' functions allow direct adding of your own code into the module. This is performed with the %native directive as follows: +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 code into the module. This is performed with the %native directive as follows:

    %native(my_func) int native_function(lua_State*L);  // registers native_function() with SWIG
     ...
    @@ -1390,14 +1537,14 @@ 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 wrappering for this function, beyond adding it into the function table. How you write your code is entirely up to you. +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.

    -

    24.6.2 Adding additional Lua code

    +

    26.6.2 Adding additional Lua code

    -As well as adding additional C/C++ code, its also possible to add your own Lua code to the module as well. +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.

    @@ -1422,7 +1569,7 @@ module name added.

    Should there be an error in the Lua code, this will not stop loading of the module. -The default behaviour of SWIG is to print a error message to stderr and then continue. +The default behaviour of SWIG is to print an error message to stderr and then continue. It is possible to change this behaviour by using a #define SWIG_DOSTRING_FAIL(STR) to define a different behaviour should the code fail.

    @@ -1431,18 +1578,18 @@ 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.

    -

    24.7 Details on the Lua binding

    +

    26.7 Details on the Lua binding

    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 how this is achieved.

    - If you just want to use SWIG and don't care how it works, then stop reading here. This is going into the guts of the code and how it works. Its mainly for people who need to know whats going on within the code. + If you just want to use SWIG and don't care how it works, then 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.

    -

    24.7.1 Binding global data into the module.

    +

    26.7.1 Binding global data into the module.

    @@ -1502,14 +1649,14 @@ 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)'.

    -

    24.7.2 Userdata and Metatables

    +

    26.7.2 Userdata and Metatables

    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 pointer to the data, a pointer to the swig_type_info (an internal SWIG struct) and a flag which marks if the object is to be disposed of when the interpreter no longer needs it. The actual accessing of the object is done via the metatable attached to this userdata.

    -The metatable is a Lua 5.0 feature (which is also why SWIG cannot wrap Lua 4.0). Its a table which holds a list of functions, operators and attributes. This is what gives the userdata the feeling that it is a real object and not just a hunk of memory. +The metatable is a Lua 5.0 feature (which is also why SWIG cannot wrap Lua 4.0). It's a table which holds a list of functions, operators and attributes. This is what gives the userdata the feeling that it is a real object and not just a hunk of memory.

    Given a class @@ -1526,10 +1673,10 @@ public: };

    -SWIG will create a module excpp, with all the various function inside. However to allow the intuitive use of the userdata is also creates up a set of metatables. As seen in the above section on global variables, use of the metatables allows for wrappers to be used intuitively. To save effort, the code creates one metatable per class and stores it inside Lua's registry. Then when an new object is instantiated, the metatable is found in the registry and the userdata associated to the metatable. Currently derived classes make a complete copy of the base classes table and then add on their own additional function. +SWIG will create a module excpp, with all the various functions inside. However to allow the intuitive use of the userdata, SWIG also creates up a set of metatables. As seen in the above section on global variables, use of the metatables allows for wrappers to be used intuitively. To save effort, the code creates one metatable per class and stores it inside Lua's registry. Then when a new object is instantiated, the metatable is found in the registry and the userdata associated with the metatable. Currently, derived classes make a complete copy of the base class' table and then add on their own additional functions.

    -Some of the internals can be seen by looking at a classes metatable. +Some of the internals can be seen by looking at the metatable of a class:

     > p=excpp.Point()
    @@ -1546,7 +1693,7 @@ __index function: 003FB698
     .fn     table: 003FB528
     

    -The '.type' attribute is the name of the class. The '.get' and '.set' tables work in a similar manner to the modules, the main difference is the '.fn' table which also holds all the member functions. (The '__gc' function is the classes destructor function) +The '.type' attribute is the name of the class. The '.get' and '.set' tables work in a similar manner to the modules, the main difference is the '.fn' table which also holds all the member functions. (The '__gc' function is the class' destructor function)

    The Lua equivalent of the code for enabling functions looks a little like this @@ -1560,7 +1707,7 @@ function __index(obj,name) local f=g[name] -- looks for the get_attribute function -- calls it & returns the value if type(f)=="function" then return f() end - -- ok, so it not an attribute, maybe its a function + -- ok, so it not an attribute, maybe it's a function local fn=m['.fn'] -- gets the function table if not fn then return nil end local f=fn[name] -- looks for the function @@ -1577,22 +1724,22 @@ So when 'p:Print()' is called, the __index looks on the object metatable for a ' In theory, you can play with this usertable & add new features, but remember that it is a shared table between all instances of one class, and you could very easily corrupt the functions in all the instances.

    -Note: Both the opaque structures (like the FILE*) and normal wrappered classes/structs use the same 'swig_lua_userdata' structure. Though the opaque structures has do not have a metatable attached, or any information on how to dispose of them when the interpreter has finished with them. +Note: Both the opaque structures (like the FILE*) and normal wrapped classes/structs use the same 'swig_lua_userdata' structure. Though the opaque structures has do not have a metatable attached, or any information on how to dispose of them when the interpreter has finished with them.

    -Note: Operator overloads are basically done in the same way, by adding functions such as '__add' & '__call' to the classes 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. +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.

    -

    24.7.3 Memory management

    +

    26.7.3 Memory management

    -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 piece of userdata has no references to it, it is not instantly collected, but will be collected when Lua deems is necessary. (You can force collection by calling the Lua function collectgarbage()). Once the userdata is about to be free'ed, the interpreter will check the userdata for a metatable and for a function '__gc'. If this exists this is called. For all complete types (ie normal wrappered classes & structs) this should exist. The '__gc' function will check the 'swig_lua_userdata' to check for the 'own' field and if this is true (which is will be for all owned data's) it will then call the destructor on the pointer. +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 piece of userdata has no references to it, it is not instantly collected, but will be collected when Lua deems is necessary. (You can force collection by calling the Lua function collectgarbage()). Once the userdata is about to be free'ed, the interpreter will check the userdata for a metatable and for a function '__gc'. If this exists this is called. For all complete types (ie normal wrapped classes & structs) this should exist. The '__gc' function will check the 'swig_lua_userdata' to check for the 'own' field and if this is true (which is will be for all owned data) it will then call the destructor on the pointer.

    It is currently not recommended to edit this field or add some user code, to change the behaviour. Though for those who wish to try, here is where to look.

    -It is also currently not possible to change the ownership flag on the data (unlike most other scripting languages, Lua does not permit access to the data from within the interpreter) +It is also currently not possible to change the ownership flag on the data (unlike most other scripting languages, Lua does not permit access to the data from within the interpreter).

    diff --git a/Doc/Manual/Makefile b/Doc/Manual/Makefile index 69d361f07..42149ba3a 100644 --- a/Doc/Manual/Makefile +++ b/Doc/Manual/Makefile @@ -15,7 +15,7 @@ # Note the # and " are escaped HTMLDOC_OPTIONS = "--book --toclevels 4 --no-numbered --toctitle \"Table of Contents\" --title --titleimage swig16.png --linkcolor \#0000ff --linkstyle underline --size Universal --left 0.50in --right 0.50in --top 0.50in --bottom 0.50in --header .t. --footer h.1 --nup 1 --tocheader .t. --tocfooter ..i --portrait --color --no-pscommands --no-xrxcomments --compression=1 --jpeg=0 --fontsize 10.0 --fontspacing 1.2 --headingfont Helvetica --bodyfont Times --headfootsize 10.0 --headfootfont Helvetica --charset iso-8859-1 --links --no-embedfonts --pagemode outline --pagelayout single --firstpage c1 --pageeffect none --pageduration 10 --effectduration 1.0 --no-encryption --permissions all --owner-password \"\" --user-password \"\" --browserwidth 680" -.PHONY: maketoc check generate all clean validate test +.PHONY: maketoc check generate all maintainer-clean validate test all: maketoc check generate @@ -38,13 +38,13 @@ generate: swightml.book swigpdf.book htmldoc --batch swigpdf.book || true python fixstyle.py SWIGDocumentation.html -swigpdf.book: +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: +swightml.book: chapters Sections.html echo "#HTMLDOC 1.8.24" > swightml.book echo -t html -f SWIGDocumentation.html $(HTMLDOC_OPTIONS) >> swightml.book echo "Sections.html" >> swightml.book @@ -69,7 +69,10 @@ test: validate: all=`sed '/^#/d' chapters`; for a in $$all; do validate --emacs $$a; done; -# Link checking using linkchecker (can take a while - 30 mins) +# Link checking using linkchecker linkchecker: - linkchecker --anchors Contents.html + @echo ----------------------------------------------------------------------- + @echo Note linkchecker versions prior to 6.1 do not work properly wrt anchors + @echo ----------------------------------------------------------------------- + linkchecker --config=./linkchecker.config index.html diff --git a/Doc/Manual/Modula3.html b/Doc/Manual/Modula3.html index 71611e3c5..065313fa2 100644 --- a/Doc/Manual/Modula3.html +++ b/Doc/Manual/Modula3.html @@ -5,7 +5,7 @@ -

    25 SWIG and Modula-3

    +

    27 SWIG and Modula-3

      @@ -54,7 +54,7 @@ especially typemaps.

      -

      25.1 Overview

      +

      27.1 Overview

      @@ -84,7 +84,7 @@ FFTW -

      25.1.1 Motivation

      +

      27.1.1 Motivation

      @@ -131,10 +131,10 @@ functions), but it doesn't allow you to easily integrate a Module-3 module into a C/C++ project.

      -

      25.2 Conception

      +

      27.2 Conception

      -

      25.2.1 Interfaces to C libraries

      +

      27.2.1 Interfaces to C libraries

      @@ -142,7 +142,7 @@ 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 -modula3.swg +modula3.swg contain code that uses these features. Because of the built-in support there is no need for calling the SWIG kernel to generate wrappers written in C. @@ -283,7 +283,7 @@ and the principal type must be renamed (%typemap).

      -

      25.2.2 Interfaces to C++ libraries

      +

      27.2.2 Interfaces to C++ libraries

      @@ -384,24 +384,23 @@ There is no C++ library I wrote a SWIG interface for, so I'm not sure if this is possible or sensible, yet.

      -

      25.3 Preliminaries

      +

      27.3 Preliminaries

      -

      25.3.1 Compilers

      +

      27.3.1 Compilers

      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 library file -modula3.swg +but the modula3.swg library file may do so. For testing examples I use Critical Mass cm3.

      -

      25.3.2 Additional Commandline Options

      +

      27.3.2 Additional Commandline Options

      @@ -478,10 +477,10 @@ Instead generate templates for some basic typemaps. -

      25.4 Modula-3 typemaps

      +

      27.4 Modula-3 typemaps

      -

      25.4.1 Inputs and outputs

      +

      27.4.1 Inputs and outputs

      @@ -499,9 +498,7 @@ or for a return value. A further typemap may specify the direction that is used for certain parameters. I have chosen this separation -in order to be able to write general typemaps for the typemap library -modula3.swg -. +in order to be able to write general typemaps for the modula3.swg typemap library. In the library code the final usage of the type is not known. Using separate typemaps for each possible use allows appropriate definitions for each case. @@ -697,7 +694,7 @@ consist of the following parts: -

      25.4.2 Subranges, Enumerations, Sets

      +

      27.4.2 Subranges, Enumerations, Sets

      @@ -749,7 +746,7 @@ that I'd like to automate.

      -

      25.4.3 Objects

      +

      27.4.3 Objects

      @@ -762,7 +759,7 @@ is not really useful, yet.

      -

      25.4.4 Imports

      +

      27.4.4 Imports

      @@ -782,9 +779,7 @@ Unqualified import is not supported.

      It is cumbersome to add this typemap to each piece of Modula-3 code. It is especially useful when writing general typemaps -for the typemap library -modula3.swg -. +for the modula3.swg typemap library. For a monolithic module you might be better off if you add the imports directly:

      @@ -797,7 +792,7 @@ IMPORT M3toC;
    -

    25.4.5 Exceptions

    +

    27.4.5 Exceptions

    @@ -821,7 +816,7 @@ you should declare %typemap("m3wrapinconv:throws") blah * %{OSError.E%}.

    -

    25.4.6 Example

    +

    27.4.6 Example

    @@ -868,10 +863,10 @@ where almost everything is generated by a typemap:

    -

    25.5 More hints to the generator

    +

    27.5 More hints to the generator

    -

    25.5.1 Features

    +

    27.5.1 Features

    @@ -908,7 +903,7 @@ where almost everything is generated by a typemap:
    -

    25.5.2 Pragmas

    +

    27.5.2 Pragmas

    @@ -931,7 +926,7 @@ where almost everything is generated by a typemap:
    -

    25.6 Remarks

    +

    27.6 Remarks

      diff --git a/Doc/Manual/Modules.html b/Doc/Manual/Modules.html index 69cc58c30..70b0f1181 100644 --- a/Doc/Manual/Modules.html +++ b/Doc/Manual/Modules.html @@ -138,7 +138,8 @@ base class's methods. Typically you will get a warning when the module name is m

      -derived_module.i:8: Warning 401: Base class 'base' ignored - unknown module name for base. Either import 
      +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.
       
      diff --git a/Doc/Manual/Mzscheme.html b/Doc/Manual/Mzscheme.html index 4351e34a7..3b49a2974 100644 --- a/Doc/Manual/Mzscheme.html +++ b/Doc/Manual/Mzscheme.html @@ -2,17 +2,19 @@ -SWIG and MzScheme +SWIG and MzScheme/Racket -

      26 SWIG and MzScheme

      +

      28 SWIG and MzScheme/Racket

      @@ -20,9 +22,9 @@

      -This section contains information on SWIG's support of MzScheme. +This section contains information on SWIG's support of Racket, formally known as MzScheme. -

      26.1 Creating native MzScheme structures

      +

      28.1 Creating native structures

      @@ -63,8 +65,116 @@ Then in scheme, you can use regular struct access procedures like +

      28.2 Simple example

      + +

      -That's pretty much it. It works with nested structs as well. +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: +

      + +
      +
      +// example.h
      +int fact(int n);
      +
      +
      + +

      +C source code: +

      + +
      +
      +// File: example.c
      +#include "example.h"
      +
      +int fact(int n) {
      +  if (n < 0) { /* This should probably return an error, but this is simpler */
      +    return 0;
      +  }
      +  if (n == 0) {
      +    return 1;
      +  }
      +  else {
      +    /* testing for overflow would be a good idea here */
      +    return n * fact(n-1);
      +  }
      +}
      +
      +
      + +

      +SWIG interface file: +

      + +
      +
      +/* File: example.i */
      +%module example
      +
      +%{
      +#include "example.h"
      +%}
      +
      +int fact(int n);
      +
      +
      + +

      +The session below using the above files is on an OS X machine, but the points to be made are more general. On OS X, libtool is the tool which creates libraries, which are named .dylib, rather than .so on other unixes, or .dll on Windows. +

      + +
      +
      +% swig -mzscheme -declaremodule example.i
      +% gcc -c -m32 -o example.o example.c # force 32-bit object file (mzscheme is 32-bit only)
      +% libtool -dynamic -o libexample.dylib example.o # make it into a library
      +% ls # what've we got so far?
      +example.c example.o
      +example.h example_wrap.c
      +example.i libexample.dylib*
      +% mzc --cgc --cc example_wrap.c # compile the wrapping code
      +% LDFLAGS="-L. -lexample" mzc --ld example_wrap.dylib example_wrap.o # ...and link it
      +% mzscheme -e '(path->string (build-path "compiled" "native" (system-library-subpath)))'
      +"compiled/native/i386-macosx/3m"
      +% mkdir -p compiled/native/i386-macosx/3m # move the extension library to a magic place
      +% mv example_wrap.dylib compiled/native/i386-macosx/3m/example_ss.dylib
      +% mzscheme
      +Welcome to MzScheme v4.2.4 [3m], Copyright (c) 2004-2010 PLT Scheme Inc.
      +> (require "example.ss")
      +> (fact 5)
      +120
      +> ^D
      +% echo 'It works!'
      +
      +
      + + +

      +Some points of interest: +

      +
        +
      • This is on a 64-bit machine, so we have to include the -m32 option when building the object file +
      • If you want to declare a scheme module (and you probably do), it's important that you include the -declaremodule option to swig (if you miss this out, it'll appear to work, but fail later). +
      • Use mzc to compile and then link the wrapped code. You'll probably need to adjust the link flags to refer to the library you're wrapping (you can either do this with an LDFLAGS declaration, as here, or with multiple ++ldf options to mzc). +
      • Create the directory with path (build-path "compiled" "native" (system-library-subpath)) and move the freshly-generated .dylib to there, changing its name to module-name_ss.dylib. After that, you can REQUIRE the new module with (require "module-name.ss"). +
      • 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

      + + +

      +See the C API for more description of using the mechanism for adding extensions. The main documentation is here. +

      + +

      +Tip: mzc's --vv option is very useful for debugging the inevitable library problems you'll encounter.

      diff --git a/Doc/Manual/Ocaml.html b/Doc/Manual/Ocaml.html index 6cbfa5510..127be904d 100644 --- a/Doc/Manual/Ocaml.html +++ b/Doc/Manual/Ocaml.html @@ -6,7 +6,7 @@ -

      27 SWIG and Ocaml

      +

      29 SWIG and Ocaml

        @@ -80,7 +80,7 @@ If you're not familiar with the Objective Caml language, you can visit The Ocaml Website.

        -

        27.1 Preliminaries

        +

        29.1 Preliminaries

        @@ -93,13 +93,13 @@ examples and test-suite which come with SWIG. You can do this by running 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 + href="http://download.camlcity.org/download/">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.

        -

        27.1.1 Running SWIG

        +

        29.1.1 Running SWIG

        @@ -122,11 +122,11 @@ you will compile the file example_wrap.c with ocamlc or the resulting .ml and .mli files as well, and do the final link with -custom (not needed for native link).

        -

        27.1.2 Compiling the code

        +

        29.1.2 Compiling the code

        -The O'Caml 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 @@ -158,7 +158,7 @@ the user more freedom with respect to custom typing.

      -

      27.1.3 The camlp4 module

      +

      29.1.3 The camlp4 module

      @@ -234,7 +234,7 @@ let b = C_string (getenv "PATH") -

      27.1.4 Using your module

      +

      29.1.4 Using your module

      @@ -248,7 +248,7 @@ When linking any ocaml bytecode with your module, use the -custom option is not needed when you build native code.

      -

      27.1.5 Compilation problems and compiling with C++

      +

      29.1.5 Compilation problems and compiling with C++

      @@ -259,7 +259,7 @@ liberal with pointer types may not compile under the C++ compiler. Most code meant to be compiled as C++ will not have problems.

      -

      27.2 The low-level Ocaml/C interface

      +

      29.2 The low-level Ocaml/C interface

      @@ -360,7 +360,7 @@ is that you must append them to the return list with swig_result = caml_list_a signature for a function that uses value in this way.

      -

      27.2.1 The generated module

      +

      29.2.1 The generated module

      @@ -394,7 +394,7 @@ it describes the output SWIG will generate for class definitions. -

      27.2.2 Enums

      +

      29.2.2 Enums

      @@ -457,7 +457,7 @@ val x : Enum_test.c_obj = C_enum `a -

      27.2.2.1 Enum typing in Ocaml

      +

      29.2.2.1 Enum typing in Ocaml

      @@ -470,10 +470,10 @@ functions imported from different modules. You must convert values to master values using the swig_val function before sharing them with another module.

      -

      27.2.3 Arrays

      +

      29.2.3 Arrays

      -

      27.2.3.1 Simple types of bounded arrays

      +

      29.2.3.1 Simple types of bounded arrays

      @@ -494,7 +494,7 @@ arrays of simple types with known bounds in your code, but this only works for arrays whose bounds are completely specified.

      -

      27.2.3.2 Complex and unbounded arrays

      +

      29.2.3.2 Complex and unbounded arrays

      @@ -507,7 +507,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.

      -

      27.2.3.3 Using an object

      +

      29.2.3.3 Using an object

      @@ -521,7 +521,7 @@ Consider writing an object when the ending condition of your array is complex, such as using a required sentinel, etc.

      -

      27.2.3.4 Example typemap for a function taking float * and int

      +

      29.2.3.4 Example typemap for a function taking float * and int

      @@ -572,7 +572,7 @@ void printfloats( float *tab, int len ); -

      27.2.4 C++ Classes

      +

      29.2.4 C++ Classes

      @@ -615,7 +615,7 @@ the underlying pointer, so using create_[x]_from_ptr alters the returned value for the same object.

      -

      27.2.4.1 STL vector and string Example

      +

      29.2.4.1 STL vector and string Example

      @@ -695,7 +695,7 @@ baz # -

      27.2.4.2 C++ Class Example

      +

      29.2.4.2 C++ Class Example

      @@ -725,7 +725,7 @@ public: }; -

      27.2.4.3 Compiling the example

      +

      29.2.4.3 Compiling the example

      @@ -743,7 +743,7 @@ bash-2.05a$ ocamlmktop -custom swig.cmo -I `camlp4 -where` \
         -L$QTPATH/lib -cclib -lqt
       
      -

      27.2.4.4 Sample Session

      +

      29.2.4.4 Sample Session

      @@ -770,10 +770,10 @@ Assuming you have a working installation of QT, you will see a window
       containing the string "hi" in a button.  
       

      -

      27.2.5 Director Classes

      +

      29.2.5 Director Classes

      -

      27.2.5.1 Director Introduction

      +

      29.2.5.1 Director Introduction

      @@ -800,7 +800,7 @@ class foo { };

      -

      27.2.5.2 Overriding Methods in Ocaml

      +

      29.2.5.2 Overriding Methods in Ocaml

      @@ -828,7 +828,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.

      -

      27.2.5.3 Director Usage Example

      +

      29.2.5.3 Director Usage Example

      @@ -887,7 +887,7 @@ in a more effortless style in ocaml, while leaving the "engine" part of the program in C++.

      -

      27.2.5.4 Creating director objects

      +

      29.2.5.4 Creating director objects

      @@ -928,7 +928,7 @@ object from causing a core dump, as long as the object is destroyed properly.

      -

      27.2.5.5 Typemaps for directors, directorin, directorout, directorargout

      +

      29.2.5.5 Typemaps for directors, directorin, directorout, directorargout

      @@ -939,7 +939,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.

      -

      27.2.5.6 directorin typemap

      +

      29.2.5.6 directorin typemap

      @@ -950,7 +950,7 @@ code receives when you are called. In general, a simple directorin typ can use the same body as a simple out typemap.

      -

      27.2.5.7 directorout typemap

      +

      29.2.5.7 directorout typemap

      @@ -961,7 +961,7 @@ for the same type, except when there are special requirements for object ownership, etc.

      -

      27.2.5.8 directorargout typemap

      +

      29.2.5.8 directorargout typemap

      @@ -978,7 +978,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.

      -

      27.2.6 Exceptions

      +

      29.2.6 Exceptions

      diff --git a/Doc/Manual/Octave.html b/Doc/Manual/Octave.html index be512f0ce..0340c2fd5 100644 --- a/Doc/Manual/Octave.html +++ b/Doc/Manual/Octave.html @@ -8,13 +8,14 @@ -

      28 SWIG and Octave

      +

      30 SWIG and Octave

      To build an Octave module when wrapping C code, run SWIG using the -octave option:

      -
      $ swig -octave example.i 
      +
      $ swig -octave -o example_wrap.cpp example.i 

      The -c++ option is also required when wrapping C++ code:

      -
      $ swig -octave -c++ example.i 
      +
      $ swig -octave -c++ -o example_wrap.cpp example.i 

      -This creates a C++ source file example_wrap.cxx. 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. +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

      + +

      -The swig command line has a number of options you can use, like to redirect it's output. Use swig --help to learn about these. +The swig command line has a number of options you can use, like to redirect its output. Use swig -help to learn about these. +Options specific to the Octave module are:

      -

      28.2.1 Compiling a dynamic module

      +
      +
      $ swig -octave -help
      +...
      +Octave Options (available with -octave)
      +     -globals name - Set name used to access C global variables [default: 'cvar']
      +                     Use '.' to load C global variables into module namespace
      +     -opprefix str - Prefix str for global operator functions [default: 'op_']
      +
      + +

      +The -globals option sets the name of the variable which is the namespace for C global variables exported by the module. +The special name "." loads C global variables into the module namespace, i.e. alongside C functions and structs exported by the module. +The -opprefix options sets the prefix of the names of global/friend operator functions. +

      + +

      30.2.2 Compiling a dynamic module

      @@ -106,12 +130,12 @@ Building an oct file is usually done with the mkoctfile command (either within O

      -$ swig -octave -c++ example.i -o example_wrap.cxx
      -$ mkoctfile example_wrap.cxx example.c
      +$ swig -octave -c++ -o example_wrap.cpp example.i
      +$ mkoctfile example_wrap.cpp example.c
       

      - where example.c is the file containing the gcd() implementation. + where "example.c" is the file containing the gcd() implementation.

      @@ -119,12 +143,12 @@ $ mkoctfile example_wrap.cxx example.c

      - mkoctfile will produce example.oct, which contains the compiled extension module. Loading it into Octave is then a matter of invoking + mkoctfile will produce "example.oct", which contains the compiled extension module. Loading it into Octave is then a matter of invoking

      octave:1> example
      -

      28.2.2 Using your module

      +

      30.2.3 Using your module

      @@ -142,52 +166,55 @@ octave:4> example.cvar.Foo=4; octave:5> example.cvar.Foo ans = 4 -

      28.3 A tour of basic C/C++ wrapping

      +

      30.3 A tour of basic C/C++ wrapping

      -

      28.3.1 Modules

      +

      30.3.1 Modules

      -The SWIG module directive specifies the name of the Octave module. If you specify `module example', then in Octave everything in the module will be accessible under "example", as in the above example. When choosing a module name, make sure you don't use the same name as a built-in Octave command or standard module name. +The SWIG module directive specifies the name of the Octave module. If you specify "module example", then in Octave everything in the module will be accessible under "example", as in the above example. When choosing a module name, make sure you don't use the same name as a built-in Octave command or standard module name.

      -When Octave is asked to invoke example, it will try to find the .m or .oct file that defines the function "example". It will thusly find example.oct, that upon loading will register all of the module's symbols. +When Octave is asked to invoke example, it will try to find the ".m" or ".oct" file that defines the function "example". You therefore need to make sure that "example.oct" is in Octave's search path, which can be specified with the environment variable "OCTAVE_PATH".

      -Giving this function a parameter "global" will cause it to load all symbols into the global namespace in addition to the example namespace. For example: +To load an Octave module, simply type its name:

      -
      $ octave -q
      -octave:1> example("global")
      +
      +octave:1> example;
       octave:2> gcd(4,6)
       ans =  2
       octave:3> cvar.Foo
       ans =  3
       octave:4> cvar.Foo=4;
       octave:5> cvar.Foo
      -ans =  4 
      +ans =  4
       
      -

      - It is also possible to rename the module namespace with an assignment, as in:
      -

      octave:1> example;
      -octave:2> c=example;
      -octave:3> c.gcd(10,4)
      -ans =  2 

      -All global variables are put into the cvar namespace object. This is accessible either as my_module.cvar, or just cvar (if the module is imported into the global namespace). -

      -

      -One can also rename it by simple assignment, e.g., +Modules can also be loaded from within functions, even before being loaded in the base context. +If the module is also used in the base context, however, it must first be loaded again:

      +
      -octave:1> some_vars = cvar;
      +octave:1> function l = my_lcm(a,b)
      +> example
      +> l = abs(a*b)/example.gcd(a,b);
      +> endfunction
      +octave:2> my_lcm(4,6)
      +ans =  12
      +octave:3> example.gcd(4,6)
      +error: can't perform indexing operations for <unknown type> type
      +octave:3> example;
      +octave:4> example.gcd(4,6)
      +ans =  2
       
      -

      28.3.2 Functions

      +

      30.3.2 Functions

      @@ -204,16 +231,16 @@ int fact(int n);

      octave:1> example.fact(4)
       24 
      -

      28.3.3 Global variables

      +

      30.3.3 Global variables

      Global variables are a little special in Octave. Given a global variable:

      -
      %module example
      +
      %module example
       extern double Foo;
      -      
      +

      To expose variables, SWIG actually generates two functions, to get and set the value. In this case, Foo_set and Foo_set would be generated. SWIG then automatically calls these functions when you get and set the variable-- in the former case creating a local copy in the interpreter of the C variables, and in the latter case copying an interpreter variables onto the C variable. @@ -257,7 +284,7 @@ octave:2> example.PI=3.142; octave:3> example.PI ans = 3.1420 -

      28.3.4 Constants and enums

      +

      30.3.4 Constants and enums

      @@ -279,7 +306,7 @@ example.SCONST="Hello World" example.SUNDAY=0 .... -

      28.3.5 Pointers

      +

      30.3.5 Pointers

      @@ -326,7 +353,7 @@ octave:2> f=example.fopen("not there","r"); error: value on right hand side of assignment is undefined error: evaluating assignment expression near line 2, column 2 -

      28.3.6 Structures and C++ classes

      +

      30.3.6 Structures and C++ classes

      @@ -461,7 +488,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.

      -

      28.3.7 C++ inheritance

      +

      30.3.7 C++ inheritance

      @@ -470,7 +497,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.

      -

      28.3.8 C++ overloaded functions

      +

      30.3.8 C++ overloaded functions

      @@ -480,7 +507,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.

      -

      28.3.9 C++ operators

      +

      30.3.9 C++ operators

      @@ -580,7 +607,11 @@ On the C++ side, the default mappings are as follows: %rename(__brace) *::operator[]; -

      28.3.10 Class extension with %extend

      +

      +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

      @@ -610,7 +641,7 @@ octave:3> printf("%s\n",a); octave:4> a.__str() 4 -

      28.3.11 C++ templates

      +

      30.3.11 C++ templates

      @@ -687,14 +718,14 @@ ans = -

      28.3.12 C++ Smart Pointers

      +

      30.3.12 C++ Smart Pointers

      C++ smart pointers are fully supported as in other modules.

      -

      28.3.13 Directors (calling Octave from C++ code)

      +

      30.3.13 Directors (calling Octave from C++ code)

      @@ -755,7 +786,8 @@ Note that you have to enable directors via the %feature directive (see other mod subclass() will accept any number of C++ bases or other subclass()'ed objects, (string,octave_value) pairs, and function_handles. In the first case, these are taken as base classes; in the second case, as named members (either variables or functions, depending on whether the given value is a function handle); in the third case, as member functions whose name is taken from the given function handle. E.g.,

      -octave:1> B=@(some_var=2) subclass(A(),'some_var',some_var,@some_func,'another_func',@(self) do_stuff())
      +octave:1> B=@(some_var=2) subclass(A(),'some_var',some_var,@some_func,'another_func',
      +@(self) do_stuff())
       

      You can also assign non-C++ member variables and functions after construct time. There is no support for non-C++ static members. @@ -774,14 +806,14 @@ c-side routine called octave-side routine called -

      28.3.14 Threads

      +

      30.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.

      -

      28.3.15 Memory management

      +

      30.3.15 Memory management

      @@ -815,14 +847,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).

      -

      28.3.16 STL support

      +

      30.3.16 STL support

      Various STL library files are provided for wrapping STL containers.

      -

      28.3.17 Matrix typemaps

      +

      30.3.17 Matrix typemaps

      diff --git a/Doc/Manual/Perl5.html b/Doc/Manual/Perl5.html index 0c2733c0e..49e8965fa 100644 --- a/Doc/Manual/Perl5.html +++ b/Doc/Manual/Perl5.html @@ -6,7 +6,7 @@ -

      29 SWIG and Perl5

      +

      31 SWIG and Perl5

        @@ -82,12 +82,12 @@ This chapter describes SWIG's support of Perl5. Although the Perl5 module is one of the earliest SWIG modules, it has continued to evolve and has been improved greatly with the help of SWIG users. For the -best results, it is recommended that SWIG be used with Perl5.003 or -later. Earlier versions are problematic and SWIG generated extensions -may not compile or run correctly. +best 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.

        -

        29.1 Overview

        +

        31.1 Overview

        @@ -108,12 +108,12 @@ described. Advanced customization features, typemaps, and other options are found near the end of the chapter.

        -

        29.2 Preliminaries

        +

        31.2 Preliminaries

        To build a Perl5 module, run SWIG using the -perl option as -follows : +follows:

        @@ -133,11 +133,11 @@ To build the module, you will need to compile the file
         example_wrap.c and link it with the rest of your program.
         

        -

        29.2.1 Getting the right header files

        +

        31.2.1 Getting the right header files

        -In order to compile, SWIG extensions need the following Perl5 header files :

        +In order to compile, SWIG extensions need the following Perl5 header files:

         #include "Extern.h"
        @@ -149,36 +149,36 @@ In order to compile, SWIG extensions need the following Perl5 header files :

        These are typically located in a directory like this

        -/usr/lib/perl5/5.00503/i386-linux/CORE
        +/usr/lib/perl/5.14/CORE
         

        The SWIG configuration script automatically tries to locate this directory so that it can compile examples. However, if you need to find out where the directory is -loaded, an easy way to find out is to run Perl itself. +located, an easy way to find out is to ask Perl itself:

        -% perl -e 'use Config; print $Config{archlib};'
        -/usr/lib/perl5/5.00503/i386-linux
        +$ perl -e 'use Config; print "$Config{archlib}\n";'
        +/usr/lib/perl/5.14
         
        -

        29.2.2 Compiling a dynamic module

        +

        31.2.2 Compiling a dynamic module

        The preferred approach to building an extension module is to compile it into -a shared object file or DLL. To do this, you will need to compile your program -using commands like this (shown for Linux): +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 your program using commands like this (shown for Linux):

         $ swig -perl example.i
        -% gcc example.c
        -% gcc -c example_wrap.c -I/usr/lib/perl5/5.00503/i386-linux/CORE -Dbool=char
        -% gcc -shared example.o example_wrap.o -o example.so
        +$ gcc -fPIC example.c
        +$ gcc -fPIC -c example_wrap.c -I/usr/lib/perl/5.14/CORE -Dbool=char
        +$ gcc -shared example.o example_wrap.o -o example.so
         

        @@ -198,13 +198,13 @@ the target should be named `example.so', `example.sl', or the appropriate dynamic module name on your system.

        -

        29.2.3 Building a dynamic module with MakeMaker

        +

        31.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 :

        +script such as the following:

         # File : Makefile.PL
        @@ -218,12 +218,12 @@ WriteMakefile(
         

        -Now, to build a module, simply follow these steps :

        +Now, to build a module, simply follow these steps:

        -% perl Makefile.PL
        -% make
        -% make install
        +$ perl Makefile.PL
        +$ make
        +$ make install
         

        @@ -232,17 +232,17 @@ 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.

        -

        29.2.4 Building a static version of Perl

        +

        31.2.4 Building a static version of Perl

        If 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 -extension, you first need to invoke SWIG as follows :

        +extension, you first need to invoke SWIG as follows:

        -% swig -perl -static example.i
        +$ swig -perl -static example.i
         

        @@ -253,7 +253,7 @@ By default SWIG includes code for dynamic loading, but the Next, you will need to supply a main() function that initializes your extension and starts the Perl interpreter. While, this may sound daunting, SWIG can do this for you automatically as -follows :

        +follows:

         %module example
        @@ -268,10 +268,10 @@ extern int fact(int);
         

        -The same thing can be accomplished by running SWIG as follows :

        +The same thing can be accomplished by running SWIG as follows:

        -% swig -perl -static -lperlmain.i example.i
        +$ swig -perl -static -lperlmain.i example.i
         

        @@ -290,7 +290,7 @@ for a dynamic module, but change the link line to something like this:

        -% gcc example.o example_wrap.o -L/usr/lib/perl5/5.00503/i386-linux/CORE \
        +$ gcc example.o example_wrap.o -L/usr/lib/perl/5.14/CORE \
         	-lperl -lsocket -lnsl -lm -o myperl
         
        @@ -301,7 +301,7 @@ added to it. Depending on your machine, you may need to link with additional libraries such as -lsocket, -lnsl, -ldl, etc.

        -

        29.2.5 Using the module

        +

        31.2.5 Using the module

        @@ -323,9 +323,7 @@ A common error received by first-time users is the following:

         use example;
        -Can't locate example.pm in @INC (@INC contains: /usr/lib/perl5/5.00503/i386-lin
        -ux /usr/lib/perl5/5.00503 /usr/lib/perl5/site_perl/5.005/i386-linux /usr/lib/pe
        -rl5/site_perl/5.005 .) at - line 1.
        +Can't locate example.pm in @INC (@INC contains: /etc/perl /usr/local/lib/perl/5.14.2 /usr/local/share/perl/5.14.2 /usr/lib/perl5 /usr/share/perl5 /usr/lib/perl/5.14 /usr/share/perl/5.14 /usr/local/lib/site_perl .) at - line 1.
         BEGIN failed--compilation aborted at - line 1.
         
        @@ -363,7 +361,7 @@ Another common error is the following:
         use example;
         Can't load './example.so' for module example: ./example.so: 
        -undefined symbol: Foo at /usr/lib/perl5/5.00503/i386-linux/DynaLoader.pm line 169.
        +undefined symbol: Foo at /usr/lib/perl/5.14/i386-linux/DynaLoader.pm line 169.
         
          at - line 1
         BEGIN failed--compilation aborted at - line 1.
        @@ -409,7 +407,7 @@ error when you try to use your module:
         
         use example;
         Can't load './example.so' for module example: libfoo.so: cannot open shared object file: 
        -No such file or directory at /usr/lib/perl5/5.00503/i386-linux/DynaLoader.pm line 169.
        +No such file or directory at /usr/lib/perl/5.14/i386-linux/DynaLoader.pm line 169.
         
          at - line 1
         BEGIN failed--compilation aborted at - line 1.
        @@ -456,7 +454,7 @@ system configuration (this requires root access and you will need to
         read the man pages).
         

        -

        29.2.6 Compilation problems and compiling with C++

        +

        31.2.6 Compilation problems and compiling with C++

        @@ -472,10 +470,10 @@ compiler. For example:

        -% swig -c++ -perl example.i
        -% g++ -c example.cxx
        -% g++ -c example_wrap.cxx -I/usr/lib/perl5/5.00503/i386-linux/CORE
        -% g++ -shared example.o example_wrap.o -o example.so
        +$ swig -c++ -perl example.i
        +$ g++ -fPIC -c example.cxx
        +$ g++ -fPIC -c example_wrap.cxx -I/usr/lib/perl/5.14/i386-linux/CORE
        +$ g++ -shared example.o example_wrap.o -o example.so
         

        @@ -485,10 +483,10 @@ Solaris, you often need to add an extra library -lCrun like this:

        -% swig -c++ -perl example.i
        -% g++ -c example.cxx
        -% g++ -c example_wrap.cxx -I/usr/lib/perl5/5.00503/i386-linux/CORE
        -% g++ -shared example.o example_wrap.o -o example.so -lCrun
        +$ swig -c++ -perl example.i
        +$ CC -c example.cxx
        +$ CC -c example_wrap.cxx -I/usr/lib/perl/5.14/i386-linux/CORE
        +$ CC -shared example.o example_wrap.o -o example.so -lCrun
         

        @@ -503,7 +501,7 @@ it needs to be. So you should compile the wrapper like:

        -% g++ -c example_wrap.cxx -I/usr/lib/perl/5.8.0/CORE -D_GNU_SOURCE
        +$ g++ -fPIC -c example_wrap.cxx -I/usr/lib/perl/5.8.0/CORE -D_GNU_SOURCE
         

        @@ -511,7 +509,7 @@ it needs to be. So you should compile the wrapper like:

        -% perl -e 'use Config; print $Config{ccflags};'
        +$ perl -e 'use Config; print "$Config{ccflags}\n";'
         

        @@ -519,8 +517,8 @@ So you could also compile the wrapper like

        -% g++ -c example_wrap.cxx -I/usr/lib/perl/5.8.0/CORE \
        -`perl -e 'use Config; print $Config{ccflags}'`
        +$ g++ -fPIC -c example_wrap.cxx -I/usr/lib/perl/5.8.0/CORE \
        +`perl -MConfig -e 'print $Config{ccflags}'`
         

        @@ -568,8 +566,8 @@ can behave strangely when working with multiple modules.

        It should be noted that you may get a lot of error messages -about the `bool' datatype when compiling a C++ Perl module. If -you experience this problem, you can try the following :

        +about the 'bool' datatype when compiling a C++ Perl module. If +you experience this problem, you can try the following:

        • Use -DHAS_BOOL when compiling the SWIG wrapper code @@ -599,7 +597,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.

          -

          29.2.7 Compiling for 64-bit platforms

          +

          31.2.7 Compiling for 64-bit platforms

          @@ -626,7 +624,7 @@ also introduce problems on platforms that support more than one linking standard (e.g., -o32 and -n32 on Irix).

          -

          29.3 Building Perl Extensions under Windows

          +

          31.3 Building Perl Extensions under Windows

          @@ -637,13 +635,13 @@ section assumes you are using SWIG with Microsoft Visual C++ although the procedure may be similar with other compilers.

          -

          29.3.1 Running SWIG from Developer Studio

          +

          31.3.1 Running SWIG from Developer Studio

          If you are developing your application within Microsoft developer studio, SWIG can be invoked as a custom build option. The process -roughly requires these steps :

          +roughly requires these steps:

          • Open up a new workspace and use the AppWizard to select a DLL @@ -651,7 +649,7 @@ project.
          • Add both the SWIG interface file (the .i file), any supporting C files, and the name of the wrapper file that will be created by SWIG -(ie. example_wrap.c). Note : If using C++, choose a +(ie. example_wrap.c). Note: If using C++, choose a different suffix for the wrapper file such as example_wrap.cxx. Don't worry if the wrapper file doesn't exist yet--Developer studio will keep a reference to it around. @@ -689,7 +687,7 @@ Now, assuming you made it this far, SWIG will be automatically invoked when you build your project. Any changes made to the interface file will result in SWIG being automatically invoked to produce a new version of the wrapper file. To run your new Perl extension, simply run Perl and -use the use command as normal. For example : +use the use command as normal. For example:

            @@ -700,7 +698,7 @@ print "$a\n";
             
             
            -

            29.3.2 Using other compilers

            +

            31.3.2 Using other compilers

            @@ -708,7 +706,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.

            -

            29.4 The low-level interface

            +

            31.4 The low-level interface

            @@ -718,7 +716,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.

            -

            29.4.1 Functions

            +

            31.4.1 Functions

            @@ -741,7 +739,7 @@ use example; $a = &example::fact(2);

        -

        29.4.2 Global variables

        +

        31.4.2 Global variables

        @@ -758,7 +756,7 @@ double Spam;

        -is accessed as follows :

        +is accessed as follows:

         use example;
        @@ -811,7 +809,7 @@ extern char *path;       // Declared later in the input
         
        -

        29.4.3 Constants

        +

        31.4.3 Constants

        @@ -851,14 +849,14 @@ print example::FOO,"\n";

      -

      29.4.4 Pointers

      +

      31.4.4 Pointers

      SWIG 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. That is, if you have a C declaration like this :

      +is. That is, if you have a C declaration like this:

       Matrix *new_Matrix(int n, int m);
      @@ -880,7 +878,7 @@ generated.

      To check to see if a value is the NULL pointer, use the -defined() command :

      +defined() command:

       if (defined($ptr)) {
      @@ -904,7 +902,7 @@ In general, $a and $b will be different--since they
       are different references.  Thus, it is a mistake to check the equality
       of $a and $b to check the equality of two C
       pointers.  The correct method to check equality of C pointers is to
      -dereference them as follows :
      +dereference them as follows:
       

      @@ -960,7 +958,7 @@ as XS and xsubpp.  Given the advancement of the SWIG typesystem and the
       SWIG and XS, this is no longer supported.
       

      -

      29.4.5 Structures

      +

      31.4.5 Structures

      @@ -1094,12 +1092,12 @@ void Bar_f_set(Bar *b, Foo *val) {

      -

      29.4.6 C++ classes

      +

      31.4.6 C++ classes

      C++ classes are wrapped by building a set of low level accessor functions. -Consider the following class : +Consider the following class:

      @@ -1117,7 +1115,7 @@ static void print(List *l);
       

      -When wrapped by SWIG, the following functions are created : +When wrapped by SWIG, the following functions are created:

      @@ -1159,7 +1157,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.
       

      -

      29.4.7 C++ classes and type-checking

      +

      31.4.7 C++ classes and type-checking

      @@ -1195,7 +1193,7 @@ If necessary, the type-checker also adjusts the value of the pointer (as is nece multiple inheritance is used).

      -

      29.4.8 C++ overloaded functions

      +

      31.4.8 C++ overloaded functions

      @@ -1239,7 +1237,7 @@ example::Spam_foo_d($s,3.14); Please refer to the "SWIG Basics" chapter for more information.

      -

      29.4.9 Operators

      +

      31.4.9 Operators

      @@ -1266,17 +1264,17 @@ The following C++ operators are currently supported by the Perl module:

    • operator or
    • -

      29.4.10 Modules and packages

      +

      31.4.10 Modules and packages

      When 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 : +%module directive. To use the module, do the following:

      -% perl5
      +$ perl5
       use example;                      # load the example module
       print example::fact(4),"\n"       # Call a function in it
       24
      @@ -1342,17 +1340,17 @@ nested namespace simply provide the fully qualified name in your
       
       
      -

      29.5 Input and output parameters

      +

      31.5 Input and output parameters

      @@ -1580,7 +1578,7 @@ print "$c\n"; Note: The REFERENCE feature is only currently supported for numeric types (integers and floating point).

      -

      29.6 Exception handling

      +

      31.6 Exception handling

      @@ -1588,7 +1586,7 @@ The 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 features contains more details, but suppose you have a C++ class like the -following : +following:

      @@ -1745,7 +1743,7 @@ This is still supported, but it is deprecated.  The newer %exception di
       functionality, but it has additional capabilities that make it more powerful.
       

      -

      29.7 Remapping datatypes with typemaps

      +

      31.7 Remapping datatypes with typemaps

      @@ -1762,7 +1760,7 @@ Typemaps are only used if you want to change some aspect of the primitive C-Perl interface.

      -

      29.7.1 A simple typemap example

      +

      31.7.1 A simple typemap example

      @@ -1796,7 +1794,7 @@ The $input variable is the input object (usually a SV *).

      -When this example is used in Perl5, it will operate as follows : +When this example is used in Perl5, it will operate as follows:

      @@ -1805,7 +1803,7 @@ $n = example::fact(6);
       print "$n\n";
       ...
       
      -Output :
      +Output:
       Received an integer : 6
       720
       
      @@ -1866,7 +1864,7 @@ example::count("e","Hello World");
      -

      29.7.2 Perl5 typemaps

      +

      31.7.2 Perl5 typemaps

      @@ -1971,7 +1969,7 @@ Return of C++ member data (all languages). Check value of input parameter.

      -

      29.7.3 Typemap variables

      +

      31.7.3 Typemap variables

      @@ -2042,7 +2040,7 @@ properly assigned. The Perl name of the wrapper function being created.

      -

      29.7.4 Useful functions

      +

      31.7.4 Useful functions

      @@ -2111,7 +2109,7 @@ int sv_isa(SV *, char *0;

      -

      29.8 Typemap Examples

      +

      31.8 Typemap Examples

      @@ -2120,7 +2118,7 @@ might look at the files "perl5.swg" and "typemaps.i" in the SWIG library.

      -

      29.8.1 Converting a Perl5 array to a char **

      +

      31.8.1 Converting a Perl5 array to a char **

      @@ -2200,7 +2198,7 @@ char **get_args() {

      When this module is compiled, the wrapped C functions can be used in a -Perl script as follows : +Perl script as follows:

      @@ -2212,7 +2210,7 @@ print @$b,"\n";                                  # Print it out
       
      -

      29.8.2 Return values

      +

      31.8.2 Return values

      @@ -2227,7 +2225,7 @@ number of output values.

      The total number of return values should not exceed the number of input values unless you explicitly extend the argument stack. This -can be done using the EXTEND() macro as in : +can be done using the EXTEND() macro as in:

      @@ -2241,7 +2239,7 @@ can be done using the EXTEND() macro as in :
       }
       
      -

      29.8.3 Returning values from arguments

      +

      31.8.3 Returning values from arguments

      @@ -2286,7 +2284,7 @@ int multout(double a, double b, double *OUTPUT, double *OUTPUT);

      When this function is called, the output arguments are appended to the stack used to return results. This shows up an array in Perl. -For example : +For example:

      @@ -2295,11 +2293,11 @@ print "multout(7,13) = @r\n";
       ($x,$y) = multout(7,13);
       
      -

      29.8.4 Accessing array structure members

      +

      31.8.4 Accessing array structure members

      -Consider the following data structure : +Consider the following data structure:

      @@ -2358,13 +2356,13 @@ the "in" typemap in the previous section would be used to convert an
       to copy the converted array into a C data structure.
       

      -

      29.8.5 Turning Perl references into C pointers

      +

      31.8.5 Turning Perl references into C pointers

      A frequent confusion on the SWIG mailing list is errors caused by the mixing of Perl references and C pointers. For example, suppose you -have a C function that modifies its arguments like this : +have a C function that modifies its arguments like this:

      @@ -2374,7 +2372,7 @@ void add(double a, double b, double *c) {
       

      -A common misinterpretation of this function is the following Perl script : +A common misinterpretation of this function is the following Perl script:

      @@ -2411,7 +2409,7 @@ To make this work with a reference, you can use a typemap such as this:
       

      -Now, if you place this before the add function, you can do this : +Now, if you place this before the add function, you can do this:

      @@ -2423,7 +2421,7 @@ print "$c\n";
       
       
      -

      29.8.6 Pointer handling

      +

      31.8.6 Pointer handling

      @@ -2502,7 +2500,7 @@ For example:

      -

      29.9 Proxy classes

      +

      31.9 Proxy classes

      @@ -2518,7 +2516,7 @@ to the underlying code. This section describes the implementation details of the proxy interface.

      -

      29.9.1 Preliminaries

      +

      31.9.1 Preliminaries

      @@ -2540,11 +2538,11 @@ 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.

      -

      29.9.2 Structure and class wrappers

      +

      31.9.2 Structure and class wrappers

      -Suppose you have the following SWIG interface file : +Suppose you have the following SWIG interface file:

      @@ -2666,13 +2664,13 @@ $v->DESTROY();
       
       
      -

      29.9.3 Object Ownership

      +

      31.9.3 Object Ownership

      In 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 : +problem---suppose you had a function like this:

      @@ -2685,7 +2683,7 @@ Vector *Vector_get(Vector *v, int index) {
       This function takes a Vector pointer and returns a pointer to another
       Vector.  Such a function might be used to manage arrays or lists of
       vectors (in C).  Now contrast this function with the constructor for a
      -Vector object :
      +Vector object:
       

      @@ -2753,11 +2751,11 @@ counting, garbage collection, or advanced features one might find in
       sophisticated languages.
       

      -

      29.9.4 Nested Objects

      +

      31.9.4 Nested Objects

      -Suppose that we have a new object that looks like this : +Suppose that we have a new object that looks like this:

      @@ -2774,7 +2772,7 @@ struct Particle {
       In this case, the members of the structure are complex objects that
       have already been encapsulated in a Perl proxy class.  To handle
       these correctly, we use the %BLESSEDMEMBERS hash which would
      -look like this (along with some supporting code) :
      +look like this (along with some supporting code):
       

      @@ -2796,7 +2794,7 @@ unmodified.
       

      -This implementation allows us to operate on nested structures as follows : +This implementation allows us to operate on nested structures as follows:

      @@ -2806,12 +2804,12 @@ $p->{f}->{x} = 0.0;
       %${$p->{v}} = ( x=>0, y=>0, z=>0);         
       
      -

      29.9.5 Proxy Functions

      +

      31.9.5 Proxy Functions

      When functions take arguments involving a complex object, it is -sometimes necessary to write a proxy function. For example : +sometimes necessary to write a proxy function. For example:

      @@ -2822,7 +2820,7 @@ double dot_product(Vector *v1, Vector *v2);
       Since Vector is an object already wrapped into a proxy class, we need
       to modify this function to accept arguments that are given in the form
       of tied hash tables.  This is done by creating a Perl function like
      -this :
      +this:
       

      @@ -2840,13 +2838,13 @@ This function replaces the original function, but operates in an
       identical manner.
       

      -

      29.9.6 Inheritance

      +

      31.9.6 Inheritance

      Simple C++ inheritance is handled using the Perl @ISA array in each class package. For example, if you have the following -interface file : +interface file:

      @@ -2881,7 +2879,7 @@ public:
       

      -The resulting, Perl wrapper class will create the following code : +The resulting, Perl wrapper class will create the following code:

      @@ -2916,7 +2914,7 @@ particular, inheritance of data members is extremely tricky (and I'm
       not even sure if it really works).
       

      -

      29.9.7 Modifying the proxy methods

      +

      31.9.7 Modifying the proxy methods

      @@ -2944,7 +2942,7 @@ public: };

      -

      29.10 Adding additional Perl code

      +

      31.10 Adding additional Perl code

      diff --git a/Doc/Manual/Php.html b/Doc/Manual/Php.html index c9ee74f38..78ee6ea7f 100644 --- a/Doc/Manual/Php.html +++ b/Doc/Manual/Php.html @@ -7,7 +7,7 @@ -

      30 SWIG and PHP

      +

      32 SWIG and PHP

        @@ -49,19 +49,23 @@

        -SWIG supports generating wrappers for PHP5. Support for PHP4 has been removed -as of SWIG 1.3.37. The PHP developers are no longer making new PHP4 releases, +SWIG supports generating wrappers for PHP5. Support for PHP4 was removed +in SWIG 1.3.37. The PHP developers are no longer making new PHP4 releases, and won't even be patching critical security issues after 2008-08-08, so it -doesn't make much sense for SWIG to continue to support PHP4 at this point. -If you need to continue to use PHP4, stick with SWIG 1.3.36. +doesn't make much sense for SWIG to continue to support PHP4 now. If you +really need to continue to use PHP4, just stick with SWIG 1.3.36. +

        + +

        +Currently any PHP5 release should work, but we don't regularly test with +PHP < 5.3.

        In this chapter, we discuss SWIG's support of PHP. The PHP module was extensively rewritten in release 1.3.26, and support for generating -OO wrappers for PHP5 was added in 1.3.30. The PHP module works fairly -well, but currently does not implement all the -features available in some of the other languages. +OO wrappers for PHP5 was added in 1.3.30. The PHP module now supports most +of the features available in some of the other languages.

        @@ -75,7 +79,7 @@ your extension into php directly, you will need the complete PHP source tree available.

        -

        30.1 Generating PHP Extensions

        +

        32.1 Generating PHP Extensions

        @@ -122,7 +126,7 @@ and it doesn't play nicely with package system. We don't recommend this approach, or provide explicit support for it.

        -

        30.1.1 Building a loadable extension

        +

        32.1.1 Building a loadable extension

        @@ -137,12 +141,12 @@ least work for Linux though): gcc -shared example_wrap.o -o example.so

      -

      30.1.2 Using PHP Extensions

      +

      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 the [PHP] section of +can load it for every script by adding this line to the [PHP] section of php.ini:

      @@ -152,7 +156,7 @@ can load it for every script by adding this line the [PHP] section of

      Alternatively, you can load it explicitly only for scripts which need it -by adding this line: +by adding this line to the start of each such PHP script::

      @@ -160,7 +164,7 @@ by adding this line:
       

      -to the start of each PHP file. SWIG also generates a php module, which +SWIG also generates a php module, which attempts to do the dl() call for you:

      @@ -168,21 +172,22 @@ attempts to do the dl() call for you: include("example.php");
      -

      30.2 Basic PHP interface

      +

      32.2 Basic PHP interface

      It 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. +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.

      -

      30.2.1 Constants

      +

      32.2.1 Constants

      -These work in much the same way as in C/C++, constants can be defined +These 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 your PHP script as a PHP constant, (i.e. no dollar sign is needed to @@ -199,7 +204,7 @@ access them.) For example, with a swig interface file like this,

      -you can access the constants in your php script like this, +you can access the constants in your PHP script like this,

      @@ -213,9 +218,16 @@ echo "E = " . E . "\n";
       

      -There are two peculiarities with using constants in PHP. The first is that -if you try to use an undeclared constant, it will evaluate to a string -set to the constant's name. For example, +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 +similar. +

      + +

      +For example,

      @@ -243,67 +255,12 @@ if(EASY_TO_MISPEL) {
       

      -will issue a warning about the undeclared constant, but will then -evaluate it and turn it into a string ('EASY_TO_MISPEL'), which -evaluates to true, rather than the value of the constant which would -be false. This is a feature! +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!

      -

      -The second 'feature' is that although constants are case sensitive (by -default), you cannot declare a constant twice with alternative -cases. E.g., -

      - -
      -
      -%module example
      -
      -#define TEST	Hello
      -#define Test	World
      -
      -
      - -

      -accessed from PHP, -

      - -
      -
      -include("example.php");
      -
      -echo TEST, Test;
      -
      -
      - -

      -will output "Hello Test" rather than "Hello World". This is because -internally, all constants are stored in a hash table by their lower -case name, so 'TEST' and 'Test' will map to the same hash element -('Test'). But, because we declared them case sensitive, the Zend -engine will test if the case matches with the case the constant was -declared with first. -

      - -

      -So, in the example above, the TEST constant was declared first, and -will be stored under the hash element 'test'. The 'Test' constant will -also map to the same hash element 'test', but will not overwrite -it. When called from the script, the TEST constant will again be -mapped to the hash element 'test' so the constant will be -retrieved. The case will then be checked, and will match up, so the -value ('Hello') will be returned. When 'Test' is evaluated, it will -also map to the same hash element 'test'. The same constant will be -retrieved, this time though the case check will fail as 'Test' != -'TEST'. So PHP will assume that Test is a undeclared constant, and as -explained above, will return it as a string set to the constant name -('Test'). Hence the script above will print 'Hello Test'. If they were -declared non-case sensitive, the output would be 'Hello Hello', as -both point to the same value, without the case test taking place. ( -Apologies, this paragraph needs rewriting to make some sense. ) -

      - -

      30.2.2 Global Variables

      +

      32.2.2 Global Variables

      @@ -352,7 +309,7 @@ undefined. At this time SWIG does not support custom accessor methods.

      -

      30.2.3 Functions

      +

      32.2.3 Functions

      @@ -405,7 +362,7 @@ print $s; # The value of $s was not changed. --> -

      30.2.4 Overloading

      +

      32.2.4 Overloading

      @@ -461,7 +418,7 @@ taking the integer argument.

      --> -

      30.2.5 Pointers and References

      +

      32.2.5 Pointers and References

      @@ -549,6 +506,12 @@ 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. +

      +
       %module example
       %include "phppointers.i"
      @@ -593,13 +556,15 @@ PHP in a number of ways: by using unset on an existing
       variable, or assigning NULL to a variable.
       

      -

      30.2.6 Structures and C++ classes

      +

      32.2.6 Structures and C++ classes

      -SWIG defaults to wrapping C++ structs and classes with PHP classes -unless "-noproxy" is specified. For PHP5, a PHP wrapper -class is generated which calls a set of flat functions wrapping the C++ class. +SWIG defaults to wrapping C++ structs and classes with PHP classes - this +is done by generating a PHP wrapper script which defines proxy classes +which calls a set of flat functions which actually wrap the C++ class. +You can disable this wrapper layer by passing the command-line option +"-noproxy" in which case you'll just get the flat functions.

      @@ -652,7 +617,7 @@ Would be used in the following way from PHP5: Member variables and methods are accessed using the -> operator.

      -

      30.2.6.1 Using -noproxy

      +

      32.2.6.1 Using -noproxy

      @@ -678,7 +643,7 @@ Complex_im_set($obj,$d); Complex_im_get($obj);

      -

      30.2.6.2 Constructors and Destructors

      +

      32.2.6.2 Constructors and Destructors

      @@ -719,7 +684,7 @@ the programmer can either reassign the variable or call unset($v)

      -

      30.2.6.3 Static Member Variables

      +

      32.2.6.3 Static Member Variables

      @@ -746,7 +711,7 @@ would be accessed in PHP as,

       include("example.php");
       
      -echo "There has now been " . Ko::threats() . " threats\n";
      +echo "There have now been " . Ko::threats() . " threats\n";
       
       
      @@ -759,10 +724,10 @@ function, e.g. Ko::threats(10); -echo "There has now been " . Ko::threats() . " threats\n"; +echo "There have now been " . Ko::threats() . " threats\n";
      -

      30.2.6.4 Static Member Functions

      +

      32.2.6.4 Static Member Functions

      @@ -784,7 +749,7 @@ Ko::threats();

      -

      30.2.7 PHP Pragmas, Startup and Shutdown code

      +

      32.2.7 PHP Pragmas, Startup and Shutdown code

      @@ -872,7 +837,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.

      -

      30.3 Cross language polymorphism

      +

      32.3 Cross language polymorphism

      @@ -907,7 +872,7 @@ wrapper functions takes care of all the cross-language method routing transparently.

      -

      30.3.1 Enabling directors

      +

      32.3.1 Enabling directors

      @@ -936,9 +901,6 @@ globally, to specific classes, and to specific methods, like this: // generate directors for all virtual methods in class Foo %feature("director") Foo; - -// generate a director for just Foo::bar() -%feature("director") Foo::bar;

      @@ -999,7 +961,7 @@ class MyFoo extends Foo {
      -

      30.3.2 Director classes

      +

      32.3.2 Director classes

      @@ -1079,7 +1041,7 @@ so there is no need for the extra overhead involved with routing the calls through PHP.

      -

      30.3.3 Ownership and object destruction

      +

      32.3.3 Ownership and object destruction

      @@ -1135,7 +1097,7 @@ In this example, we are assuming that FooContainer will take care of deleting all the Foo pointers it contains at some point.

      -

      30.3.4 Exception unrolling

      +

      32.3.4 Exception unrolling

      @@ -1194,7 +1156,7 @@ Swig::DirectorMethodException is thrown, PHP will register the exception as soon as the C wrapper function returns.

      -

      30.3.5 Overhead and code bloat

      +

      32.3.5 Overhead and code bloat

      @@ -1227,7 +1189,7 @@ optimized by selectively enabling director methods (using the %feature directive) for only those methods that are likely to be extended in PHP.

      -

      30.3.6 Typemaps

      +

      32.3.6 Typemaps

      @@ -1241,7 +1203,7 @@ need to be supported.

      -

      30.3.7 Miscellaneous

      +

      32.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 8f9e43735..8c1eb2d36 100644 --- a/Doc/Manual/Pike.html +++ b/Doc/Manual/Pike.html @@ -6,7 +6,7 @@ -

      31 SWIG and Pike

      +

      33 SWIG and Pike

        @@ -46,10 +46,10 @@ least, make sure you read the "SWIG Basics" chapter.

        -

        31.1 Preliminaries

        +

        33.1 Preliminaries

        -

        31.1.1 Running SWIG

        +

        33.1.1 Running SWIG

        @@ -94,7 +94,7 @@ can use the -o option:

        $ swig -pike -o pseudonym.c example.i
        -

        31.1.2 Getting the right header files

        +

        33.1.2 Getting the right header files

        @@ -114,7 +114,7 @@ You're looking for files with the names global.h, program.h and so on.

        -

        31.1.3 Using your module

        +

        33.1.3 Using your module

        @@ -129,10 +129,10 @@ Pike v7.4 release 10 running Hilfe v3.5 (Incremental Pike Frontend) (1) Result: 24

      -

      31.2 Basic C/C++ Mapping

      +

      33.2 Basic C/C++ Mapping

      -

      31.2.1 Modules

      +

      33.2.1 Modules

      @@ -143,7 +143,7 @@ concerned), SWIG's %module directive doesn't really have any significance.

      -

      31.2.2 Functions

      +

      33.2.2 Functions

      @@ -168,7 +168,7 @@ exactly as you'd expect it to: (1) Result: 24 -

      31.2.3 Global variables

      +

      33.2.3 Global variables

      @@ -197,7 +197,7 @@ will result in two functions, Foo_get() and Foo_set(): (3) Result: 3.141590 -

      31.2.4 Constants and enumerated types

      +

      33.2.4 Constants and enumerated types

      @@ -205,7 +205,7 @@ Enumerated types in C/C++ declarations are wrapped as Pike constants, not as Pike enums.

      -

      31.2.5 Constructors and Destructors

      +

      33.2.5 Constructors and Destructors

      @@ -213,7 +213,7 @@ Constructors are wrapped as create() methods, and destructors are wrapped as destroy() methods, for Pike classes.

      -

      31.2.6 Static Members

      +

      33.2.6 Static Members

      diff --git a/Doc/Manual/Preface.html b/Doc/Manual/Preface.html index 2d0aa093e..e1fcfbbd8 100644 --- a/Doc/Manual/Preface.html +++ b/Doc/Manual/Preface.html @@ -93,12 +93,12 @@ SWIG along with information about beta releases and future work.

      -Subversion access to the latest version of SWIG is also available. More information +Git and Subversion access to the latest version of SWIG is also available. More information about this can be obtained at:

      diff --git a/Doc/Manual/Preprocessor.html b/Doc/Manual/Preprocessor.html index 8d41efccf..8fcbe9206 100644 --- a/Doc/Manual/Preprocessor.html +++ b/Doc/Manual/Preprocessor.html @@ -16,8 +16,11 @@
    • Macro Expansion
    • SWIG Macros
    • C99 and GNU Extensions +
    • Preprocessing and delimiters +
    • Preprocessor and Typemaps
    • Viewing preprocessor output
    • The #error and #warning directives @@ -306,7 +309,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

      +

      7.7 Preprocessing and delimiters

      + + +

      +The preprocessor handles { }, " " and %{ %} delimiters differently. +

      + +

      7.7.1 Preprocessing and %{ ... %} & " ... " delimiters

      @@ -331,7 +341,7 @@ the contents of the %{ ... %} block are copied without modification to the output (including all preprocessor directives).

      -

      7.8 Preprocessing and { ... } delimiters

      +

      7.7.2 Preprocessing and { ... } delimiters

      @@ -373,7 +383,7 @@ to actually go into the wrapper file, prefix the preprocessor directives with % and leave the preprocessor directive in the code.

      -

      7.9 Preprocessor and Typemaps

      +

      7.8 Preprocessor and Typemaps

      @@ -444,7 +454,7 @@ would generate -

      7.10 Viewing preprocessor output

      +

      7.9 Viewing preprocessor output

      @@ -454,7 +464,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.11 The #error and #warning directives

      +

      7.10 The #error and #warning directives

      diff --git a/Doc/Manual/Python.html b/Doc/Manual/Python.html index 23271e649..762abebba 100644 --- a/Doc/Manual/Python.html +++ b/Doc/Manual/Python.html @@ -6,7 +6,7 @@ -

      32 SWIG and Python

      +

      34 SWIG and Python

    • Further details on the Python class interface @@ -93,6 +98,8 @@
    • %feature("docstring") @@ -128,7 +135,7 @@ very least, make sure you read the "SWIG Basics" chapter.

      -

      32.1 Overview

      +

      34.1 Overview

      @@ -155,10 +162,10 @@ described followed by a discussion of low-level implementation details.

      -

      32.2 Preliminaries

      +

      34.2 Preliminaries

      -

      32.2.1 Running SWIG

      +

      34.2.1 Running SWIG

      @@ -256,13 +263,13 @@ The following sections have further practical examples and details on how you might go about compiling and using the generated files.

      -

      32.2.2 Using distutils

      +

      34.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).

      @@ -348,7 +355,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)

      -

      32.2.3 Hand compiling a dynamic module

      +

      34.2.3 Hand compiling a dynamic module

      @@ -396,7 +403,7 @@ module actually consists of two files; socket.py and

      -

      32.2.4 Static linking

      +

      34.2.4 Static linking

      @@ -475,7 +482,7 @@ If using static linking, you might want to rely on a different approach (perhaps using distutils).

      -

      32.2.5 Using your module

      +

      34.2.5 Using your module

      @@ -632,7 +639,7 @@ system configuration (this requires root access and you will need to read the man pages).

      -

      32.2.6 Compilation of C++ extensions

      +

      34.2.6 Compilation of C++ extensions

      @@ -724,7 +731,7 @@ erratic program behavior. If working with lots of software components, you might want to investigate using a more formal standard such as COM.

      -

      32.2.7 Compiling for 64-bit platforms

      +

      34.2.7 Compiling for 64-bit platforms

      @@ -761,7 +768,7 @@ and -m64 allow you to choose the desired binary format for your python extension.

      -

      32.2.8 Building Python Extensions under Windows

      +

      34.2.8 Building Python Extensions under Windows

      @@ -870,7 +877,7 @@ SWIG Wiki.

      -

      32.3 A tour of basic C/C++ wrapping

      +

      34.3 A tour of basic C/C++ wrapping

      @@ -879,7 +886,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.

      -

      32.3.1 Modules

      +

      34.3.1 Modules

      @@ -892,7 +899,7 @@ module name, make sure you don't use the same name as a built-in Python command or standard module name.

      -

      32.3.2 Functions

      +

      34.3.2 Functions

      @@ -916,7 +923,7 @@ like you think it does: >>> -

      32.3.3 Global variables

      +

      34.3.3 Global variables

      @@ -1054,7 +1061,7 @@ that starts with a leading underscore. SWIG does not create cvar if there are no global variables in a module.

      -

      32.3.4 Constants and enums

      +

      34.3.4 Constants and enums

      @@ -1094,7 +1101,7 @@ other object. Unfortunately, there is no easy way for SWIG to generate code that prevents this. You will just have to be careful.

      -

      32.3.5 Pointers

      +

      34.3.5 Pointers

      @@ -1235,7 +1242,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.

      -

      32.3.6 Structures

      +

      34.3.6 Structures

      @@ -1424,7 +1431,7 @@ everything works just like you would expect. For example: -

      32.3.7 C++ classes

      +

      34.3.7 C++ classes

      @@ -1513,7 +1520,7 @@ they are accessed through cvar like this: -

      32.3.8 C++ inheritance

      +

      34.3.8 C++ inheritance

      @@ -1568,7 +1575,7 @@ then the function spam() accepts Foo * or a pointer to any cla It is safe to use multiple inheritance with SWIG.

      -

      32.3.9 Pointers, references, values, and arrays

      +

      34.3.9 Pointers, references, values, and arrays

      @@ -1629,7 +1636,7 @@ treated as a returning value, and it will follow the same allocation/deallocation process.

      -

      32.3.10 C++ overloaded functions

      +

      34.3.10 C++ overloaded functions

      @@ -1752,7 +1759,7 @@ first declaration takes precedence. Please refer to the "SWIG and C++" chapter for more information about overloading.

      -

      32.3.11 C++ operators

      +

      34.3.11 C++ operators

      @@ -1841,7 +1848,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.

      -

      32.3.12 C++ namespaces

      +

      34.3.12 C++ namespaces

      @@ -1908,7 +1915,7 @@ utilizes thousands of small deeply nested namespaces each with identical symbol names, well, then you get what you deserve.

      -

      32.3.13 C++ templates

      +

      34.3.13 C++ templates

      @@ -1962,7 +1969,7 @@ Some more complicated examples will appear later.

      -

      32.3.14 C++ Smart Pointers

      +

      34.3.14 C++ Smart Pointers

      @@ -2046,151 +2053,16 @@ simply use the __deref__() method. For example: - -

      32.3.15 C++ Reference Counted Objects (ref/unref)

      +

      34.3.15 C++ reference counted objects

      -Another usual idiom in C++ is the use of reference counted -objects. Consider for example: - -

      -
      -class RCObj  {
      -  // implement the ref counting mechanism
      -  int add_ref();
      -  int del_ref();
      -  int ref_count();
      -
      -public:
      -  virtual ~RCObj() = 0;
      -
      -  int ref() const {
      -    return add_ref();
      -  }
      -
      -  int unref() const   {
      -    if (ref_count() == 0 || del_ref() == 0 ) {
      -	delete this;
      -	return 0;
      -      } 
      -    return ref_count();
      -  }
      -};
      -
      -
      -class A : RCObj {
      -public:
      -  A();
      -  int foo();
      -};
      -
      -
      -class B {
      -  A *_a;
      -
      -public:
      -  B(A *a) : _a(a) { 
      -    a->ref(); 
      -  }
      -
      -  ~B() { 
      -    a->unref(); 
      -  }
      -};
      -
      -int main() {
      -  A *a  = new A();
      -  a->ref();           // 'a' is ref here
      -
      -  B *b1 = new B(a);   // 'a' is ref here
      -  if (1 + 1 == 2) {
      -    B *b2 = new B(a); // 'a' is ref here
      -    delete b2;        // 'a' is unref, but not deleted   
      -  }
      -
      -  delete b1;          // 'a' is unref, but not deleted   
      -  a->unref();         // 'a' is unref and deleted
      -}
      -
      -
      - -

      -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 an Reference Counted -Object 'RCObj', which implements the ref/unref idiom. -

      - -

      -To tell SWIG that 'RCObj' and all its derived classes are reference -counted objects, you use the "ref" and "unref" features. -For example: +The C++ reference counted objects section contains +Python examples of memory management using referencing counting.

      -
      -
      -%module example
      -...
      -
      -%feature("ref")   RCObj "$this->ref();"
      -%feature("unref") RCObj "$this->unref();"
      -
      -%include "rcobj.h"
      -%include "A.h"
      -...
      -
      -
      - -

      -where the code passed to the "ref" and "unref" features will be -executed as needed whenever a new object is passed to python, or when -python tries to release the shadow object instance, respectively. -

      - -

      -In the python side, the use of a reference counted object is not -different than any other regular instance: -

      - -
      -
      -def create_A():
      -  a = A()         # SWIG ref 'a' (new object is passed to python)
      -  b1 = B(a)       # C++  ref 'a'
      -  if 1 + 1 == 2:
      -     b2 = B(a)    # C++ ref 'a'
      -  return a        # 'b1' and 'b2' are released, C++ unref 'a' twice
      -
      -a = create_A()   
      -exit              # 'a' is released, SWIG unref 'a'
      -
      -
      - -

      -Note that the user doesn't explicitly need to call 'a->ref()' nor 'a->unref()' -(as neither 'delete a'). Instead, SWIG take cares of executing the "ref" -and "unref" codes as needed. If the user doesn't specify the -"ref/unref" features, SWIG will produce a code equivalent to define -them as: -

      - -
      -
      -%feature("ref")   ""
      -%feature("unref") "delete $this;"
      -
      -
      - -

      -In other words, SWIG will not do anything special when a new object -is passed to python, and it will always 'delete' the object when -python releases the proxy instance. -

      - - -

      32.4 Further details on the Python class interface

      +

      34.4 Further details on the Python class interface

      @@ -2203,7 +2075,17 @@ of low-level details were omitted. This section provides a brief overview of how the proxy classes work.

      -

      32.4.1 Proxy classes

      +

      New in SWIG version 2.0.4: +The use of Python proxy classes has performance implications that may be +unacceptable for a high-performance library. The new -builtin +option instructs SWIG to forego the use of proxy classes, and instead +create wrapped types as new built-in Python types. When this option is used, +the following section ("Proxy classes") does not apply. Details on the use of +the -builtin option are in the Built-in Types +section. +

      + +

      34.4.1 Proxy classes

      @@ -2292,9 +2174,325 @@ 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).

      -

      32.4.2 Memory management

      +

      34.4.2 Built-in Types

      +

      +The -builtin option provides a significant performance improvement +in the wrapped code. To understand the difference between proxy classes +and built-in types, let's take a look at what a wrapped object looks like +under both circumstances. +

      + +

      When proxy classes are used, each wrapped object in python is an instance +of a pure python class. As a reminder, here is what the __init__ method looks +like in a proxy class: +

      + +
      +
      +class Foo(object):
      +     def __init__(self):
      +         self.this = _example.new_Foo()
      +         self.thisown = 1
      +
      +
      + +

      When a Foo instance is created, the call to _example.new_Foo() +creates a new C++ Foo instance; wraps that C++ instance inside an instance of +a python built-in type called SwigPyObject; and stores the SwigPyObject +instance in the 'this' field of the python Foo object. Did you get all that? So, the +python Foo object is composed of three parts:

      + +
        +
      • The python Foo instance, which contains...
      • +
      • ... an instance of struct SwigPyObject, which contains...
      • +
      • ... a C++ Foo instance
      • +
      + +

      When -builtin is used, the pure python layer is stripped off. Each +wrapped class is turned into a new python built-in type which inherits from +SwigPyObject, and SwigPyObject instances are returned directly +from the wrapped methods. For more information about python built-in extensions, +please refer to the python documentation:

      + +

      http://docs.python.org/extending/newtypes.html

      + +

      34.4.2.1 Limitations

      + + +

      Use of the -builtin option implies a couple of limitations: +

        +
      • python version support:

        +
          +
        • Versions 2.5 and up are fully supported
        • +
        • Versions 2.3 and 2.4 are mostly supported; there are problems with director classes and/or sub-classing a wrapped type in python.
        • +
        • Versions older than 2.3 are not supported.
        • +
        +
      • +
      • Some legacy syntax is no longer supported; in particular:

        +
          +
        • The functional interface is no longer exposed. For example, you may no longer call Whizzo.new_CrunchyFrog(). Instead, you must use Whizzo.CrunchyFrog().
        • +
        • Static member variables are no longer accessed through the 'cvar' field (e.g., Dances.cvar.FishSlap). + They are instead accessed in the idiomatic way (Dances.FishSlap).
        • +
        +
      • +
      • Wrapped types may not be raised as python exceptions. Here's why: the python internals expect that all sub-classes of Exception will have this struct layout:

        + +
        +
        +typedef struct {
        +    PyObject_HEAD
        +    PyObject *dict;
        +    PyObject *args;
        +    PyObject *message;
        +} PyBaseExceptionObject;
        +
        +
        + +

        But swig-generated wrappers expect that all swig-wrapped classes will have this struct layout:

        + +
        +
        +typedef struct {
        +    PyObject_HEAD
        +    void *ptr;
        +    swig_type_info *ty;
        +    int own;
        +    PyObject *next;
        +    PyObject *dict;
        +} SwigPyObject;
        +
        +
        + +

        There are workarounds for this. For example, if you wrap this class: + +

        +
        +class MyException {
        +public:
        +    MyException (const char *msg_);
        +    ~MyException ();
        +
        +    const char *what () const;
        +
        +private:
        +    char *msg;
        +};
        +
        +
        + +

        ... you can define this python class, which may be raised as an exception:

        + +
        +
        +class MyPyException (Exception) :
        +    def __init__(self, msg, *args) :
        +        Exception.__init__(self, *args)
        +        self.myexc = MyException(msg)
        +    def what (self) :
        +        return self.myexc.what()
        +
        +
        +
      • +
      • Reverse binary operators (e.g., __radd__) are not supported.

        +

        To illustrate this point, if you have a wrapped class called MyString, +and you want to use instances of MyString interchangeably with native python +strings, you can define an 'operator+ (const char*)' method :

        + +
        +
        +class MyString {
        +public:
        +    MyString (const char *init);
        +    MyString operator+ (const char *other) const;
        +    ...
        +};
        +
        +
        + +

        +SWIG will automatically create an operator overload in python that will allow this: +

        + +
        +
        +from MyModule import MyString
        +
        +mystr = MyString("No one expects")
        +episode = mystr + " the Spanish Inquisition"
        +
        +
        + +

        +This works because the first operand (mystr) defines a way +to add a native string to itself. However, the following will not work: +

        + +
        +
        +from MyModule import MyString
        +
        +mystr = MyString("Parrot")
        +episode = "Dead " + mystr
        +
        +
        + +

        +The above code fails, because the first operand -- a native python string -- +doesn't know how to add an instance of MyString to itself. +

        +
      • + +
      • If you have multiple SWIG modules that share type information (more info), +the -builtin option requires a bit of extra discipline to ensure that base classes are initialized before derived classes. Specifically:

        +
          +
        • There must be an unambiguous dependency graph for the modules.

        • +
        • Module dependencies must be explicitly stated with %import statements in the SWIG interface file.

          +
        + +

        As an example, suppose module A has this interface in A.i :

        + +
        +%module "A";
        +
        +class Base {
        +...
        +};
        +
        + +

        If you want to wrap another module containing a class that inherits from A, this is how it would look :

        + +
        +%module "B";
        +
        +%import "A.i"
        +
        +class Derived : public Base {
        +...
        +};
        +
        + +

        The import "A.i" statement is required, because module B depends on module A.

        + +

        As long as you obey these requirements, your python code may import the modules in any order :

        + +
        +import B
        +import A
        +
        +assert(issubclass(B.Derived, A.Base))
        +
        +
      • +
      + +

      34.4.2.2 Operator overloads -- use them!

      + + +

      The entire justification for the -builtin option is improved +performance. To that end, the best way to squeeze maximum performance out +of your wrappers is to use operator overloads. +Named method dispatch is slow in python, even when compared to other scripting languages. +However, python built-in types have a large number of "slots", +analogous to C++ operator overloads, which allow you to short-circuit named method dispatch +for certain common operations. +

      + +

      By default, SWIG will translate most C++ arithmetic operator overloads into python +slot entries. For example, suppose you have this class: + +

      +
      +class Twit {
      +public:
      +    Twit operator+ (const Twit& twit) const;
      +
      +    // Forward to operator+
      +    Twit add (const Twit& twit) const
      +    { return *this + twit; }
      +};
      +
      +
      + +

      SWIG will automatically register operator+ as a python slot operator for addition. You may write python code like this:

      + +
      +
      +from MyModule import Twit
      +
      +nigel = Twit()
      +emily = Twit()
      +percival = nigel + emily
      +percival = nigel.add(emily)
      +
      +
      + +

      The last two lines of the python code are equivalent, +but the line that uses the '+' operator is much faster. +

      + +

      In-place operators (e.g., operator+=) and comparison operators +(operator==, operator<, etc.) are also converted to python +slot operators. For a complete list of C++ operators that are +automatically converted to python slot operators, refer to the file +python/pyopers.swig in the SWIG library. +

      + +

      There are other very useful python slots that you +may explicitly define using %feature directives. For example, +suppose you want to use instances of a wrapped class as keys in a native python +dict. That will work as long as you define a hash function for +instances of your class, and use it to define the python tp_hash +slot: +

      + +
      +
      +%feature("python:slot", "tp_hash", functype="hashfunc") Cheese::cheeseHashFunc;
      +
      +class Cheese {
      +public:
      +    Cheese (const char *name);
      +    long cheeseHashFunc () const;
      +};
      +
      +
      + +

      This will allow you to write python code like this:

      + +
      +
      +from my MyPackage import Cheese
      +
      +inventory = {
      +    Cheese("cheddar") : 0,
      +    Cheese("gouda") : 0,
      +    Cheese("camembert") : 0
      +}
      +
      +
      + +

      Because you defined the tp_hash slot, Cheese objects may +be used as hash keys; and when the cheeseHashFunc method is invoked +by a python dict, it will not go through named method dispatch. +A more detailed discussion about %feature("python:slot") can be found +in the file python/pyopers.swig in the SWIG library. +You can read about all of the available python slots here:

      + +

      http://docs.python.org/c-api/typeobj.html

      + +

      You may override (almost) all of the slots defined in the PyTypeObject, +PyNumberMethods, PyMappingMethods, PySequenceMethods, and PyBufferProcs +structs. +

      + + +

      34.4.3 Memory management

      + + +

      NOTE: Although this section refers to proxy objects, everything here also applies +when the -builtin option is used.

      +

      Associated with proxy object, is an ownership flag .thisown The value of this flag determines who is responsible for deleting the underlying C++ object. If set to 1, @@ -2484,7 +2682,7 @@ It is also possible to deal with situations like this using typemaps--an advanced topic discussed later.

      -

      32.4.3 Python 2.2 and classic classes

      +

      34.4.4 Python 2.2 and classic classes

      @@ -2521,7 +2719,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).

      -

      32.5 Cross language polymorphism

      +

      34.5 Cross language polymorphism

      @@ -2555,7 +2753,7 @@ proxy classes, director classes, and C wrapper functions takes care of all the cross-language method routing transparently.

      -

      32.5.1 Enabling directors

      +

      34.5.1 Enabling directors

      @@ -2584,9 +2782,6 @@ globally, to specific classes, and to specific methods, like this: // generate directors for all virtual methods in class Foo %feature("director") Foo; - -// generate a director for just Foo::bar() -%feature("director") Foo::bar; @@ -2648,7 +2843,7 @@ class MyFoo(mymodule.Foo): -

      32.5.2 Director classes

      +

      34.5.2 Director classes

      @@ -2730,7 +2925,7 @@ so there is no need for the extra overhead involved with routing the calls through Python.

      -

      32.5.3 Ownership and object destruction

      +

      34.5.3 Ownership and object destruction

      @@ -2797,7 +2992,7 @@ deleting all the Foo pointers it contains at some point. Note that no hard references to the Foo objects remain in Python.

      -

      32.5.4 Exception unrolling

      +

      34.5.4 Exception unrolling

      @@ -2856,7 +3051,7 @@ Swig::DirectorMethodException is thrown, Python will register the exception as soon as the C wrapper function returns.

      -

      32.5.5 Overhead and code bloat

      +

      34.5.5 Overhead and code bloat

      @@ -2890,7 +3085,7 @@ directive) for only those methods that are likely to be extended in Python.

      -

      32.5.6 Typemaps

      +

      34.5.6 Typemaps

      @@ -2904,7 +3099,7 @@ need to be supported.

      -

      32.5.7 Miscellaneous

      +

      34.5.7 Miscellaneous

      @@ -2951,7 +3146,7 @@ methods that return const references.

      -

      32.6 Common customization features

      +

      34.6 Common customization features

      @@ -2964,7 +3159,7 @@ This section describes some common SWIG features that are used to improve your the interface to an extension module.

      -

      32.6.1 C/C++ helper functions

      +

      34.6.1 C/C++ helper functions

      @@ -3045,7 +3240,7 @@ hard to implement. It is possible to clean this up using Python code, typemaps, customization features as covered in later sections.

      -

      32.6.2 Adding additional Python code

      +

      34.6.2 Adding additional Python code

      @@ -3191,10 +3386,42 @@ public: +

      +Note that when the underlying C++ method is overloaded, there is only one proxy Python method +for multiple C++ methods. In this case, only one of parsed methods is examined +for the feature. You are better off specifying the feature without the argument list to ensure it will get used, +as it will then get attached to all the overloaded C++ methods. For example: +

      + +
      +
      +%module example
      +
      +// Add python code to bar()
      +
      +%pythonprepend Foo::bar %{
      +   #do something before C++ call
      +%}
      +
      +%pythonappend Foo::bar %{
      +   #do something after C++ call
      +%}
       
       
      +class Foo {
      +public:
      +    int bar(int x);
      +    int bar();
      +}
      +
      +
      -

      32.6.3 Class extension with %extend

      +

      +The same applies for overloaded constructors. +

      + + +

      34.6.3 Class extension with %extend

      @@ -3283,7 +3510,7 @@ Vector(12,14,16) in any way---the extensions only show up in the Python interface.

      -

      32.6.4 Exception handling with %exception

      +

      34.6.4 Exception handling with %exception

      @@ -3409,7 +3636,7 @@ The language-independent exception.i library file can also be used to raise exceptions. See the SWIG Library chapter.

      -

      32.7 Tips and techniques

      +

      34.7 Tips and techniques

      @@ -3419,7 +3646,7 @@ strings, binary data, and arrays. This chapter discusses the common techniques solving these problems.

      -

      32.7.1 Input and output parameters

      +

      34.7.1 Input and output parameters

      @@ -3632,7 +3859,7 @@ void foo(Bar *OUTPUT); may not have the intended effect since typemaps.i does not define an OUTPUT rule for Bar.

      -

      32.7.2 Simple pointers

      +

      34.7.2 Simple pointers

      @@ -3701,7 +3928,7 @@ If you replace %pointer_functions() by %pointer_class(type,name)SWIG Library chapter for further details.

      -

      32.7.3 Unbounded C Arrays

      +

      34.7.3 Unbounded C Arrays

      @@ -3763,7 +3990,7 @@ well suited for applications in which you need to create buffers, package binary data, etc.

      -

      32.7.4 String handling

      +

      34.7.4 String handling

      @@ -3832,7 +4059,7 @@ If you need to return binary data, you might use the also be used to extra binary data from arbitrary pointers.

      -

      32.8 Typemaps

      +

      34.8 Typemaps

      @@ -3849,7 +4076,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.

      -

      32.8.1 What is a typemap?

      +

      34.8.1 What is a typemap?

      @@ -3965,7 +4192,7 @@ parameter is omitted): -

      32.8.2 Python typemaps

      +

      34.8.2 Python typemaps

      @@ -4006,7 +4233,7 @@ a look at the SWIG library version 1.3.20 or so.

      -

      32.8.3 Typemap variables

      +

      34.8.3 Typemap variables

      @@ -4077,7 +4304,7 @@ properly assigned. The Python name of the wrapper function being created. -

      32.8.4 Useful Python Functions

      +

      34.8.4 Useful Python Functions

      @@ -4205,7 +4432,7 @@ write me -

      32.9 Typemap Examples

      +

      34.9 Typemap Examples

      @@ -4214,7 +4441,7 @@ might look at the files "python.swg" and "typemaps.i" in the SWIG library.

      -

      32.9.1 Converting Python list to a char **

      +

      34.9.1 Converting Python list to a char **

      @@ -4294,7 +4521,7 @@ memory allocation is used to allocate memory for the array, the the C function.

      -

      32.9.2 Expanding a Python object into multiple arguments

      +

      34.9.2 Expanding a Python object into multiple arguments

      @@ -4373,7 +4600,7 @@ to supply the argument count. This is automatically set by the typemap code. F -

      32.9.3 Using typemaps to return arguments

      +

      34.9.3 Using typemaps to return arguments

      @@ -4462,7 +4689,7 @@ function can now be used as follows: >>> -

      32.9.4 Mapping Python tuples into small arrays

      +

      34.9.4 Mapping Python tuples into small arrays

      @@ -4511,7 +4738,7 @@ array, such an approach would not be recommended for huge arrays, but for small structures, this approach works fine.

      -

      32.9.5 Mapping sequences to C arrays

      +

      34.9.5 Mapping sequences to C arrays

      @@ -4592,7 +4819,7 @@ static int convert_darray(PyObject *input, double *ptr, int size) { %} %typemap(in) double [ANY](double temp[$1_dim0]) { - if (!convert_darray($input,temp,$1_dim0))) { + if (!convert_darray($input,temp,$1_dim0)) { return NULL; } $1 = &temp[0]; @@ -4600,7 +4827,7 @@ static int convert_darray(PyObject *input, double *ptr, int size) { -

      32.9.6 Pointer handling

      +

      34.9.6 Pointer handling

      @@ -4697,7 +4924,7 @@ class object (if applicable). -

      32.10 Docstring Features

      +

      34.10 Docstring Features

      @@ -4725,7 +4952,7 @@ of your users much simpler.

      -

      32.10.1 Module docstring

      +

      34.10.1 Module docstring

      @@ -4759,7 +4986,7 @@ layout of controls on a panel, etc. to be loaded from an XML file." -

      32.10.2 %feature("autodoc")

      +

      34.10.2 %feature("autodoc")

      @@ -4783,14 +5010,15 @@ introspection, then life is good once more. which when attached to a node in the parse tree will cause a docstring to be generated that includes the name of the function, parameter names, default values if any, and return type if any. There are also -three options for autodoc controlled by the value given to the -feature, described below. +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. -

      32.10.2.1 %feature("autodoc", "0")

      +

      34.10.2.1 %feature("autodoc", "0")

      -When the "0" option is given then the types of the parameters will +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:

      @@ -4815,18 +5043,19 @@ def function_name(*args, **kwargs): -

      32.10.2.2 %feature("autodoc", "1")

      +

      34.10.2.2 %feature("autodoc", "1")

      -When the "1" option is used then the parameter types will be +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. Pointer, reference and const info is removed, -%rename's are evaluated, etc. (This is not always -successful, but works most of the time. See the next section for what -to do when it doesn't.) Given the example above, then turning on the -parameter types with the "1" option will result in Python code like +user. Pointer, reference and const info is removed if the associated type +is has an associated Python type (%rename's are thus shown correctly). +This works most of the time, otherwise a C/C++ type will be used. +See the next section for the "docstring" feature for tweaking the docstrings to your liking. +Given the example above, then turning on the +parameter types with level "1" will result in Python code like this:

      @@ -4839,8 +5068,92 @@ def function_name(*args, **kwargs): +

      34.10.2.3 %feature("autodoc", "2")

      -

      32.10.2.3 %feature("autodoc", "docstring")

      + +

      +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: +

      + +
      +
      +def function_name(*args, **kwargs):
      +    """
      +    function_name(x, y, foo=None, bar=None) -> bool
      +
      +    Parameters:
      +        x: int
      +        y: int
      +        foo: Foo *
      +        bar: Bar *
      +
      +    """
      +    ...
      +
      +
      + +

      +Note that the documentation for each parameter is sourced from the "doc" typemap which by default shows the +C/C++ type rather than the simplified Python type name described earlier for level "1". +Typemaps can of course change the output for any particular type, for example the int x parameter: +

      + +
      +
      +%feature("autodoc", "2");
      +%typemap("doc") int x "$1_name (C++ type: $1_type) -- Input $1_name dimension"
      +bool function_name(int x, int y, Foo* foo=NULL, Bar* bar=NULL);
      +
      +
      + +

      +resulting in +

      + +
      +
      +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 *
      +
      +    """
      +
      +
      + +

      34.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 generated code will be: +

      + +
      +
      +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 *
      +
      +    """
      +    ...
      +
      +
      + + +

      34.10.2.5 %feature("autodoc", "docstring")

      @@ -4859,7 +5172,7 @@ void GetPosition(int* OUTPUT, int* OUTPUT); -

      32.10.3 %feature("docstring")

      +

      34.10.3 %feature("docstring")

      @@ -4891,7 +5204,7 @@ with more than one line. -

      32.11 Python Packages

      +

      34.11 Python Packages

      @@ -4918,7 +5231,7 @@ and also in base class declarations, etc. if the package name is different than its own.

      -

      32.12 Python 3 Support

      +

      34.12 Python 3 Support

      @@ -4945,7 +5258,7 @@ The following are Python 3.0 new features that are currently supported by SWIG.

      -

      32.12.1 Function annotation

      +

      34.12.1 Function annotation

      @@ -4954,7 +5267,7 @@ SWIG is able to generate proxy method definitions like this:

      -  def foo(self, bar : "int" = 0) -> "void" : ...
      +  def foo(self, bar : "int"=0) -> "void" : ...
       

      @@ -4963,7 +5276,7 @@ still could be generated:

      -  def foo(self, bar = 0): ...
      +  def foo(self, bar=0): ...
       

      @@ -4974,10 +5287,11 @@ all overloaded functions share the same function in SWIG generated proxy class.

      -For detailed usage of function annotation, see PEP 3107. +For detailed usage of function annotation, see +PEP 3107.

      -

      32.12.2 Buffer interface

      +

      34.12.2 Buffer interface

      @@ -5129,7 +5443,7 @@ modify the buffer. -

      32.12.3 Abstract base classes

      +

      34.12.3 Abstract base classes

      @@ -5166,7 +5480,8 @@ used to define an abstract base class for your own C++ class:

      -For details of abstract base class, please see PEP 3119. +For details of abstract base class, please see +PEP 3119.

      diff --git a/Doc/Manual/Ruby.html b/Doc/Manual/Ruby.html index b61ded8e5..47cf4f303 100644 --- a/Doc/Manual/Ruby.html +++ b/Doc/Manual/Ruby.html @@ -1,32 +1,13 @@ - - - - - - - - - - - - - - SWIG and Ruby + - - - - - - -

      33 SWIG and Ruby

      +

      36 SWIG and Ruby

        @@ -167,7 +148,7 @@ -

        33.1 Preliminaries

        +

        36.1 Preliminaries

        SWIG 1.3 is known to work with Ruby versions 1.6 and later. @@ -190,7 +171,7 @@ of Ruby.

        -

        33.1.1 Running SWIG

        +

        36.1.1 Running SWIG

        To build a Ruby module, run SWIG using the -ruby @@ -244,7 +225,7 @@ to compile this file and link it with the rest of your program.

        -

        33.1.2 Getting the right header files

        +

        36.1.2 Getting the right header files

        In order to compile the wrapper code, the compiler needs the ruby.h @@ -255,7 +236,9 @@ header file. This file is usually contained in a directory such as

        -
        /usr/lib/ruby/1.8/x86_64-linux-gnu/ruby.h
        /usr/local/lib/ruby/1.6/i686-linux/ruby.h
        +
        /usr/lib/ruby/1.8/x86_64-linux-gnu/ruby.h
        +/usr/local/lib/ruby/1.6/i686-linux/ruby.h
        +
        @@ -276,7 +259,10 @@ installed, you can run Ruby to find out. For example:

        -
        $ 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 .
        +
        $ 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 .
        +
        @@ -288,7 +274,7 @@ installed, you can run Ruby to find out. For example:

        -

        33.1.3 Compiling a dynamic module

        +

        36.1.3 Compiling a dynamic module

        Ruby extension modules are typically compiled into shared @@ -324,16 +310,7 @@ looks like the following:

        - - - -
        require 'mkmf'
        create_makefile('example')
        - - - - -
        @@ -401,7 +378,12 @@ can add this:

        -
        open("Makefile", "a") { |mf|
        puts <<EOM
        # Your make rules go here
        EOM
        }
        +
        open("Makefile", "a") { |mf|
        + puts <<EOM
        + # Your make rules go here
        + EOM
        +}
        +
        @@ -416,7 +398,8 @@ can add this:

        to the end of the extconf.rb file. If for some reason you don't want to use the standard approach, you'll need to determine the correct compiler and linker flags for your build -platform. For example, a typical sequence of commands for the Linux +platform. For example, assuming you have code you need to link to in a file +called example.c, a typical sequence of commands for the Linux operating system would look something like this:

        @@ -424,7 +407,10 @@ 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 -shared example.o example_wrap.o -o example.so +
        $ swig -ruby example.i
        +$ gcc -c example.c
        +$ gcc -c example_wrap.c -I/usr/local/lib/ruby/1.6/i686-linux 
        +$ gcc -shared example.o example_wrap.o -o example.so
         
        @@ -443,7 +429,7 @@ manual pages for your compiler and linker to determine the correct set of options. You might also check the SWIG Wiki for additional information.

        -

        33.1.4 Using your module

        +

        36.1.4 Using your module

        Ruby module names must be capitalized, @@ -456,7 +442,12 @@ module is imported by requiring the etc feature:

        -
        # The feature name begins with a lowercase letter...
        require 'etc'

        # ... but the module name begins with an uppercase letter
        puts "Your login name: #{Etc.getlogin}"
        +
        # The feature name begins with a lowercase letter...
        +require 'etc'
        +
        +# ... but the module name begins with an uppercase letter
        +puts "Your login name: #{Etc.getlogin}"
        +
        @@ -498,7 +489,7 @@ begins with:

        -

        33.1.5 Static linking

        +

        36.1.5 Static linking

        An alternative approach to dynamic linking is to rebuild the @@ -519,7 +510,7 @@ finally rebuilding Ruby.

        -

        33.1.6 Compilation of C++ extensions

        +

        36.1.6 Compilation of C++ extensions

        On most machines, C++ extension modules should be linked @@ -571,7 +562,7 @@ extension, e.g.

        -

        33.2 Building Ruby Extensions under Windows 95/NT

        +

        36.2 Building Ruby Extensions under Windows 95/NT

        Building a SWIG extension to Ruby under Windows 95/NT is @@ -610,7 +601,7 @@ files.

        -

        33.2.1 Running SWIG from Developer Studio

        +

        36.2.1 Running SWIG from Developer Studio

        If you are developing your application within Microsoft @@ -752,7 +743,7 @@ directory, then run the Ruby script from the DOS/Command prompt:

        -

        33.3 The Ruby-to-C/C++ Mapping

        +

        36.3 The Ruby-to-C/C++ Mapping

        This section describes the basics of how SWIG maps C or C++ @@ -762,7 +753,7 @@ declarations in your SWIG interface files to Ruby constructs.

        -

        33.3.1 Modules

        +

        36.3.1 Modules

        The SWIG %module directive specifies @@ -931,7 +922,7 @@ Ruby's built-in names.

        -

        33.3.2 Functions

        +

        36.3.2 Functions

        Global functions are wrapped as Ruby module methods. For @@ -994,7 +985,7 @@ module that can be used like so:

        -

        33.3.3 Variable Linking

        +

        36.3.3 Variable Linking

        C/C++ global variables are wrapped as a pair of singleton @@ -1094,7 +1085,7 @@ effect until it is explicitly disabled using %mutable. -

        33.3.4 Constants

        +

        36.3.4 Constants

        C/C++ constants are wrapped as module constants initialized @@ -1138,7 +1129,7 @@ constant values, e.g.

        -

        33.3.5 Pointers

        +

        36.3.5 Pointers

        "Opaque" pointers to arbitrary C/C++ types (i.e. types that @@ -1190,7 +1181,7 @@ the Ruby nil object.

        -

        33.3.6 Structures

        +

        36.3.6 Structures

        C/C++ structs are wrapped as Ruby classes, with accessor @@ -1365,7 +1356,7 @@ pointers. For example,

        -

        33.3.7 C++ classes

        +

        36.3.7 C++ classes

        Like structs, C++ classes are wrapped by creating a new Ruby @@ -1451,7 +1442,7 @@ class. -

        33.3.8 C++ Inheritance

        +

        36.3.8 C++ Inheritance

        The SWIG type-checker is fully aware of C++ inheritance. @@ -1682,7 +1673,7 @@ Typing").

        -

        33.3.9 C++ Overloaded Functions

        +

        36.3.9 C++ Overloaded Functions

        C++ overloaded functions, methods, and constructors are @@ -1882,7 +1873,7 @@ and C++" chapter for more information about overloading.

        -

        33.3.10 C++ Operators

        +

        36.3.10 C++ Operators

        For the most part, overloaded operators are handled @@ -1963,7 +1954,7 @@ on operator overloading.

        -

        33.3.11 C++ namespaces

        +

        36.3.11 C++ namespaces

        SWIG is aware of C++ namespaces, but namespace names do not @@ -2039,7 +2030,7 @@ identical symbol names, well, then you get what you deserve.

        -

        33.3.12 C++ templates

        +

        36.3.12 C++ templates

        C++ templates don't present a huge problem for SWIG. However, @@ -2083,7 +2074,7 @@ directive. For example:

        -

        33.3.13 C++ Standard Template Library (STL)

        +

        36.3.13 C++ Standard Template Library (STL)

        On a related note, the standard SWIG library contains a @@ -2336,7 +2327,7 @@ chapter.

        -

        33.3.14 C++ STL Functors

        +

        36.3.14 C++ STL Functors

        Some containers in the STL allow you to modify their default @@ -2536,7 +2527,7 @@ b
        -

        33.3.15 C++ STL Iterators

        +

        36.3.15 C++ STL Iterators

        The STL is well known for the use of iterators.  There @@ -2733,7 +2724,7 @@ i
        ->> [3, 4, 5 ]

        +>> [3, 4, 5 ]
        @@ -2747,7 +2738,7 @@ i
        -

        33.3.16 C++ Smart Pointers

        +

        36.3.16 C++ Smart Pointers

        In certain C++ programs, it is common to use classes that @@ -2872,7 +2863,7 @@ method. For example:

        -

        33.3.17 Cross-Language Polymorphism

        +

        36.3.17 Cross-Language Polymorphism

        SWIG's Ruby module supports cross-language polymorphism @@ -2885,7 +2876,7 @@ using this feature with Ruby.

        -

        33.3.17.1 Exception Unrolling

        +

        36.3.17.1 Exception Unrolling

        Whenever a C++ director class routes one of its virtual @@ -2923,7 +2914,7 @@ caught here and a C++ exception is raised in its place.

        -

        33.4 Naming

        +

        36.4 Naming

        Ruby has several common naming conventions. Constants are @@ -3019,7 +3010,7 @@ planned to become the default option in future releases.

        -

        33.4.1 Defining Aliases

        +

        36.4.1 Defining Aliases

        It's a fairly common practice in the Ruby built-ins and @@ -3111,7 +3102,7 @@ Features") for more details).

        -

        33.4.2 Predicate Methods

        +

        36.4.2 Predicate Methods

        Ruby methods that return a boolean value and end in a @@ -3200,7 +3191,7 @@ Features") for more details).

        -

        33.4.3 Bang Methods

        +

        36.4.3 Bang Methods

        Ruby methods that modify an object in-place and end in an @@ -3264,7 +3255,7 @@ Features") for more details).

        -

        33.4.4 Getters and Setters

        +

        36.4.4 Getters and Setters

        Often times a C++ library will expose properties through @@ -3334,7 +3325,7 @@ methods to be exposed in Ruby as value and value=. -

        33.5 Input and output parameters

        +

        36.5 Input and output parameters

        A common problem in some C programs is handling parameters @@ -3585,10 +3576,10 @@ of %apply

        -

        33.6 Exception handling

        +

        36.6 Exception handling

        -

        33.6.1 Using the %exception directive

        +

        36.6.1 Using the %exception directive

        The SWIG %exception directive can be @@ -3683,7 +3674,7 @@ Features for more examples.

        -

        33.6.2 Handling Ruby Blocks

        +

        36.6.2 Handling Ruby Blocks

        One of the highlights of Ruby and most of its standard library @@ -3864,7 +3855,7 @@ RUBY_YIELD_SELF );

        For more information on typemaps, see Typemaps.

        -

        33.6.3 Raising exceptions

        +

        36.6.3 Raising exceptions

        There are three ways to raise exceptions from C++ code to @@ -4625,7 +4616,7 @@ the built-in Ruby exception types.

        -

        33.6.4 Exception classes

        +

        36.6.4 Exception classes

        Starting with SWIG 1.3.28, the Ruby module supports the %exceptionclass @@ -4683,7 +4674,7 @@ providing for a more natural integration between C++ code and Ruby code.

        -

        33.7 Typemaps

        +

        36.7 Typemaps

        This section describes how you can modify SWIG's default @@ -4706,7 +4697,7 @@ of the primitive C-Ruby interface.

        -

        33.7.1 What is a typemap?

        +

        36.7.1 What is a typemap?

        A typemap is nothing more than a code generation rule that is @@ -4935,7 +4926,7 @@ arguments. For example:

        -
        %typemap(in) (char *str, int len) {
        $1 = STR2CSTR($input);
        $2 = (int) RSTRING($input)->len;
        };

        int count(char c, char *str, int len);
        +
        %typemap(in) (char *str, int len) {
        $1 = StringValuePtr($input);
        $2 = (int) RSTRING($input)->len;
        };

        int count(char c, char *str, int len);
        @@ -4968,7 +4959,7 @@ to be used as follows (notice how the length parameter is omitted):

        -

        33.7.2 Typemap scope

        +

        36.7.2 Typemap scope

        Once defined, a typemap remains in effect for all of the @@ -5016,7 +5007,7 @@ where the class itself is defined. For example:

        -

        33.7.3 Copying a typemap

        +

        36.7.3 Copying a typemap

        A typemap is copied by using assignment. For example:

        @@ -5118,7 +5109,7 @@ rules as for -

        33.7.4 Deleting a typemap

        +

        36.7.4 Deleting a typemap

        A typemap can be deleted by simply defining no code. For @@ -5170,7 +5161,7 @@ typemaps immediately after the clear operation.

        -

        33.7.5 Placement of typemaps

        +

        36.7.5 Placement of typemaps

        Typemap declarations can be declared in the global scope, @@ -5254,7 +5245,7 @@ string -

        33.7.6 Ruby typemaps

        +

        36.7.6 Ruby typemaps

        The following list details all of the typemap methods that @@ -5264,7 +5255,7 @@ can be used by the Ruby module:

        -

        33.7.6.1  "in" typemap

        +

        36.7.6.1  "in" typemap

        Converts Ruby objects to input @@ -5507,7 +5498,7 @@ arguments to be specified. For example:

        -

        33.7.6.2 "typecheck" typemap

        +

        36.7.6.2 "typecheck" typemap

        The "typecheck" typemap is used to support overloaded @@ -5548,7 +5539,7 @@ on "Typemaps and Overloading."

        -

        33.7.6.3  "out" typemap

        +

        36.7.6.3  "out" typemap

        Converts return value of a C function @@ -5780,7 +5771,7 @@ version of the C datatype matched by the typemap. -

        33.7.6.4 "arginit" typemap

        +

        36.7.6.4 "arginit" typemap

        The "arginit" typemap is used to set the initial value of a @@ -5805,7 +5796,7 @@ applications. For example:

        -

        33.7.6.5 "default" typemap

        +

        36.7.6.5 "default" typemap

        The "default" typemap is used to turn an argument into a @@ -5847,7 +5838,7 @@ default argument wrapping.

        -

        33.7.6.6 "check" typemap

        +

        36.7.6.6 "check" typemap

        The "check" typemap is used to supply value checking code @@ -5871,7 +5862,7 @@ arguments have been converted. For example:

        -

        33.7.6.7 "argout" typemap

        +

        36.7.6.7 "argout" typemap

        The "argout" typemap is used to return values from arguments. @@ -6029,7 +6020,7 @@ some function like SWIG_Ruby_AppendOutput.

        -

        33.7.6.8 "freearg" typemap

        +

        36.7.6.8 "freearg" typemap

        The "freearg" typemap is used to cleanup argument data. It is @@ -6065,7 +6056,7 @@ abort prematurely.

        -

        33.7.6.9 "newfree" typemap

        +

        36.7.6.9 "newfree" typemap

        The "newfree" typemap is used in conjunction with the %newobject @@ -6096,7 +6087,7 @@ ownership and %newobject for further details.

        -

        33.7.6.10 "memberin" typemap

        +

        36.7.6.10 "memberin" typemap

        The "memberin" typemap is used to copy data from an @@ -6129,7 +6120,7 @@ other objects.

        -

        33.7.6.11 "varin" typemap

        +

        36.7.6.11 "varin" typemap

        The "varin" typemap is used to convert objects in the target @@ -6140,7 +6131,7 @@ This is implementation specific.

        -

        33.7.6.12 "varout" typemap

        +

        36.7.6.12 "varout" typemap

        The "varout" typemap is used to convert a C/C++ object to an @@ -6151,7 +6142,7 @@ This is implementation specific.

        -

        33.7.6.13 "throws" typemap

        +

        36.7.6.13 "throws" typemap

        The "throws" typemap is only used when SWIG parses a C++ @@ -6210,7 +6201,7 @@ handling with %exception section.

        -

        33.7.6.14 directorin typemap

        +

        36.7.6.14 directorin typemap

        Converts C++ objects in director @@ -6464,7 +6455,7 @@ referring to the class itself. -

        33.7.6.15 directorout typemap

        +

        36.7.6.15 directorout typemap

        Converts Ruby objects in director @@ -6527,49 +6518,16 @@ typemap.

    • - - - - - - - - - - - - - - - - - + + + + + + - - - - - - - - - - - - - - - - - - - - - + @@ -6724,7 +6682,7 @@ exception.
      -

      33.7.6.16 directorargout typemap

      +

      36.7.6.16 directorargout typemap

      Output argument processing in director @@ -6773,80 +6731,21 @@ $result = output_helper( $result, NUM2INT($1) );

      - - - - - - - - - - - - - - - - + + + + + - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - - - - - - - - - + - - - - - @@ -6964,7 +6863,7 @@ referring to the instance of the class itself -

      33.7.6.17 ret typemap

      +

      36.7.6.17 ret typemap

      Cleanup of function return values @@ -6974,7 +6873,7 @@ referring to the instance of the class itself -

      33.7.6.18 globalin typemap

      +

      36.7.6.18 globalin typemap

      Setting of C global variables @@ -6984,7 +6883,7 @@ referring to the instance of the class itself -

      33.7.7 Typemap variables

      +

      36.7.7 Typemap variables

      @@ -7094,7 +6993,7 @@ being created. -

      33.7.8 Useful Functions

      +

      36.7.8 Useful Functions

      When you write a typemap, you usually have to work directly @@ -7118,7 +7017,7 @@ across multiple languages.

      -

      33.7.8.1 C Datatypes to Ruby Objects

      +

      36.7.8.1 C Datatypes to Ruby Objects

      @@ -7174,7 +7073,7 @@ SWIG_From_float(float) -

      33.7.8.2 Ruby Objects to C Datatypes

      +

      36.7.8.2 Ruby Objects to C Datatypes

      Here, while the Ruby versions return the value directly, the SWIG @@ -7236,7 +7135,7 @@ Ruby_Format_TypeError( "$1_name", "$1_type","$symname", $argnum, $input

      - + @@ -7263,7 +7162,7 @@ Ruby_Format_TypeError( "$1_name", "$1_type","$symname", $argnum, $input -

      33.7.8.3 Macros for VALUE

      +

      36.7.8.3 Macros for VALUE

      RSTRING_LEN(str)

      @@ -7326,7 +7225,7 @@ Ruby_Format_TypeError( "$1_name", "$1_type","$symname", $argnum, $input -

      33.7.8.4 Exceptions

      +

      36.7.8.4 Exceptions

      void rb_raise(VALUE exception, const char *fmt, @@ -7493,7 +7392,7 @@ arguments are interpreted as with printf(). -

      33.7.8.5 Iterators

      +

      36.7.8.5 Iterators

      void rb_iter_break()

      @@ -7595,7 +7494,7 @@ VALUE), VALUE value)

      -

      33.7.9 Typemap Examples

      +

      36.7.9 Typemap Examples

      This section includes a few examples of typemaps. For more @@ -7606,7 +7505,7 @@ directory.

      -

      33.7.10 Converting a Ruby array to a char **

      +

      36.7.10 Converting a Ruby array to a char **

      A common problem in many C programs is the processing of @@ -7619,7 +7518,7 @@ Array instance to be used as a char ** object.

      -
      %module argv

      // This tells SWIG to treat char ** as a special case
      %typemap(in) char ** {
      /* Get the length of the array */
      int size = RARRAY($input)->len;
      int i;
      $1 = (char **) malloc((size+1)*sizeof(char *));
      /* Get the first element in memory */
      VALUE *ptr = RARRAY($input)->ptr;
      for (i=0; i < size; i++, ptr++)
      /* Convert Ruby Object String to char* */
      $1[i]= STR2CSTR(*ptr);
      $1[i]=NULL; /* End of list */
      }

      // This cleans up the char ** array created before
      // the function call

      %typemap(freearg) char ** {
      free((char *) $1);
      }

      // Now a test function
      %inline %{
      int print_args(char **argv) {
      int i = 0;
      while (argv[i]) {
      printf("argv[%d] = %s\n", i,argv[i]);
      i++;
      }
      return i;
      }
      %}

      +
      %module argv

      // This tells SWIG to treat char ** as a special case
      %typemap(in) char ** {
      /* Get the length of the array */
      int size = RARRAY($input)->len;
      int i;
      $1 = (char **) malloc((size+1)*sizeof(char *));
      /* Get the first element in memory */
      VALUE *ptr = RARRAY($input)->ptr;
      for (i=0; i < size; i++, ptr++)
      /* Convert Ruby Object String to char* */
      $1[i]= StringValuePtr(*ptr);
      $1[i]=NULL; /* End of list */
      }

      // This cleans up the char ** array created before
      // the function call

      %typemap(freearg) char ** {
      free((char *) $1);
      }

      // Now a test function
      %inline %{
      int print_args(char **argv) {
      int i = 0;
      while (argv[i]) {
      printf("argv[%d] = %s\n", i,argv[i]);
      i++;
      }
      return i;
      }
      %}

      @@ -7661,7 +7560,7 @@ after the execution of the C function.

      -

      33.7.11 Collecting arguments in a hash

      +

      36.7.11 Collecting arguments in a hash

      Ruby's solution to the "keyword arguments" capability of some @@ -7897,7 +7796,7 @@ equivalents and store them in our local C arrays:

      -
      %typemap(in) (int nattributes, const char **names, const int *values)
      (VALUE keys_arr, int i, VALUE key, VALUE val) {
      Check_Type($input, T_HASH);
      $1 = NUM2INT(rb_funcall($input, rb_intern("size"), 0, NULL));
      $2 = NULL;
      $3 = NULL;
      if ($1 > 0) {
      $2 = (char **) malloc($1*sizeof(char *));
      $3 = (int *) malloc($1*sizeof(int));
      keys_arr = rb_funcall($input, rb_intern("keys"), 0, NULL);
      for (i = 0; i < $1; i++) {
      key = rb_ary_entry(keys_arr, i);
      val = rb_hash_aref($input, key);
      Check_Type(key, T_STRING);
      Check_Type(val, T_FIXNUM);
      $2[i] = STR2CSTR(key);
      $3[i] = NUM2INT(val);

      }
      }
      }
      +
      %typemap(in) (int nattributes, const char **names, const int *values)
      (VALUE keys_arr, int i, VALUE key, VALUE val) {
      Check_Type($input, T_HASH);
      $1 = NUM2INT(rb_funcall($input, rb_intern("size"), 0, NULL));
      $2 = NULL;
      $3 = NULL;
      if ($1 > 0) {
      $2 = (char **) malloc($1*sizeof(char *));
      $3 = (int *) malloc($1*sizeof(int));
      keys_arr = rb_funcall($input, rb_intern("keys"), 0, NULL);
      for (i = 0; i < $1; i++) {
      key = rb_ary_entry(keys_arr, i);
      val = rb_hash_aref($input, key);
      Check_Type(key, T_STRING);
      Check_Type(val, T_FIXNUM);
      $2[i] = StringValuePtr(key);
      $3[i] = NUM2INT(val);

      }
      }
      }
      @@ -7940,7 +7839,7 @@ directory of the SWIG distribution.

      -

      33.7.12 Pointer handling

      +

      36.7.12 Pointer handling

      Occasionally, it might be necessary to convert pointer values @@ -8039,7 +7938,7 @@ For example:

      -

      33.7.12.1 Ruby Datatype Wrapping

      +

      36.7.12.1 Ruby Datatype Wrapping

      VALUE Data_Wrap_Struct(VALUE class, void @@ -8090,7 +7989,7 @@ and assigns that pointer to ptr.

      -

      33.7.13 Example: STL Vector to Ruby Array

      +

      36.7.13 Example: STL Vector to Ruby Array

      Another use for macros and type maps is to create a Ruby array @@ -8199,7 +8098,7 @@ the C++ Standard Template Library.
      -

      33.8 Docstring Features

      +

      36.8 Docstring Features

      @@ -8260,7 +8159,7 @@ generate ri documentation from a c wrap file, you could do:

      -

      33.8.1 Module docstring

      +

      36.8.1 Module docstring

      @@ -8311,7 +8210,7 @@ macro. For example: -

      33.8.2 %feature("autodoc")

      +

      36.8.2 %feature("autodoc")

      Since SWIG does know everything about the function it wraps, @@ -8340,7 +8239,7 @@ feature, described below. -

      33.8.2.1 %feature("autodoc", "0")

      +

      36.8.2.1 %feature("autodoc", "0")

      @@ -8388,7 +8287,7 @@ Then Ruby code like this will be generated: -

      33.8.2.2 %feature("autodoc", "1")

      +

      36.8.2.2 %feature("autodoc", "1")

      @@ -8420,7 +8319,7 @@ this: -

      33.8.2.3 %feature("autodoc", "2")

      +

      36.8.2.3 %feature("autodoc", "2")

      @@ -8436,7 +8335,7 @@ this: -

      33.8.2.4 %feature("autodoc", "3")

      +

      36.8.2.4 %feature("autodoc", "3")

      @@ -8464,7 +8363,7 @@ this: -

      33.8.2.5 %feature("autodoc", "docstring")

      +

      36.8.2.5 %feature("autodoc", "docstring")

      @@ -8492,7 +8391,7 @@ generated string. For example: -

      33.8.3 %feature("docstring")

      +

      36.8.3 %feature("docstring")

      @@ -8507,10 +8406,10 @@ docstring and they are output together.

      -

      33.9 Advanced Topics

      +

      36.9 Advanced Topics

      -

      33.9.1 Operator overloading

      +

      36.9.1 Operator overloading

      SWIG allows operator overloading with, by using the %extend @@ -9527,7 +9426,7 @@ parses the expression a != b as !(a == b). -

      33.9.2 Creating Multi-Module Packages

      +

      36.9.2 Creating Multi-Module Packages

      The chapter on Working @@ -9708,7 +9607,7 @@ initialized:

      -

      33.9.3 Specifying Mixin Modules

      +

      36.9.3 Specifying Mixin Modules

      The Ruby language doesn't support multiple inheritance, but @@ -9806,7 +9705,7 @@ Features") for more details).

      -

      33.10 Memory Management

      +

      36.10 Memory Management

      One of the most common issues in generating SWIG bindings for @@ -9853,7 +9752,7 @@ understanding of how the underlying library manages memory.

      -

      33.10.1 Mark and Sweep Garbage Collector

      +

      36.10.1 Mark and Sweep Garbage Collector

      Ruby uses a mark and sweep garbage collector. When the garbage @@ -9901,7 +9800,7 @@ this memory.

      -

      33.10.2 Object Ownership

      +

      36.10.2 Object Ownership

      As described above, memory management depends on clearly @@ -10098,7 +9997,38 @@ classes is:

      -
      /* File RubyOwnershipExample.i */

      %module RubyOwnershipExample

      %{
      #include "RubyOwnershipExample.h"
      %}

      class Foo
      {
      public:
      Foo();
      ~Foo();
      };

      class Bar
      {
      Foo *foo_;
      public:
      Bar();
      ~Bar();
      Foo* get_foo();

      %newobject get_new_foo;
      Foo* get_new_foo();

      %apply SWIGTYPE *DISOWN {Foo *foo};
      void set_foo(Foo *foo);
      %clear Foo *foo;
      };

      +
      /* File RubyOwnershipExample.i */
      +
      +%module RubyOwnershipExample
      +
      +%{
      +#include "RubyOwnershipExample.h"
      +%}
      +
      +class Foo
      +{
      +public:
      + Foo();
      + ~Foo();
      +};
      +
      +class Bar
      +{
      + Foo *foo_;
      +public:
      + Bar();
      + ~Bar();
      + Foo* get_foo();
      +
      + %newobject get_new_foo;
      + Foo* get_new_foo();
      +
      + %apply SWIGTYPE *DISOWN {Foo *foo};
      + void set_foo(Foo *foo);
      + %clear Foo *foo;
      +};
      +
      +
      @@ -10128,7 +10058,7 @@ classes is:

      -

      33.10.3 Object Tracking

      +

      36.10.3 Object Tracking

      The remaining parts of this section will use the class library @@ -10165,7 +10095,35 @@ class library models a zoo and the animals it contains.

      -
      $ irb
      irb(main):001:0> require 'example'
      => true

      irb(main):002:0> tiger1 = Example::Animal.new("tiger1")
      => #<Example::Animal:0x2be3820>

      irb(main):004:0> tiger1.get_name()
      => "tiger1"

      irb(main):003:0> zoo = Example::Zoo.new()
      => #<Example::Zoo:0x2be0a60>

      irb(main):006:0> zoo.add_animal(tiger)
      => nil

      irb(main):007:0> zoo.get_num_animals()
      => 1

      irb(main):007:0> tiger2 = zoo.remove_animal(0)
      => #<Example::Animal:0x2bd4a18>

      irb(main):008:0> tiger2.get_name()
      => "tiger1"

      irb(main):009:0> tiger1.equal?(tiger2)
      => false

      +
      $ irb
      +irb(main):001:0> require 'example'
      +=> true
      +
      +irb(main):002:0> tiger1 = Example::Animal.new("tiger1")
      +=> #<Example::Animal:0x2be3820>
      +
      +irb(main):004:0> tiger1.get_name()
      +=> "tiger1"
      +
      +irb(main):003:0> zoo = Example::Zoo.new()
      +=> #<Example::Zoo:0x2be0a60>
      +
      +irb(main):006:0> zoo.add_animal(tiger)
      +=> nil
      +
      +irb(main):007:0> zoo.get_num_animals()
      +=> 1
      +
      +irb(main):007:0> tiger2 = zoo.remove_animal(0)
      +=> #<Example::Animal:0x2bd4a18>
      +
      +irb(main):008:0> tiger2.get_name()
      +=> "tiger1"
      +
      +irb(main):009:0> tiger1.equal?(tiger2)
      +=> false
      +
      +
      @@ -10192,7 +10150,16 @@ the same underlying C++ object. This can cause problems. For example:
      -
      irb(main):010:0> tiger1 = nil
      => nil

      irb(main):011:0> GC.start
      => nil

      irb(main):012:0> tiger2.get_name()
      (irb):12: [BUG] Segmentation fault

      +
      irb(main):010:0> tiger1 = nil
      +=> nil
      +
      +irb(main):011:0> GC.start
      +=> nil
      +
      +irb(main):012:0> tiger2.get_name()
      +(irb):12: [BUG] Segmentation fault
      +
      +
      @@ -10251,7 +10218,7 @@ class-by-class basis if needed. To fix the example above:

      -
      %module example

      %{
      #include "example.h"
      %}

      /* 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;

      %include "example.h"
      +
      %module example

      %{
      #include "example.h"
      %}

      /* 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;

      %include "example.h"
      @@ -10282,7 +10249,7 @@ class-by-class basis if needed. To fix the example above:

      -
      $ irb
      irb(main):001:0> require 'example'
      => true

      irb(main):002:0> tiger1 = Example::Animal.new("tiger1")
      => #<Example::Animal:0x2be37d8>

      irb(main):003:0> zoo = Example::Zoo.new()
      => #<Example::Zoo:0x2be0a18>

      irb(main):004:0> zoo.add_animal(tiger1)
      => nil

      irb(main):006:0> tiger2 = zoo.remove_animal(0)
      => #<Example::Animal:0x2be37d8>

      irb(main):007:0> tiger1.equal?(tiger2)
      => true

      irb(main):008:0> tiger1 = nil
      => nil

      irb(main):009:0> GC.start
      => nil

      irb(main):010:0> tiger.get_name()
      => "tiger1"
      irb(main):011:0>

      +
      $ irb
      irb(main):001:0> require 'example'
      => true

      irb(main):002:0> tiger1 = Example::Animal.new("tiger1")
      => #<Example::Animal:0x2be37d8>

      irb(main):003:0> zoo = Example::Zoo.new()
      => #<Example::Zoo:0x2be0a18>

      irb(main):004:0> zoo.add_animal(tiger1)
      => nil

      irb(main):006:0> tiger2 = zoo.remove_animal(0)
      => #<Example::Animal:0x2be37d8>

      irb(main):007:0> tiger1.equal?(tiger2)
      => true

      irb(main):008:0> tiger1 = nil
      => nil

      irb(main):009:0> GC.start
      => nil

      irb(main):010:0> tiger.get_name()
      => "tiger1"
      irb(main):011:0>

      @@ -10342,7 +10309,7 @@ methods.

      -

      33.10.4 Mark Functions

      +

      36.10.4 Mark Functions

      With a bit more testing, we see that our class library still @@ -10359,7 +10326,7 @@ has problems. For example:

      -
      $ irb
      irb(main):001:0> require 'example'
      => true

      irb(main):002:0> tiger1 = Example::Animal.new("tiger1")
      => #<Example::Animal:0x2bea6a8>

      irb(main):003:0> zoo = Example::Zoo.new()
      => #<Example::Zoo:0x2be7960>

      irb(main):004:0> zoo.add_animal(tiger1)
      => nil

      irb(main):007:0> tiger1 = nil
      => nil

      irb(main):007:0> GC.start
      => nil

      irb(main):005:0> tiger2 = zoo.get_animal(0)
      (irb):12: [BUG] Segmentation fault
      +
      $ irb
      irb(main):001:0> require 'example'
      => true

      irb(main):002:0> tiger1 = Example::Animal.new("tiger1")
      => #<Example::Animal:0x2bea6a8>

      irb(main):003:0> zoo = Example::Zoo.new()
      => #<Example::Zoo:0x2be7960>

      irb(main):004:0> zoo.add_animal(tiger1)
      => nil

      irb(main):007:0> tiger1 = nil
      => nil

      irb(main):007:0> GC.start
      => nil

      irb(main):005:0> tiger2 = zoo.get_animal(0)
      (irb):12: [BUG] Segmentation fault
      @@ -10407,7 +10374,7 @@ implementation is:

      -
      %module example

      %{
      #include "example.h"
      %}

      /* Keep track of mappings between C/C++ structs/classes
      and Ruby objects so we can implement a mark function. */
      %trackobjects;

      /* Specify the mark function */
      %markfunc Zoo "mark_Zoo";

      %include "example.h"

      %header %{

      static void mark_Zoo(void* ptr) {
      Zoo* zoo = (Zoo*) ptr;

      /* Loop over each object and tell the garbage collector
      that we are holding a reference to them. */
      int count = zoo->get_num_animals();

      for(int i = 0; i < count; ++i) {
      Animal* animal = zoo->get_animal(i);
      VALUE object = SWIG_RubyInstanceFor(animal);

      if (object != Qnil) {
      rb_gc_mark(object);
      }
      }
      }
      %}

      +
      %module example

      %{
      #include "example.h"
      %}

      /* Keep track of mappings between C/C++ structs/classes
      and Ruby objects so we can implement a mark function. */
      %trackobjects;

      /* Specify the mark function */
      %markfunc Zoo "mark_Zoo";

      %include "example.h"

      %header %{

      static void mark_Zoo(void* ptr) {
      Zoo* zoo = (Zoo*) ptr;

      /* Loop over each object and tell the garbage collector
      that we are holding a reference to them. */
      int count = zoo->get_num_animals();

      for(int i = 0; i < count; ++i) {
      Animal* animal = zoo->get_animal(i);
      VALUE object = SWIG_RubyInstanceFor(animal);

      if (object != Qnil) {
      rb_gc_mark(object);
      }
      }
      }
      %}

      @@ -10436,7 +10403,7 @@ test suite.

      -
      $ irb
      irb(main):002:0> tiger1=Example::Animal.new("tiger1")
      => #<Example::Animal:0x2be3bf8>

      irb(main):003:0> Example::Zoo.new()
      => #<Example::Zoo:0x2be1780>

      irb(main):004:0> zoo = Example::Zoo.new()
      => #<Example::Zoo:0x2bde9c0>

      irb(main):005:0> zoo.add_animal(tiger1)
      => nil

      irb(main):009:0> tiger1 = nil
      => nil

      irb(main):010:0> GC.start
      => nil
      irb(main):014:0> tiger2 = zoo.get_animal(0)
      => #<Example::Animal:0x2be3bf8>

      irb(main):015:0> tiger2.get_name()
      => "tiger1"
      irb(main):016:0>

      +
      $ irb
      irb(main):002:0> tiger1=Example::Animal.new("tiger1")
      => #<Example::Animal:0x2be3bf8>

      irb(main):003:0> Example::Zoo.new()
      => #<Example::Zoo:0x2be1780>

      irb(main):004:0> zoo = Example::Zoo.new()
      => #<Example::Zoo:0x2bde9c0>

      irb(main):005:0> zoo.add_animal(tiger1)
      => nil

      irb(main):009:0> tiger1 = nil
      => nil

      irb(main):010:0> GC.start
      => nil
      irb(main):014:0> tiger2 = zoo.get_animal(0)
      => #<Example::Animal:0x2be3bf8>

      irb(main):015:0> tiger2.get_name()
      => "tiger1"
      irb(main):016:0>

      @@ -10460,7 +10427,7 @@ test suite.

      -

      33.10.5 Free Functions

      +

      36.10.5 Free Functions

      By default, SWIG creates a "free" function that is called when @@ -10512,14 +10479,22 @@ directive, let's slightly change our example. Assume that the zoo object is responsible for freeing 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::

      +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;
      + }
      +}
      @@ -10538,7 +10513,29 @@ and the destructor should be updated as below::

      -
      $irb
      irb(main):002:0> require 'example'
      => true

      irb(main):003:0> zoo = Example::Zoo.new()
      => #<Example::Zoo:0x2be0fe8>

      irb(main):005:0> tiger1 = Example::Animal.new("tiger1")
      => #<Example::Animal:0x2bda760>

      irb(main):006:0> zoo.add_animal(tiger1)
      => nil

      irb(main):007:0> zoo = nil
      => nil

      irb(main):008:0> GC.start
      => nil

      irb(main):009:0> tiger1.get_name()
      (irb):12: [BUG] Segmentation fault

      +
      $irb
      +irb(main):002:0> require 'example'
      +=> true
      +
      +irb(main):003:0> zoo = Example::Zoo.new()
      +=> #<Example::Zoo:0x2be0fe8>
      +
      +irb(main):005:0> tiger1 = Example::Animal.new("tiger1")
      +=> #<Example::Animal:0x2bda760>
      +
      +irb(main):006:0> zoo.add_animal(tiger1)
      +=> nil
      +
      +irb(main):007:0> zoo = nil
      +=> nil
      +
      +irb(main):008:0> GC.start
      +=> nil
      +
      +irb(main):009:0> tiger1.get_name()
      +(irb):12: [BUG] Segmentation fault
      +
      +
      @@ -10571,7 +10568,49 @@ existing Ruby object to the destroyed C++ object and raise an exception.
      -
      %module example

      %{
      #include "example.h"
      %}

      /* Specify that ownership is transferred to the zoo
      when calling add_animal */
      %apply SWIGTYPE *DISOWN { Animal* animal };

      /* Track objects */
      %trackobjects;

      /* Specify the mark function */
      %freefunc Zoo "free_Zoo";

      %include "example.h"

      %header %{
      static void free_Zoo(void* ptr) {
      Zoo* zoo = (Zoo*) ptr;

      /* Loop over each animal */
      int count = zoo->get_num_animals();

      for(int i = 0; i < count; ++i) {
      /* Get an animal */
      Animal* animal = zoo->get_animal(i);

      /* Unlink the Ruby object from the C++ object */
      SWIG_RubyUnlinkObjects(animal);

      /* Now remove the tracking for this animal */
      SWIG_RubyRemoveTracking(animal);
      }

      /* Now call SWIG_RubyRemoveTracking for the zoo */
      SWIG_RubyRemoveTracking(ptr);

      /* Now free the zoo which will free the animals it contains */
      delete zoo;
      }
      %}
      +
      %module example
      +
      +%{
      +#include "example.h"
      +%}
      +
      +/* Specify that ownership is transferred to the zoo
      +	when calling add_animal */
      +%apply SWIGTYPE *DISOWN { Animal* animal };
      +
      +/* Track objects */
      +%trackobjects;
      +
      +/* Specify the mark function */
      +%freefunc Zoo "free_Zoo";
      +
      +%include "example.h"
      +
      +%header %{
      + static void free_Zoo(void* ptr) {
      + Zoo* zoo = (Zoo*) ptr;
      +
      + /* Loop over each animal */
      + int count = zoo->get_num_animals();
      +
      + for(int i = 0; i < count; ++i) {
      + /* Get an animal */
      + Animal* animal = zoo->get_animal(i);
      +
      + /* Unlink the Ruby object from the C++ object */
      + SWIG_RubyUnlinkObjects(animal);
      +
      + /* Now remove the tracking for this animal */
      + SWIG_RubyRemoveTracking(animal);
      + }
      +
      + /* Now call SWIG_RubyRemoveTracking for the zoo */
      + SWIG_RubyRemoveTracking(ptr);
      + 
      + /* Now free the zoo which will free the animals it contains */
      + delete zoo;
      + }
      +%} 
      @@ -10590,7 +10629,30 @@ existing Ruby object to the destroyed C++ object and raise an exception.
      -
      $irb
      irb(main):002:0> require 'example'
      => true

      irb(main):003:0> zoo = Example::Zoo.new()
      => #<Example::Zoo:0x2be0fe8>

      irb(main):005:0> tiger1 = Example::Animal.new("tiger1")
      => #<Example::Animal:0x2bda760>

      irb(main):006:0> zoo.add_animal(tiger1)
      => nil

      irb(main):007:0> zoo = nil
      => nil

      irb(main):008:0> GC.start
      => nil

      irb(main):009:0> tiger1.get_name()
      RuntimeError: This Animal * already released
      from (irb):10:in `get_name'
      from (irb):10
      irb(main):011:0>
      +
      $irb
      +irb(main):002:0> require 'example'
      +=> true
      +
      +irb(main):003:0> zoo = Example::Zoo.new()
      +=> #<Example::Zoo:0x2be0fe8>
      +
      +irb(main):005:0> tiger1 = Example::Animal.new("tiger1")
      +=> #<Example::Animal:0x2bda760>
      +
      +irb(main):006:0> zoo.add_animal(tiger1)
      +=> nil
      +
      +irb(main):007:0> zoo = nil
      +=> nil
      +
      +irb(main):008:0> GC.start
      +=> nil
      +
      +irb(main):009:0> tiger1.get_name()
      +RuntimeError: This Animal * already released
      + from (irb):10:in `get_name'
      + from (irb):10
      +irb(main):011:0>
      @@ -10615,7 +10677,7 @@ been freed, and thus raises a runtime exception.

      -

      33.10.6 Embedded Ruby and the C++ Stack

      +

      36.10.6 Embedded Ruby and the C++ Stack

      As has been said, the Ruby GC runs and marks objects before diff --git a/Doc/Manual/SWIG.html b/Doc/Manual/SWIG.html index d523bee77..58a3c8e55 100644 --- a/Doc/Manual/SWIG.html +++ b/Doc/Manual/SWIG.html @@ -44,6 +44,12 @@

    • Arrays
    • Creating read-only variables
    • Renaming and ignoring declarations +
    • Default/optional arguments
    • Pointers to functions and callbacks @@ -142,6 +148,7 @@ can be obtained by typing swig -help or swig -o outfile Name of output file -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 -version Show SWIG version number @@ -1662,6 +1669,9 @@ generate a warning message. Simply change the directives to %immutable;5.4.7 Renaming and ignoring declarations +

      5.4.7.1 Simple renaming of specific identifiers

      + +

      Normally, the name of a C declaration is used when that declaration is wrapped into the target language. However, this may generate a @@ -1741,12 +1751,6 @@ to add conditional compilation to the header. However, it should be stressed t declarations. If you need to remove a whole section of problematic code, the SWIG preprocessor should be used instead.

      -

      -More powerful variants of %rename and %ignore directives can be used to help -wrap C++ overloaded functions and methods or C++ methods which use default arguments. This is described in the -Ambiguity resolution and renaming section in the C++ chapter. -

      -

      Compatibility note: Older versions of SWIG provided a special %name directive for renaming declarations. For example: @@ -1763,6 +1767,337 @@ 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.

      +

      5.4.7.2 Advanced renaming support

      + + +

      +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 necessary to apply some +transformation to all the names in the target language to better follow its +naming conventions, like adding a specific prefix to all wrapped functions. Doing it individually +for each function is impractical so SWIG supports applying a renaming rule to +all declarations if the name of the identifier to be renamed is not specified: +

      + +
      +
      +%rename("myprefix_%s") ""; // print -> myprefix_print
      +
      +
      + +

      +This also shows that the argument of %rename doesn't have to be a +literal string but can be a printf()-like format string. In the +simplest form, "%s" is replaced with the name of the original +declaration, as shown above. However this is not always enough and SWIG +provides extensions to the usual format string syntax to allow applying a +(SWIG-defined) function to the argument. For example, to wrap all C functions +do_something_long() as more Java-like doSomethingLong() you +can use the "lowercamelcase" extended format specifier like this: +

      + +
      +
      +%rename("%(lowercamelcase)s") ""; // foo_bar -> fooBar; FooBar -> fooBar
      +
      +
      + +

      +Some functions can be parametrized, for example the "strip" one +strips the provided prefix from its argument. The prefix is specified as part +of the format string, following a colon after the function name: +

      +
      +
      +%rename("%(strip:[wx])s") ""; // wxHello -> Hello; FooBar -> FooBar
      +
      +
      + +

      +Below is the table summarizing all currently defined functions with an example +of applying each one. Note that some of them have two names, a shorter one +and a more descriptive one, but the two functions are otherwise equivalent: +

      +
    • $symname Name of -function/method being wrapped$inputRuby object being sent to the function
      $symname Name of function/method being wrapped
      $1...n Argument being -sent to the functionArgument being sent to the function
      $resultResult that the -director function returnsResult that the director function returns
      $inputRuby object being sent to the function
      $symnamename of the -function/method being wrappedname of the function/method being wrapped
      $1...nArgument being -sent to the functionArgument being sent to the function
      char * STR2CSTR(String)char * StringValuePtr(String) SWIG_AsCharPtrAndSize(VALUE, char*, size_t, int* alloc)
      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FunctionReturnsExample (in/out)
      uppercase or upperUpper case version of the string.PrintPRINT
      lowercase or lowerLower case version of the string.Printprint
      titleString with first letter capitalized and the rest in lower case.printPrint
      firstuppercaseString with the first letter capitalized and the rest unchanged.printItPrintIt
      firstlowercaseString with the first letter in lower case and the rest unchanged.PrintItprintIt
      camelcase or ctitleString with capitalized first letter and any letter following an + underscore (which are removed in the process) and rest in lower case.print_itPrintIt
      lowercamelcase or lctitleString with every letter following an underscore (which is removed in + the process) capitalized and rest, including the first letter, in lower + case.print_itprintIt
      undercase or utitleLower case string with underscores inserted before every upper case + letter in the original string and any number not at the end of string. + Logically, this is the reverse of camelcase.PrintItprint_it
      schemifyString with all underscores replaced with dashes, resulting in more + Lispers/Schemers-pleasing name.print_itprint-it
      strip:[prefix]String without the given prefix or the original string if it doesn't + start with this prefix. Note that square brackets should be used + literally, e.g. %rename("strip:[wx]")wxPrintPrint
      regex:/pattern/subst/String after (Perl-like) regex substitution operation. This function + allows to apply arbitrary regular expressions to the identifier names. The + pattern part is a regular expression in Perl syntax (as supported + by the Perl Compatible Regular Expressions (PCRE)) + library and the subst string + can contain back-references introduced by '\' or, as backslashes need + to be escaped in C strings, rather by "\\". For example, to remove + any alphabetic prefix before an underscore you could use the following directive: + %rename("regex:/(\\w+)_(.*)/\\2/")Prefix_PrintPrint
      command:cmdOutput of an external command cmd with the string passed to + it as input. Notice that this function is extremely slow compared to all + the other ones as it involves spawning a separate process and using it for + many declarations is not recommended. The cmd is not enclosed in + square brackets but must be terminated with a triple '<' sign, + e.g. %rename("command:tr -d aeiou <<<") + (nonsensical example removing all vowels)PrintPrnt
      + +

      +The most general function of all of the above ones (not counting +command which is even more powerful in principle but which should +generally be avoided because of performance considerations) is the +regex one. Here are some more examples of its use: +

      + +
      +
      +// Strip the wx prefix from all identifiers except those starting with wxEVT
      +%rename("%(regex:/wx(?!EVT)(.*)/\\1/)s") ""; // wxSomeWidget -> SomeWidget
      +                                             // wxEVT_PAINT -> wxEVT_PAINT
      +
      +// Apply a rule for renaming the enum elements to avoid the common prefixes
      +// which are redundant in C#/Java
      +%rename("%(regex:/^([A-Z][a-z]+)+_(.*)/\\2/)s", %$isenumitem) ""; // Colour_Red -> Red
      +
      +// Remove all "Set/Get" prefixes.
      +%rename("%(regex:/^(Set|Get)(.*)/\\2/)s") ""; // SetValue -> Value
      +                                              // GetValue -> Value
      +
      +
      + +

      +As before, everything that was said above about %rename also applies to +%ignore. In fact, the latter is just a special case of the former and +ignoring an identifier is the same as renaming it to the special +"$ignore" value. So the following snippets +

      + +
      +
      +%ignore print;
      +
      +
      + +

      +and +

      + +
      +
      +%rename("$ignore") print;
      +
      +
      + +

      +are exactly equivalent and %rename can be used to selectively ignore +multiple declarations using the previously described matching possibilities. +

      + +

      5.4.7.3 Limiting global renaming rules

      + + +

      +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 are always some +exceptions to the general rules. To deal with them, the scope of an unnamed +%rename can be limited using subsequent match parameters. +They can be applied to any of the attributes associated by SWIG with the +declarations appearing in its input. For example: +

      +
      +
      +%rename("foo", match$name="bar") "";
      +
      +
      +

      +can be used to achieve the same effect as the simpler +

      +
      +
      +%rename("foo") bar;
      +
      +
      +

      +and so is not very interesting on its own. However match can also be +applied to the declaration type, for example match="class" restricts +the match to class declarations only (in C++) and match="enumitem" +restricts it to the enum elements. SWIG also provides convenience macros for +such match expressions, for example +

      +
      +
      +%rename("%(title)s", %$isenumitem) "";
      +
      +
      +

      +will capitalize the names of all the enum elements but not change the case of +the other declarations. Similarly, %$isclass, %$isfunction, +%$isconstructor, %$isunion, %$istemplate, +and %$isvariable can be used. Many other checks are possible and this +documentation is not exhaustive, see the "%rename predicates" section in +swig.swg for the full list of supported match expressions. +

      + +

      +In addition to literally matching some string with match you can +also use regexmatch or notregexmatch to match a string +against a regular expression. For example, to ignore all functions having +"Old" as a suffix you could use +

      +
      +
      +%rename("$ignore", regexmatch$name="Old$") "";
      +
      +
      +

      +For simple cases like this, specifying the regular expression for the +declaration name directly can be preferable and can also be done using +regextarget: +

      +
      +
      +%rename("$ignore", regextarget=1) "Old$";
      +
      +
      + +

      +Notice that the check is done only against the name of the declaration +itself, if you need to match the full name of a C++ declaration you +must use fullname attribute: +

      + +
      +
      +%rename("$ignore", regextarget=1, fullname=1) "NameSpace::ClassName::.*Old$";
      +
      +
      + +

      +As for notregexmatch, it restricts the match only to the strings not +matching the specified regular expression. So to rename all declarations to lower case +except those consisting of capital letters only: +

      +
      +
      +%rename("$(lower)s", notregexmatch$name="^[A-Z]+$") "";
      +
      +
      + +

      +Finally, variants of %rename and %ignore directives can be used to help +wrap C++ overloaded functions and methods or C++ methods which use default arguments. This is described in the +Ambiguity resolution and renaming section in the C++ chapter. +

      + + +

      5.4.7.4 Ignoring everything then wrapping a few selected symbols

      + + +

      +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 has many classes in it and just the one class called Star is wanted within this header, +the following approach could be taken: +

      + +
      +
      +%ignore ""; // Ignore everything
      +
      +// Unignore chosen class 'Star'
      +%rename("%s") Star;
      +
      +// As the ignore everything will include the constructor, destructor, methods etc
      +// in the class, these have to be explicitly unignored too:
      +%rename("%s") Star::Star;
      +%rename("%s") Star::~Star;
      +%rename("%s") Star::shine; // named method
      +
      +%include "myheader.h"
      +
      +
      + +

      +Another approach which might be more suitable as it does not require naming all the methods in the +chosen class is to begin by ignoring just the classes. This does not add an explicit ignore to any +members of the class, so when the chosen class is unignored, all of its methods will be wrapped. +

      + +
      +
      +%rename($ignore, %$isclass) ""; // Only ignore all classes
      +%rename("%s") Star; // Unignore 'Star'
      +%include "myheader.h"
      +
      +
      + +

      5.4.8 Default/optional arguments

      @@ -1926,13 +2261,13 @@ 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 +variation installs the callbacks as all upper case constants such as ADD, SUB, and MUL:

       /* Some callback functions */
      -%callback("%(upper)s");
      +%callback("%(uppercase)s");
       int add(int,int);
       int sub(int,int);
       int mul(int,int);
      @@ -1940,7 +2275,7 @@ int mul(int,int);
       

      -A format string of "%(lower)s" converts all characters to lower-case. +A format string of "%(lowercase)s" converts all characters to lower case. A string of "%(title)s" capitalizes the first character and converts the rest to lower case.

      @@ -1949,7 +2284,8 @@ rest to lower case. And now, a final note about function pointer support. Although SWIG does not normally allow callback functions to be written in the target language, this can be accomplished with the use of typemaps and other advanced SWIG features. -This is described in a later chapter. +See the Typemaps chapter for more about typemaps +and individual target language chapters for more on callbacks and the 'director' feature.

      5.5 Structures and unions

      @@ -2746,14 +3082,15 @@ output of SWIG is structured first.

      -When SWIG creates its output file, it is broken up into four sections +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).

      • Begin section.
        -A placeholder to put code at the beginning of the C/C++ wrapper file. +A placeholder for users to put code at the beginning of the C/C++ wrapper file. +This is most often used to define preprocessor macros that are used in later sections.
      • Runtime code.
        diff --git a/Doc/Manual/SWIGPlus.html b/Doc/Manual/SWIGPlus.html index f9bfc8ec6..716882f53 100644 --- a/Doc/Manual/SWIGPlus.html +++ b/Doc/Manual/SWIGPlus.html @@ -57,6 +57,7 @@
      • Exception handling with %catches
      • Pointers to Members
      • Smart pointers and operator->() +
      • C++ reference counted objects - ref/unref feature
      • Using declarations and inheritance
      • Nested classes
      • A brief rant about const-correctness @@ -2837,6 +2838,12 @@ struct Derived : Base { } +

        +The following special variables are expanded if used within a %extend block: +$name, $symname, $overname, $decl, $fulldecl, $parentname and $parentsymname. +The Special variables section provides more information each of these special variables. +

        +

        The %extend directive follows all of the same conventions as its use with C structures. Please refer to the Adding member functions to C structures @@ -3120,8 +3127,8 @@ nothing is known about List<int>, you will get a warning message

        -example.h:42. Nothing known about class 'List<int >' (ignored). 
        -example.h:42. Maybe you forgot to instantiate 'List<int >' using %template. 
        +example.h:42: Warning 401. Nothing known about class 'List<int >'. Ignored. 
        +example.h:42: Warning 401. Maybe you forgot to instantiate 'List<int >' using %template. 
         
        @@ -3162,7 +3169,7 @@ Don't worry--if you get the order wrong, SWIG should generate a warning message. Occasionally, you may need to tell SWIG about base classes that are defined by templates, but which aren't supposed to be wrapped. Since SWIG is not able to automatically instantiate templates for this purpose, you must do it manually. To do this, simply -use %template with no name. For example: +use the empty template instantiation, that is, %template with no name. For example:

        @@ -3356,7 +3363,7 @@ public:

        In this case, the %extend directive is not needed, and -%template does the exactly same job, i.e., it adds two new +%template does exactly the same job, i.e., it adds two new methods to the Foo class.

        @@ -4192,8 +4199,9 @@ In the example below, the generic template type is used to rename to bbb
        -%rename(bbb) Space::ABC::aaa(T t);                       // will match but with lower precedence than ccc
        -%rename(ccc) Space::ABC<Space::XYZ>::aaa(Space::XYZ t);  // will match but with higher precedence than bbb
        +%rename(bbb) Space::ABC::aaa(T t);                  // will match but with lower precedence than ccc
        +%rename(ccc) Space::ABC<Space::XYZ>::aaa(Space::XYZ t);// will match but with higher precedence
        +                                                             // than bbb
         
         namespace Space {
           class XYZ {};
        @@ -4214,9 +4222,9 @@ Below shows how %rename can be placed inside a namespace.
         
         namespace Space {
        -  %rename(bbb) ABC::aaa(T t);                       // will match but with lower precedence than ccc
        -  %rename(ccc) ABC<Space::XYZ>::aaa(Space::XYZ t);  // will match but with higher precedence than bbb
        -  %rename(ddd) ABC<Space::XYZ>::aaa(XYZ t);         // will not match
        +  %rename(bbb) ABC::aaa(T t);                     // will match but with lower precedence than ccc
        +  %rename(ccc) ABC<Space::XYZ>::aaa(Space::XYZ t);// will match but with higher precedence than bbb
        +  %rename(ddd) ABC<Space::XYZ>::aaa(XYZ t);       // will not match
         }
         
         namespace Space {
        @@ -4238,11 +4246,11 @@ The following example shows how %rename can be placed within %extend.
         
         namespace Space {
           %extend ABC {
        -    %rename(bbb) aaa(T t);           // will match but with lower precedence than ccc
        +    %rename(bbb) aaa(T t);         // will match but with lower precedence than ccc
           }
           %extend ABC<Space::XYZ> {
        -    %rename(ccc) aaa(Space::XYZ t);  // will match but with higher precedence than bbb
        -    %rename(ddd) aaa(XYZ t);         // will not match
        +    %rename(ccc) aaa(Space::XYZ t);// will match but with higher precedence than bbb
        +    %rename(ddd) aaa(XYZ t);       // will not match
           }
         }
         
        @@ -4617,8 +4625,179 @@ 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 Using declarations and inheritance

        + +

        +Another similar idiom in C++ is the use of reference counted objects. Consider for example: + +

        +
        +class RCObj  {
        +  // implement the ref counting mechanism
        +  int add_ref();
        +  int del_ref();
        +  int ref_count();
        +
        +public:
        +  virtual ~RCObj() = 0;
        +
        +  int ref() const {
        +    return add_ref();
        +  }
        +
        +  int unref() const   {
        +    if (ref_count() == 0 || del_ref() == 0 ) {
        +	delete this;
        +	return 0;
        +      } 
        +    return ref_count();
        +  }
        +};
        +
        +
        +class A : RCObj {
        +public:
        +  A();
        +  int foo();
        +};
        +
        +
        +class B {
        +  A *_a;
        +
        +public:
        +  B(A *a) : _a(a) { 
        +    a->ref(); 
        +  }
        +
        +  ~B() { 
        +    a->unref(); 
        +  }
        +};
        +
        +int main() {
        +  A *a  = new A();       // (count: 0)
        +  a->ref();           // 'a' ref here (count: 1)
        +
        +  B *b1 = new B(a);   // 'a' ref here (count: 2)
        +  if (1 + 1 == 2) {
        +    B *b2 = new B(a); // 'a' ref here (count: 3)
        +    delete b2;        // 'a' unref, but not deleted (count: 2)
        +  }
        +
        +  delete b1;          // 'a' unref, but not deleted (count: 1)
        +  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 Counted + Object 'RCObj', which implements the ref/unref idiom. +

        + +

        +To tell SWIG that 'RCObj' and all its derived classes are reference +counted objects, use the "ref" and "unref" features. +These are also available as %refobject and %unrefobject, respectively. +For example: +

        + + +
        +
        +%module example
        +...
        +
        +%feature("ref")   RCObj "$this->ref();"
        +%feature("unref") RCObj "$this->unref();"
        +
        +%include "rcobj.h"
        +%include "A.h"
        +...
        +
        +
        + +

        +where the code passed to the "ref" and "unref" features will be +executed as needed whenever a new object is passed to python, or when +python tries to release the proxy object instance, respectively. +

        + +

        +On the python side, the use of a reference counted object is no +different to any other regular instance: +

        + +
        +
        +def create_A():
        +  a = A()         # SWIG ref 'a' - new object is passed to python (count: 1)
        +  b1 = B(a)       # C++ ref 'a (count: 2)
        +  if 1 + 1 == 2:
        +     b2 = B(a)    # C++ ref 'a' (count: 3)
        +  return a        # 'b1' and 'b2' are released and deleted, C++ unref 'a' twice (count: 1)
        +
        +a = create_A()    # (count: 1)
        +exit              # 'a' is released, SWIG unref 'a' called in the destructor wrapper (count: 0)
        +
        +
        + +

        +Note that the user doesn't explicitly need to call 'a->ref()' nor 'a->unref()' +(and neither 'delete a'). Instead, SWIG takes cares of executing the "ref" +and "unref" calls as needed. If the user doesn't specify the +"ref/unref" feature for a type, SWIG will produce code equivalent to defining these +features: +

        + +
        +
        +%feature("ref")   ""
        +%feature("unref") "delete $this;"
        +
        +
        + +

        +In other words, SWIG will not do anything special when a new object +is passed to python, and it will always 'delete' the underlying object when +python releases the proxy instance. +

        + +

        +The %newobject feature is designed to indicate to +the target language that it should take ownership of the returned object. +When used in conjunction with a type that has the "ref" feature associated with it, it additionally emits the +code in the "ref" feature into the C++ wrapper. +Consider wrapping the following factory function in addition to the above: +

        + +
        +
        +%newobject AFactory;
        +A *AFactory() {
        +  return new A();
        +}
        +
        +
        + +

        +The AFactory function now acts much like a call to the A constructor with respect to memory handling: +

        + +
        +
        +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

        @@ -4781,7 +4960,7 @@ public:

      -

      6.26 Nested classes

      +

      6.27 Nested classes

      @@ -4925,7 +5104,7 @@ Nested class warnings could also not be suppressed using %warnfilter.

      -

      6.27 A brief rant about const-correctness

      +

      6.28 A brief rant about const-correctness

      @@ -4983,7 +5162,7 @@ using another tool if maintaining constness is the most important part of your project.

      -

      6.28 Where to go for more information

      +

      6.29 Where to go for more information

      diff --git a/Doc/Manual/Sections.html b/Doc/Manual/Sections.html index 8693adc07..9e4a3dd17 100644 --- a/Doc/Manual/Sections.html +++ b/Doc/Manual/Sections.html @@ -6,7 +6,7 @@

      SWIG-2.0 Documentation

      -Last update : SWIG-2.0.1 (in progress) +Last update : SWIG-2.0.10 (in progress)

      Sections

      @@ -19,7 +19,7 @@ Last update : SWIG-2.0.1 (in progress)
    • SWIG Basics (Read this!)
    • SWIG and C++
    • The SWIG preprocessor
    • -
    • The SWIG Library
    • +
    • The SWIG library
    • Argument handling
    • Typemaps
    • Customization features
    • @@ -33,24 +33,26 @@ Last update : SWIG-2.0.1 (in progress)

      Language Module Documentation

      diff --git a/Doc/Manual/Tcl.html b/Doc/Manual/Tcl.html index d47dae5de..e6b3b4a43 100644 --- a/Doc/Manual/Tcl.html +++ b/Doc/Manual/Tcl.html @@ -6,7 +6,7 @@ -

      34 SWIG and Tcl

      +

      37 SWIG and Tcl

        @@ -83,7 +83,7 @@ Tcl 8.0 or a later release. Earlier releases of SWIG supported Tcl 7.x, but this is no longer supported.

        -

        34.1 Preliminaries

        +

        37.1 Preliminaries

        @@ -109,7 +109,7 @@ build a Tcl extension module. To finish building the module, you need to compile this file and link it with the rest of your program.

        -

        34.1.1 Getting the right header files

        +

        37.1.1 Getting the right header files

        @@ -127,12 +127,13 @@ this is the case, you should probably make a symbolic link so that tcl.h -

        34.1.2 Compiling a dynamic module

        +

        37.1.2 Compiling a dynamic module

        The preferred approach to building an extension module is to compile it into -a shared object file or DLL. To do this, you will need to compile your program +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 your program using commands like this (shown for Linux):

        @@ -162,7 +163,7 @@ The name of the module is specified using the %module directive or the -module command line option.

        -

        34.1.3 Static linking

        +

        37.1.3 Static linking

        @@ -228,7 +229,7 @@ minimal in most situations (and quite frankly not worth the extra hassle in the opinion of this author).

        -

        34.1.4 Using your module

        +

        37.1.4 Using your module

        @@ -356,7 +357,7 @@ to the default system configuration (this requires root access and you will need the man pages).

        -

        34.1.5 Compilation of C++ extensions

        +

        37.1.5 Compilation of C++ extensions

        @@ -439,7 +440,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.1.6 Compiling for 64-bit platforms

        +

        37.1.6 Compiling for 64-bit platforms

        @@ -466,7 +467,7 @@ also introduce problems on platforms that support more than one linking standard (e.g., -o32 and -n32 on Irix).

        -

        34.1.7 Setting a package prefix

        +

        37.1.7 Setting a package prefix

        @@ -485,7 +486,7 @@ option will append the prefix to the name when creating a command and call it "Foo_bar".

        -

        34.1.8 Using namespaces

        +

        37.1.8 Using namespaces

        @@ -507,7 +508,7 @@ When the -namespace option is used, objects in the module are always accessed with the namespace name such as Foo::bar.

        -

        34.2 Building Tcl/Tk Extensions under Windows 95/NT

        +

        37.2 Building Tcl/Tk Extensions under Windows 95/NT

        @@ -518,7 +519,7 @@ covers the process of using SWIG with Microsoft Visual C++. although the procedure may be similar with other compilers.

        -

        34.2.1 Running SWIG from Developer Studio

        +

        37.2.1 Running SWIG from Developer Studio

        @@ -576,7 +577,7 @@ MSDOS > tclsh80 %

      -

      34.2.2 Using NMAKE

      +

      37.2.2 Using NMAKE

      @@ -639,7 +640,7 @@ to get you started. With a little practice, you'll be making lots of Tcl extensions.

      -

      34.3 A tour of basic C/C++ wrapping

      +

      37.3 A tour of basic C/C++ wrapping

      @@ -650,7 +651,7 @@ classes. This section briefly covers the essential aspects of this wrapping.

      -

      34.3.1 Modules

      +

      37.3.1 Modules

      @@ -684,7 +685,7 @@ To fix this, supply an extra argument to load like this: -

      34.3.2 Functions

      +

      37.3.2 Functions

      @@ -709,7 +710,7 @@ like you think it does: % -

      34.3.3 Global variables

      +

      37.3.3 Global variables

      @@ -789,7 +790,7 @@ extern char *path; // Read-only (due to %immutable) -

      34.3.4 Constants and enums

      +

      37.3.4 Constants and enums

      @@ -873,7 +874,7 @@ When an identifier name is given, it is used to perform an implicit hash-table l conversion. This allows the global statement to be omitted.

      -

      34.3.5 Pointers

      +

      37.3.5 Pointers

      @@ -969,7 +970,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

      +

      37.3.6 Structures

      @@ -1251,7 +1252,7 @@ Note: Tcl only destroys the underlying object if it has ownership. See the memory management section that appears shortly.

      -

      34.3.7 C++ classes

      +

      37.3.7 C++ classes

      @@ -1318,7 +1319,7 @@ In Tcl, the static member is accessed as follows: -

      34.3.8 C++ inheritance

      +

      37.3.8 C++ inheritance

      @@ -1367,7 +1368,7 @@ For instance: It is safe to use multiple inheritance with SWIG.

      -

      34.3.9 Pointers, references, values, and arrays

      +

      37.3.9 Pointers, references, values, and arrays

      @@ -1421,7 +1422,7 @@ to hold the result and a pointer is returned (Tcl will release this memory when the return value is garbage collected).

      -

      34.3.10 C++ overloaded functions

      +

      37.3.10 C++ overloaded functions

      @@ -1544,7 +1545,7 @@ first declaration takes precedence. Please refer to the "SWIG and C++" chapter for more information about overloading.

      -

      34.3.11 C++ operators

      +

      37.3.11 C++ operators

      @@ -1646,7 +1647,7 @@ There are ways to make this operator appear as part of the class using the % Keep reading.

      -

      34.3.12 C++ namespaces

      +

      37.3.12 C++ namespaces

      @@ -1710,7 +1711,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

      +

      37.3.13 C++ templates

      @@ -1762,7 +1763,7 @@ More details can be found in the SWIG and C++ -

      34.3.14 C++ Smart Pointers

      +

      37.3.14 C++ Smart Pointers

      @@ -1846,7 +1847,7 @@ simply use the __deref__() method. For example: -

      34.4 Further details on the Tcl class interface

      +

      37.4 Further details on the Tcl class interface

      @@ -1859,7 +1860,7 @@ of low-level details were omitted. This section provides a brief overview of how the proxy classes work.

      -

      34.4.1 Proxy classes

      +

      37.4.1 Proxy classes

      @@ -1924,7 +1925,7 @@ function. This allows objects to be encapsulated objects that look a lot like as shown in the last section.

      -

      34.4.2 Memory management

      +

      37.4.2 Memory management

      @@ -2112,7 +2113,7 @@ typemaps--an advanced topic discussed later.

      -

      34.5 Input and output parameters

      +

      37.5 Input and output parameters

      @@ -2300,7 +2301,7 @@ set c [lindex $dim 1] -

      34.6 Exception handling

      +

      37.6 Exception handling

      @@ -2434,7 +2435,7 @@ Since SWIG's exception handling is user-definable, you are not limited to C++ ex See the chapter on "Customization Features" for more examples.

      -

      34.7 Typemaps

      +

      37.7 Typemaps

      @@ -2451,7 +2452,7 @@ Typemaps are only used if you want to change some aspect of the primitive C-Tcl interface.

      -

      34.7.1 What is a typemap?

      +

      37.7.1 What is a typemap?

      @@ -2568,7 +2569,7 @@ parameter is omitted): -

      34.7.2 Tcl typemaps

      +

      37.7.2 Tcl typemaps

      @@ -2706,7 +2707,7 @@ Initialize an argument to a value before any conversions occur. Examples of these methods will appear shortly.

      -

      34.7.3 Typemap variables

      +

      37.7.3 Typemap variables

      @@ -2777,7 +2778,7 @@ properly assigned. The Tcl name of the wrapper function being created. -

      34.7.4 Converting a Tcl list to a char **

      +

      37.7.4 Converting a Tcl list to a char **

      @@ -2839,7 +2840,7 @@ argv[2] = Larry 3 -

      34.7.5 Returning values in arguments

      +

      37.7.5 Returning values in arguments

      @@ -2881,7 +2882,7 @@ result, a Tcl function using these typemaps will work like this : % -

      34.7.6 Useful functions

      +

      37.7.6 Useful functions

      @@ -2958,7 +2959,7 @@ int Tcl_IsShared(Tcl_Obj *obj); -

      34.7.7 Standard typemaps

      +

      37.7.7 Standard typemaps

      @@ -3042,7 +3043,7 @@ work) -

      34.7.8 Pointer handling

      +

      37.7.8 Pointer handling

      @@ -3118,7 +3119,7 @@ For example: -

      34.8 Turning a SWIG module into a Tcl Package.

      +

      37.8 Turning a SWIG module into a Tcl Package.

      @@ -3190,7 +3191,7 @@ As a final note, most SWIG examples do not yet use the to use the load command instead.

      -

      34.9 Building new kinds of Tcl interfaces (in Tcl)

      +

      37.9 Building new kinds of Tcl interfaces (in Tcl)

      @@ -3289,7 +3290,7 @@ danger of blowing something up (although it is easily accomplished with an out of bounds array access).

      -

      34.9.1 Proxy classes

      +

      37.9.1 Proxy classes

      @@ -3410,7 +3411,7 @@ short, but clever Tcl script can be combined with SWIG to do many interesting things.

      -

      34.10 Tcl/Tk Stubs

      +

      37.10 Tcl/Tk Stubs

      diff --git a/Doc/Manual/Typemaps.html b/Doc/Manual/Typemaps.html index 1568c082e..b3b0bc7a9 100644 --- a/Doc/Manual/Typemaps.html +++ b/Doc/Manual/Typemaps.html @@ -73,6 +73,7 @@

    • Typemaps for multiple target languages
    • Optimal code generation when returning by value
    • Multi-argument typemaps +
    • Typemap warnings
    • Typemap fragments
      • Fragment type specialization @@ -1711,7 +1712,8 @@ you'll find the full typemap contents (example shown below for Python): %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""'"); + SWIG_exception_fail(SWIG_ArgError(res), "in method '" "$symname" "', argument " + "$argnum"" of type '" "$type""'"); } $1 = ($ltype)(argp); } @@ -1732,7 +1734,8 @@ SWIGINTERN PyObject *_wrap_foo(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { ... 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]""'"); + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "foo" "', argument " + "1"" of type '" "int [10][4]""'"); } arg1 = (int (*)[4])(argp1); ... @@ -1791,7 +1794,8 @@ void set_value(const char* val) {} } } -%apply SWIGTYPE * { const char* val, const char* another_value } // use default pointer handling instead of strings +// use default pointer handling instead of strings +%apply SWIGTYPE * { const char* val, const char* another_value } %typemap(check) const char* val = char* NON_NULL; @@ -3296,7 +3300,8 @@ SWIG can detect when the "optimal" attribute cannot be used and will ignore it a
         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: 
        +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) {
        @@ -3317,8 +3322,8 @@ 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 optimal attribute usage in
        -example.i:7: Warning 475: the out typemap.
        +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.
         
        @@ -3593,7 +3598,16 @@ with non-consecutive C/C++ arguments; a workaround such as a helper function re- the arguments to make them consecutive will need to be written.

        -

        10.10 Typemap fragments

        +

        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

        @@ -3659,17 +3673,21 @@ 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". Both string and curly braces can be used: +Usually the section name used is "header". Different delimiters can be used:

        +%fragment("my_name", "header") %{ ... %}
         %fragment("my_name", "header") { ... }
         %fragment("my_name", "header") " ... "
         

        +and these follow the usual preprocessing rules mentioned in the +Preprocessing delimiters +section. The following are some rules and guidelines for using fragments:

        @@ -3747,8 +3765,8 @@ A fragment can use one or more additional fragments, for example:
        -%fragment("<limits.h>", "header")  {
        -  #include <limits.h>
        +%fragment("<limits.h>", "header") {
        +  %#include <limits.h>
         }
         
         
        @@ -3842,7 +3860,7 @@ 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.10.1 Fragment type specialization

        +

        10.11.1 Fragment type specialization

        @@ -3875,7 +3893,7 @@ struct A {

        -

        10.10.2 Fragments and automatic typemap specialization

        +

        10.11.2 Fragments and automatic typemap specialization

        @@ -3921,7 +3939,7 @@ The interested (or very brave) reader can take a look at the fragments.swg file

        -

        10.11 The run-time type checker

        +

        10.12 The run-time type checker

        @@ -3947,7 +3965,7 @@ language modules.

      • Modules can be unloaded from the type system.
      -

      10.11.1 Implementation

      +

      10.12.1 Implementation

      @@ -4133,7 +4151,7 @@ structures rather than creating new ones. These swig_module_info structures are chained together in a circularly linked list.

      -

      10.11.2 Usage

      +

      10.12.2 Usage

      This section covers how to use these functions from typemaps. To learn how to @@ -4227,7 +4245,7 @@ probably just look at the output of SWIG to get a better sense for how types are managed.

      -

      10.12 Typemaps and overloading

      +

      10.13 Typemaps and overloading

      @@ -4538,7 +4556,7 @@ Subsequent "in" typemaps would then perform more extensive type-checking.

    -

    10.13 More about %apply and %clear

    +

    10.14 More about %apply and %clear

    @@ -4624,7 +4642,7 @@ example: -

    10.14 Passing data between typemaps

    +

    10.15 Passing data between typemaps

    @@ -4661,7 +4679,7 @@ sure that the typemaps sharing information have exactly the same types and names

    -

    10.15 C++ "this" pointer

    +

    10.16 C++ "this" pointer

    @@ -4721,7 +4739,7 @@ will also match the typemap. One work around is to create an interface file tha the method, but gives the argument a name other than self.

    -

    10.16 Where to go for more information?

    +

    10.17 Where to go for more information?

    diff --git a/Doc/Manual/Varargs.html b/Doc/Manual/Varargs.html index fb34a3ad9..13abc8cee 100644 --- a/Doc/Manual/Varargs.html +++ b/Doc/Manual/Varargs.html @@ -331,33 +331,82 @@ 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 parameters to a varargs function are of uniform type, %varargs can also +If the arguments to a varargs function are of uniform type, %varargs can also accept a numerical argument count as follows:

    -%varargs(10,char *arg = NULL) execlp;
    +%varargs(3, char *str = NULL) execlp;
     ...
    -int execlp(const char *path, const char *arg1, ...);
    +int execlp(const char *path, const char *arg, ...);
     

    -This would wrap execlp() as a function that accepted up to 10 optional arguments. +and is effectively seen as: +

    + +
    +
    +int execlp(const char *path, const char *arg, 
    +           char *str1 = NULL, 
    +           char *str2 = NULL, 
    +           char *str3 = NULL);
    +
    +
    + +

    +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.

    -Argument replacement is most appropriate in cases where the types of -the extra arguments is uniform and the maximum number of arguments is -known. When replicated argument replacement is used, at least one extra -argument is added to the end of the arguments when making the function call. -This argument serves as a sentinel to make sure the list is properly terminated. -It has the same value as that supplied to the %varargs directive. +The handling of default arguments can be changed via the +compactdefaultargs feature. If this feature is used, for example +

    + +
    +
    +%feature("compactdefaultargs") execlp;
    +%varargs(3, char *str = NULL) execlp;
    +...
    +int execlp(const char *path, const char *arg, ...);
    +
    +
    + +

    +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, +

    + +
    +
    +%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 %vargars 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). @@ -461,23 +510,36 @@ like this:

     %typemap(in) (...)(char *args[10]) {
    -    int i;
    -    int argc;
    -    for (i = 0; i < 10; i++) args[i] = 0;
    -    argc = PyTuple_Size(varargs);
    -    if (argc > 10) {
    -       PyErr_SetString(PyExc_ValueError,"Too many arguments");
    +  int i;
    +  int argc;
    +  for (i = 0; i < 10; i++) args[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;
         }
    -    for (i = 0; i < argc; i++) {
    -       PyObject *o = PyTuple_GetItem(varargs,i);
    -       if (!PyString_Check(o)) {
    -           PyErr_SetString(PyExc_ValueError,"Expected a string");
    -           return NULL;
    -       }
    -       args[i] = PyString_AsString(o);
    +    pystr = PyUnicode_AsUTF8String(pyobj);
    +    str = PyBytes_AsString(pystr);
    +    Py_XDECREF(pystr);
    +%#else  
    +    if (!PyString_Check(pyobj)) {
    +       PyErr_SetString(PyExc_ValueError, "Expected a string");
    +       return NULL;
         }
    -    $1 = (void *) args;
    +    str = PyString_AsString(pyobj);
    +%#endif
    +    args[i] = str;
    +  }
    +  $1 = (void *) args;
     }
     
    @@ -777,13 +839,13 @@ of type va_list. For example:
    -int vfprintf(FILE *f, const char *fmt, va_list ap);
    +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 +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 @@ -791,6 +853,36 @@ 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;
    +}
    +%}
    +
    +
    +

    13.8 C++ Issues

    diff --git a/Doc/Manual/Warnings.html b/Doc/Manual/Warnings.html index 96e35902a..1571146f1 100644 --- a/Doc/Manual/Warnings.html +++ b/Doc/Manual/Warnings.html @@ -25,7 +25,7 @@
  • C/C++ Parser (300-399)
  • Types and typemaps (400-499)
  • Code generation (500-599) -
  • Language module specific (800-899) +
  • Language module specific (700-899)
  • User defined (900-999)
  • History @@ -257,16 +257,23 @@ Warning messages can be associated with typemaps using the
    -%typemap(in, warning="901:You are really going to regret this") blah * {
    +%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. +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
    +
    +
    +

    14.5 Symbolic symbols

    @@ -381,8 +388,12 @@ example.i(4) : Syntax error in input.
      -
    • 201. Unable to find 'filename'. -
    • 202. Could not evaluate 'expr'. +
    • 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)

    @@ -497,7 +508,7 @@ example.i(4) : Syntax error in input.
  • 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. +
  • 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). @@ -513,9 +524,11 @@ example.i(4) : Syntax error in input.
  • 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. -

    14.9.6 Language module specific (800-899)

    +

    14.9.6 Language module specific (700-899)

      @@ -538,6 +551,8 @@ example.i(4) : Syntax error in input.
    • 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).
      diff --git a/Doc/Manual/Windows.html b/Doc/Manual/Windows.html index da8a5d6bf..c94a3da3b 100644 --- a/Doc/Manual/Windows.html +++ b/Doc/Manual/Windows.html @@ -236,8 +236,8 @@ The short abbreviated instructions follow...

    -The step by step instructions to download and install MinGW and MSYS, then download and build the latest version of SWIG from SVN follow... -Note that the instructions for obtaining SWIG from SVN are also online at SWIG SVN. +The step by step instructions to download and install MinGW and MSYS, then download and build the latest version of SWIG from Github follow... +Note that the instructions for obtaining SWIG from Github are also online at SWIG Bleeding Edge.

    @@ -300,19 +300,35 @@ tar -zxf bison-2.0-MSYS.tar.gz

  • - To get the latest SWIG SVN (version from Subversion source control), type in the following: + The very latest development version of SWIG is available from SWIG on Github + and can be downloaded as a zip file or if you have Git installed, via Git. + Either download the latest Zip file snapshot and unzip and rename the top level folder to /usr/src/swig. + + Otherwise if using Git, type in the following:
     mkdir /usr/src
     cd /usr/src
    -svn co https://swig.svn.sourceforge.net/svnroot/swig/trunk swig
    +git clone https://github.com/swig/swig.git
     
    Pitfall note: -If you want to check out SWIG to a different folder to the proposed +If you want to place SWIG in a different folder to the proposed /usr/src/swig, do not use MSYS emulated windows drive letters, because the autotools will fail miserably on those.
  • +
  • +The PCRE third party library needs to be built next. +Download the latest PCRE source tarball, such as pcre-8.10.tar.bz2, from +PCRE and place in the /usr/src/swig directory. +Build PCRE as a static library using the Tools/pcre-build.sh script as follows: + +
    +cd /usr/src/swig
    +Tools/pcre-build.sh
    +
    +
  • +
  • You are now ready to build SWIG. Execute the following commands to build swig.exe:
    diff --git a/Doc/Manual/android-class.png b/Doc/Manual/android-class.png
    new file mode 100644
    index 000000000..f7061cb3a
    Binary files /dev/null and b/Doc/Manual/android-class.png differ
    diff --git a/Doc/Manual/android-simple.png b/Doc/Manual/android-simple.png
    new file mode 100644
    index 000000000..234674cba
    Binary files /dev/null and b/Doc/Manual/android-simple.png differ
    diff --git a/Doc/Manual/ch11.1.png b/Doc/Manual/ch11.1.png
    deleted file mode 100644
    index 2cc2becd4..000000000
    Binary files a/Doc/Manual/ch11.1.png and /dev/null differ
    diff --git a/Doc/Manual/ch11.2.png b/Doc/Manual/ch11.2.png
    deleted file mode 100644
    index e6d1b55ea..000000000
    Binary files a/Doc/Manual/ch11.2.png and /dev/null differ
    diff --git a/Doc/Manual/ch11.3.png b/Doc/Manual/ch11.3.png
    deleted file mode 100644
    index 54ee72442..000000000
    Binary files a/Doc/Manual/ch11.3.png and /dev/null differ
    diff --git a/Doc/Manual/ch12.1.png b/Doc/Manual/ch12.1.png
    deleted file mode 100644
    index 2072f06a4..000000000
    Binary files a/Doc/Manual/ch12.1.png and /dev/null differ
    diff --git a/Doc/Manual/ch9.table.2.png b/Doc/Manual/ch9.table.2.png
    deleted file mode 100644
    index ac6647e17..000000000
    Binary files a/Doc/Manual/ch9.table.2.png and /dev/null differ
    diff --git a/Doc/Manual/chapters b/Doc/Manual/chapters
    index cdd4ef635..fd21651e3 100644
    --- a/Doc/Manual/chapters
    +++ b/Doc/Manual/chapters
    @@ -16,8 +16,10 @@ Warnings.html
     Modules.html
     CCache.html
     Allegrocl.html
    +Android.html
     CSharp.html
     Chicken.html
    +D.html
     Go.html
     Guile.html
     Java.html
    @@ -31,8 +33,7 @@ Perl5.html
     Php.html
     Pike.html
     Python.html
    +R.html
     Ruby.html
     Tcl.html
    -R.html
     Extending.html
    -
    diff --git a/Doc/Manual/linkchecker.config b/Doc/Manual/linkchecker.config
    new file mode 100644
    index 000000000..a947b278a
    --- /dev/null
    +++ b/Doc/Manual/linkchecker.config
    @@ -0,0 +1,5 @@
    +[checking]
    +anchors=1
    +
    +[filtering]
    +ignorewarnings=http-robots-denied
    diff --git a/Doc/Manual/makechap.py b/Doc/Manual/makechap.py
    index 4dd048c36..8225bfc79 100644
    --- a/Doc/Manual/makechap.py
    +++ b/Doc/Manual/makechap.py
    @@ -1,4 +1,4 @@
    -#!/usr/local/bin/python
    +#!/usr/bin/env python
     
     ###############################################################################
     # Takes a chapter as input and adds internal links and numbering to all
    diff --git a/Doc/Manual/maketoc.py b/Doc/Manual/maketoc.py
    index c78bcfd13..d8c4aa759 100644
    --- a/Doc/Manual/maketoc.py
    +++ b/Doc/Manual/maketoc.py
    @@ -1,4 +1,4 @@
    -#!/usr/local/bin/python
    +#!/usr/bin/env python
     
     import sys
     import os
    @@ -12,7 +12,7 @@ print >>f, """
     SWIG Users Manual
     
     
    -

    SWIG Users Manual

    +

    SWIG Users Manual

    """ diff --git a/Examples/Makefile.in b/Examples/Makefile.in index 6dae4e461..c5e525c17 100644 --- a/Examples/Makefile.in +++ b/Examples/Makefile.in @@ -12,7 +12,7 @@ # certain packages have been installed. Set the prefixes # accordingly. # -# 2. To use this makefile, set required varibles, eg SRCS, INTERFACE, +# 2. To use this makefile, set required variables, eg SRCS, INTERFACE, # INTERFACEDIR, INCLUDES, LIBS, TARGET, and do a # $(MAKE) -f Makefile.template.in SRCS='$(SRCS)' \ # INCLUDES='$(INCLUDES) LIBS='$(LIBS)' INTERFACE='$(INTERFACE)' \ @@ -70,7 +70,7 @@ IOBJS = $(IWRAP:.i=.@OBJEXT@) CPP_DLLIBS = #-L/usr/local/lib/gcc-lib/sparc-sun-solaris2.5.1/2.7.2 \ -L/usr/local/lib -lg++ -lstdc++ -lgcc -# Solaris workshop 5.0 +# Solaris workshop 5.0 # CPP_DLLIBS = -L/opt/SUNWspro/lib -lCrun # Symbols used for using shared libraries @@ -160,7 +160,7 @@ tcl_cpp: $(SRCS) # ----------------------------------------------------------------- tcl_clean: - rm -f *_wrap* *~ .~* mytclsh@EXEEXT@ + rm -f *_wrap* *~ .~* mytclsh@EXEEXT@ rm -f core @EXTRA_CLEAN@ rm -f *.@OBJEXT@ *@SO@ @@ -297,9 +297,9 @@ python_static_cpp: $(SRCS) $(CXX) $(CXXFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) \ $(PYTHON_INCLUDE) $(LIBS) -L$(PYTHON_LIB) $(PYTHON_LIBOPTS) -o $(TARGET) -# ----------------------------------------------------------------- +# ----------------------------------------------------------------- # Running a Python example -# ----------------------------------------------------------------- +# ----------------------------------------------------------------- ifeq (,$(PY3)) PYSCRIPT = runme.py @@ -314,13 +314,14 @@ python_run: $(PYSCRIPT) runme3.py: runme.py cp $< $@ - $(PY2TO3) -w $@ >/dev/null 2>&1 + $(PY2TO3) -w $@ >/dev/null 2>&1 # ----------------------------------------------------------------- # Cleaning the python examples # ----------------------------------------------------------------- python_clean: + rm -rf __pycache__ rm -f *_wrap* *~ .~* mypython@EXEEXT@ *.pyc rm -f core @EXTRA_CLEAN@ rm -f *.@OBJEXT@ *@SO@ *@PYTHON_SO@ @@ -332,11 +333,11 @@ python_clean: ################################################################## # Make sure these locate your Octave installation -OCTAVE_INCLUDE= $(DEFS) @OCTAVEEXT@ -OCTAVE_LIB = +OCTAVE = OCTAVE_HISTFILE=/dev/null @OCTAVE@ -qfH +OCTAVE_CXX = $(DEFS) @OCTAVE_CPPFLAGS@ @OCTAVE_CXXFLAGS@ # Extra Octave specific dynamic linking options -OCTAVE_DLNK = @OCTAVEDYNAMICLINKING@ +OCTAVE_DLNK = @OCTAVE_LDFLAGS@ OCTAVE_SO = @OCTAVE_SO@ # ---------------------------------------------------------------- @@ -346,7 +347,7 @@ OCTAVE_SO = @OCTAVE_SO@ octave: $(SRCS) $(SWIG) -octave $(SWIGOPT) $(INTERFACEPATH) - $(CXX) -g -c $(CCSHARED) $(CXXFLAGS) $(ICXXSRCS) $(CXXSRCS) $(INCLUDES) -I$(OCTAVE_INCLUDE) + $(CXX) -g -c $(CCSHARED) $(CXXFLAGS) $(ICXXSRCS) $(INCLUDES) $(OCTAVE_CXX) $(CC) -g -c $(CCSHARED) $(CFLAGS) $(SRCS) $(CSRCS) $(INCLUDES) $(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(OCTAVE_DLNK) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(OCTAVE_SO) @@ -356,14 +357,24 @@ octave: $(SRCS) octave_cpp: $(SRCS) $(SWIG) -c++ -octave $(SWIGOPT) $(INTERFACEPATH) - $(CXX) -g -c $(CCSHARED) $(CXXFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) -I$(OCTAVE_INCLUDE) + $(CXX) -g -c $(CCSHARED) $(CXXFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) $(OCTAVE_CXX) $(CXXSHARED) -g $(CXXFLAGS) $(OBJS) $(IOBJS) $(OCTAVE_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(OCTAVE_SO) +# ----------------------------------------------------------------- +# Running an Octave example +# ----------------------------------------------------------------- + +OCTSCRIPT = runme.m + +octave_run: $(OCTSCRIPT) + env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH OCTAVE_PATH=$(srcdir):$$OCTAVE_PATH $(OCTAVE) $(OCTSCRIPT) >/dev/null + # ----------------------------------------------------------------- # Cleaning the octave examples # ----------------------------------------------------------------- octave_clean: + rm -rf __pycache__ rm -f *_wrap* *~ .~* myoctave@EXEEXT@ *.pyc rm -f core @EXTRA_CLEAN@ rm -f *.@OBJEXT@ *@SO@ *@OCTAVE_SO@ @@ -549,14 +560,14 @@ mzscheme: $(SRCS) mzscheme_cpp: $(SRCS) $(SWIG) -mzscheme -c++ $(SWIGOPT) $(INTERFACEPATH) $(COMPILETOOL) $(MZC) `echo $(INCLUDES) | sed 's/-I/++ccf -I/g'` --cc $(ICXXSRCS) $(SRCS) $(CXXSRCS) - $(CXXSHARED) $(CXXFLAGS) -o $(LIBPREFIX)$(TARGET)$(MZSCHEME_SO) $(OBJS) $(IOBJS) $(MZDYNOBJ) $(CPP_DLLIBS) + $(CXXSHARED) $(CXXFLAGS) -o $(LIBPREFIX)$(TARGET)$(MZSCHEME_SO) $(OBJS) $(IOBJS) $(MZDYNOBJ) $(CPP_DLLIBS) # ----------------------------------------------------------------- # Cleaning the mzscheme examples # ----------------------------------------------------------------- mzscheme_clean: - rm -f *_wrap* *~ .~* + rm -f *_wrap* *~ .~* rm -f core @EXTRA_CLEAN@ rm -f *.@OBJEXT@ *@SO@ @@ -633,7 +644,7 @@ ocaml_static_cpp: $(SRCS) $(OCAMLCORE) $(SWIG) -ocaml -c++ $(SWIGOPT) $(INTERFACEPATH) cp $(ICXXSRCS) $(ICXXSRCS:%.cxx=%.c) - $(OCC) -cc '$(CXX)' -g -c -ccopt -g -ccopt "-xc++ $(INCLUDES)" \ + $(OCC) -cc '$(CXX) -Wno-write-strings' -g -c -ccopt -g -ccopt "-xc++ $(INCLUDES)" \ $(ICXXSRCS:%.cxx=%.c) $(SRCS) $(CXXSRCS) $(OCC) -g -c $(INTERFACE:%.i=%.mli) $(OCC) -g -c $(INTERFACE:%.i=%.ml) @@ -644,13 +655,13 @@ ocaml_static_cpp: $(SRCS) $(INTERFACE:%.i=%.cmo) \ $(PROGFILE:%.ml=%.cmo) \ $(INTERFACE:%.i=%_wrap.@OBJEXT@) $(OBJS) \ - -cclib "$(LIBS)" -cc '$(CXX)' + -cclib "$(LIBS)" -cc '$(CXX) -Wno-write-strings' ocaml_static_cpp_toplevel: $(SRCS) $(OCAMLCORE) $(SWIG) -ocaml -c++ $(SWIGOPT) $(INTERFACEPATH) cp $(ICXXSRCS) $(ICXXSRCS:%.cxx=%.c) - $(OCC) -cc '$(CXX)' -g -c -ccopt -g -ccopt "-xc++ $(INCLUDES)" \ + $(OCC) -cc '$(CXX) -Wno-write-strings' -g -c -ccopt -g -ccopt "-xc++ $(INCLUDES)" \ $(ICXXSRCS:%.cxx=%.c) $(SRCS) $(CXXSRCS) $(OCC) -g -c $(INTERFACE:%.i=%.mli) $(OCC) -g -c $(INTERFACE:%.i=%.ml) @@ -658,17 +669,17 @@ ocaml_static_cpp_toplevel: $(SRCS) $(OCC) $(OCAMLPP) -c $(PROGFILE) $(NOLINK) || $(OCAMLMKTOP) \ swig.cmo \ - -I $(OCAMLP4WHERE) camlp4o.cma swigp4.cmo \ + -I $(OCAMLP4WHERE) dynlink.cma camlp4o.cma swigp4.cmo \ -g -ccopt -g -cclib -g -custom -o $(TARGET)_top \ $(INTERFACE:%.i=%.cmo) \ $(INTERFACE:%.i=%_wrap.@OBJEXT@) $(OBJS) \ - -cclib "$(LIBS)" -cc '$(CXX)' + -cclib "$(LIBS)" -cc '$(CXX) -Wno-write-strings' ocaml_dynamic_cpp: $(SRCS) $(OCAMLCORE) $(SWIG) -ocaml -c++ $(SWIGOPT) $(INTERFACEPATH) cp $(ICXXSRCS) $(ICXXSRCS:%.cxx=%.c) - $(OCC) -cc '$(CXX)' -g -c -ccopt -g -ccopt "-xc++ $(INCLUDES)" \ + $(OCC) -cc '$(CXX) -Wno-write-strings' -g -c -ccopt -g -ccopt "-xc++ $(INCLUDES)" \ $(ICXXSRCS:%.cxx=%.c) $(SRCS) $(CXXSRCS) -ccopt -fPIC $(CXXSHARED) $(CXXFLAGS) -o $(INTERFACE:%.i=%@SO@) \ $(INTERFACE:%.i=%_wrap.@OBJEXT@) $(OBJS) \ @@ -685,7 +696,7 @@ ocaml_dynamic_cpp: $(SRCS) $(OCC) -cclib -export-dynamic -g -ccopt -g -cclib -g -custom \ -o $(TARGET) \ -package dl -linkpkg \ - $(INTERFACE:%.i=%.cmo) $(PROGFILE:%.ml=%.cmo) -cc '$(CXX)' + $(INTERFACE:%.i=%.cmo) $(PROGFILE:%.ml=%.cmo) -cc '$(CXX) -Wno-write-strings' ocaml_clean: rm -f *_wrap* *~ .~* *.cmo *.cmi $(MLFILE) $(MLFILE)i swig.mli swig.cmi swig.ml swig.cmo swigp4.ml swigp4.cmo @@ -782,7 +793,7 @@ PHP=@PHP@ PHPSCRIPT ?= runme.php php_run: - env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) $(PHP) -n -q -d extension_dir=. -d safe_mode=Off $(PHPSCRIPT) + $(RUNTOOL) $(PHP) -n -q -d extension_dir=. -d safe_mode=Off $(PHPSCRIPT) # ----------------------------------------------------------------- # Cleaning the PHP examples @@ -845,7 +856,7 @@ pike_cpp_static: $(SRCS) # ----------------------------------------------------------------- pike_clean: - rm -f *_wrap* *~ .~* mypike@EXEEXT@ + rm -f *_wrap* *~ .~* mypike@EXEEXT@ rm -f core @EXTRA_CLEAN@ rm -f *.@OBJEXT@ *@SO@ @@ -862,7 +873,7 @@ CHICKEN_CFLAGS = @CHICKENOPTS@ CHICKENOPTS = -quiet CHICKEN_MAIN = -# SWIG produces $(ISRCS) (the C wrapper file) +# SWIG produces $(ISRCS) (the C wrapper file) # and $(CHICKEN_GENERATED_SCHEME) (the Scheme wrapper file): CHICKEN_GENERATED_SCHEME = $(INTERFACE:.i=.scm) CHICKEN_COMPILED_SCHEME = $(INTERFACE:.i=_chicken.c) @@ -1054,12 +1065,12 @@ lua_clean: allegrocl: $(SRCS) $(SWIG) -allegrocl -cwrap $(SWIGOPT) $(INTERFACEPATH) - $(CC) -c $(CCSHARED) $(CFLAGS) $(ISRCS) $(INCLUDES) $(SRCS) + $(CC) -c $(CCSHARED) $(CFLAGS) $(ISRCS) $(INCLUDES) $(SRCS) $(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(SO) allegrocl_cpp: $(SRCS) $(SWIG) -c++ -allegrocl $(SWIGOPT) $(INTERFACEPATH) - $(CXX) -c $(CCSHARED) $(CXXFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) + $(CXX) -c $(CCSHARED) $(CXXFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) $(CXXSHARED) $(CXXFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO) allegrocl_clean: @@ -1088,12 +1099,12 @@ clisp_clean: cffi: $(SRCS) $(SWIG) -cffi $(SWIGOPT) $(INTERFACEPATH) -# $(CC) -c $(CCSHARED) $(CFLAGS) $(ISRCS) $(INCLUDES) $(SRCS) +# $(CC) -c $(CCSHARED) $(CFLAGS) $(ISRCS) $(INCLUDES) $(SRCS) # $(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(SO) cffi_cpp: $(SRCS) $(SWIG) -c++ -cffi $(SWIGOPT) $(INTERFACEPATH) - $(CXX) -c $(CCSHARED) $(CXXFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) + $(CXX) -c $(CCSHARED) $(CXXFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) $(CXXSHARED) $(CXXFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO) cffi_clean: @@ -1107,12 +1118,12 @@ cffi_clean: uffi: $(SRCS) $(SWIG) -uffi $(SWIGOPT) $(INTERFACEPATH) -# $(CC) -c $(CCSHARED) $(CFLAGS) $(ISRCS) $(INCLUDES) $(SRCS) +# $(CC) -c $(CCSHARED) $(CFLAGS) $(ISRCS) $(INCLUDES) $(SRCS) # $(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(SO) uffi_cpp: $(SRCS) $(SWIG) -c++ -uffi $(SWIGOPT) $(INTERFACEPATH) -# $(CXX) -c $(CCSHARED) $(CXXFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) +# $(CXX) -c $(CCSHARED) $(CXXFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) # $(CXXSHARED) $(CXXFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO) uffi_clean: @@ -1127,14 +1138,25 @@ uffi_clean: R = R RCXXSRCS = $(INTERFACE:.i=_wrap.cpp) #Need to use _wrap.cpp for R build system as it does not understand _wrap.cxx RRSRC = $(INTERFACE:.i=.R) +R_CFLAGS=-fPIC + +# need to compile .cxx files outside of R build system to make sure that +# we get -fPIC +# CMD SHLIB stdout is piped to /dev/null to prevent echo of compiler command r: $(SRCS) $(SWIG) -r $(SWIGOPT) $(INTERFACEPATH) - +( PKG_CPPFLAGS="$(INCLUDES)" $(COMPILETOOL) $(R) CMD SHLIB -o $(LIBPREFIX)$(TARGET)$(SO) $(ISRCS) $(SRCS) ) +ifneq ($(SRCS),) + $(CC) -g -c $(CFLAGS) $(R_CFLAGS) $(SRCS) $(INCLUDES) +endif + +( PKG_CPPFLAGS="$(INCLUDES)" $(COMPILETOOL) $(R) CMD SHLIB -o $(LIBPREFIX)$(TARGET)$(SO) $(ISRCS) $(OBJS) > /dev/null ) r_cpp: $(CXXSRCS) $(SWIG) -c++ -r $(SWIGOPT) -o $(RCXXSRCS) $(INTERFACEPATH) - +( PKG_CPPFLAGS="$(INCLUDES)" $(COMPILETOOL) $(R) CMD SHLIB -o $(LIBPREFIX)$(TARGET)$(SO) $(RCXXSRCS) $(SRCS) $(CXXSRCS)) +ifneq ($(CXXSRCS),) + $(CXX) -g -c $(CFLAGS) $(R_CFLAGS) $(CXXSRCS) $(INCLUDES) +endif + +( PKG_CPPFLAGS="$(INCLUDES)" $(COMPILETOOL) $(R) CMD SHLIB -o $(LIBPREFIX)$(TARGET)$(SO) $(RCXXSRCS) $(OBJS) > /dev/null ) r_clean: rm -f *_wrap* *~ .~* @@ -1148,19 +1170,23 @@ r_clean: GO = @GO@ GOGCC = @GOGCC@ +GO1 = @GO1@ +GOC = @GOC@ +GOOPT = @GOOPT@ GOSWIGARG = `if $(GOGCC) ; then echo -gccgo; fi` -GOCOMPILEARG = `if $(GOGCC) ; then echo -c -g; fi` +GOCOMPILEARG = `if $(GOGCC) ; then echo -c -g; elif $(GO1) ; then echo tool $(GOC:c=g) ; fi` GOSRCS = $(INTERFACE:.i=.go) GOCSRCS = $(INTERFACE:.i=_gc.c) -GOC = $(GO:g=c) -GOLD = $(GO:g=l) +GOLD = $(GOC:c=l) +GOTOOL = `if $(GO1) ; then echo go tool; fi` +GOPACK = `if $(GO1) ; then echo go tool pack; else echo gopack; fi` GOPACKAGE = $(INTERFACE:.i=.a) -GOOBJEXT = $(GO:g=) +GOOBJEXT = $(GOC:c=) GOGCOBJS = $(GOSRCS:.go=.$(GOOBJEXT)) GOGCCOBJS = $(GOSRCS:.go=.@OBJEXT@) @@ -1169,13 +1195,13 @@ GOGCCOBJS = $(GOSRCS:.go=.@OBJEXT@) # ---------------------------------------------------------------- go: $(SRCS) - $(SWIG) -go $(GOSWIGARG) $(SWIGOPT) $(INTERFACEPATH) + $(SWIG) -go $(GOOPT) $(GOSWIGARG) $(SWIGOPT) $(INTERFACEPATH) $(CC) -g -c $(CCSHARED) $(CFLAGS) $(SRCS) $(ISRCS) $(INCLUDES) $(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(SO) - $(COMPILETOOL) $(GO) -I . $(GOCOMPILEARG) $(GOSRCS) + $(COMPILETOOL) $(GO) $(GOCOMPILEARG) -I . $(GOSRCS) if ! $(GOGCC) ; then \ - $(COMPILETOOL) $(GOC) -I $${GOROOT}/pkg/$${GOOS}_$${GOARCH} $(GOCSRCS) && \ - $(COMPILETOOL) gopack grc $(GOPACKAGE) $(GOGCOBJS) $(GOCSRCS:.c=.$(GOOBJEXT)); \ + $(COMPILETOOL) $(GOTOOL) $(GOC) -I $${GOROOT}/pkg/$${GOOS}_$${GOARCH} $(GOCSRCS) && \ + $(COMPILETOOL) $(GOPACK) grc $(GOPACKAGE) $(GOGCOBJS) $(GOCSRCS:.c=.$(GOOBJEXT)); \ fi # ---------------------------------------------------------------- @@ -1183,13 +1209,13 @@ go: $(SRCS) # ---------------------------------------------------------------- go_cpp: $(SRCS) - $(SWIG) -go -c++ $(GOSWIGARG) $(SWIGOPT) $(INTERFACEPATH) + $(SWIG) -go -c++ $(GOOPT) $(GOSWIGARG) $(SWIGOPT) $(INTERFACEPATH) $(CXX) -g -c $(CCSHARED) $(CXXFLAGS) $(SRCS) $(CXXSRCS) $(ICXXSRCS) $(INCLUDES) $(CXXSHARED) $(CXXFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO) - $(COMPILETOOL) $(GO) -I . $(GOCOMPILEARG) $(GOSRCS) + $(COMPILETOOL) $(GO) $(GOCOMPILEARG) -I . $(GOSRCS) if ! $(GOGCC) ; then \ - $(COMPILETOOL) $(GOC) -I $${GOROOT}/pkg/$${GOOS}_$${GOARCH} $(GOCSRCS) && \ - $(COMPILETOOL) gopack grc $(GOPACKAGE) $(GOGCOBJS) $(GOCSRCS:.c=.$(GOOBJEXT)); \ + $(COMPILETOOL) $(GOTOOL) $(GOC) -I $${GOROOT}/pkg/$${GOOS}_$${GOARCH} $(GOCSRCS) && \ + $(COMPILETOOL) $(GOPACK) grc $(GOPACKAGE) $(GOGCOBJS) $(GOCSRCS:.c=.$(GOOBJEXT)); \ fi # ----------------------------------------------------------------- @@ -1201,7 +1227,7 @@ go_run: runme.go if $(GOGCC) ; then \ $(COMPILETOOL) $(GO) -o runme runme.@OBJEXT@ $(GOGCCOBJS) $(LIBPREFIX)$(TARGET)$(SO); \ else \ - $(COMPILETOOL) $(GOLD) -r $${GOROOT}/pkg/$${GOOS}_$${GOARCH}:. -o runme runme.$(GOOBJEXT); \ + $(COMPILETOOL) $(GOTOOL) $(GOLD) -r $${GOROOT}/pkg/$${GOOS}_$${GOARCH}:. -o runme runme.$(GOOBJEXT); \ fi env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) ./runme @@ -1213,3 +1239,64 @@ go_clean: rm -f *_wrap* *_gc* .~* runme rm -f core @EXTRA_CLEAN@ rm -f *.@OBJEXT@ *.[568] *.a *@SO@ + +################################################################## +##### D ###### +################################################################## + +DLIBPREFIX = @DLIBPREFIX@ + +ifeq (,$(D_VERSION)) + D_VERSION = @DDEFAULTVERSION@ +endif + +ifeq (2,$(D_VERSION)) + SWIGD = $(SWIG) -d -d2 + DCOMPILER = @D2COMPILER@ +else + SWIGD = $(SWIG) -d + DCOMPILER = @D1COMPILER@ +endif + +# ---------------------------------------------------------------- +# Build a dynamically loadable D wrapper for a C module +# ---------------------------------------------------------------- + +d: $(SRCS) + $(SWIGD) $(SWIGOPT) $(INTERFACEPATH) + $(CC) -c $(CCSHARED) $(CFLAGS) $(DCFLAGS) $(EXTRA_CFLAGS) $(SRCS) $(ISRCS) $(INCLUDES) + $(LDSHARED) $(CFLAGS) $(DCFLAGS) $(EXTRA_LDFLAGS) $(OBJS) $(IOBJS) $(LIBS) -o $(DLIBPREFIX)$(TARGET)$(SO) + +# ---------------------------------------------------------------- +# Build a dynamically loadable D wrapper for a C++ module +# ---------------------------------------------------------------- + +d_cpp: $(SRCS) + $(SWIGD) -c++ $(SWIGOPT) $(INTERFACEPATH) + $(CXX) -c $(CCSHARED) $(CFLAGS) $(DCFLAGS) $(EXTRA_CFLAGS) $(SRCS) $(CXXSRCS) $(ICXXSRCS) $(INCLUDES) + $(CXXSHARED) $(CFLAGS) $(DCFLAGS) $(EXTRA_LDFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(CPP_DLLIBS) -o $(DLIBPREFIX)$(TARGET)$(SO) + +# ---------------------------------------------------------------- +# Compile D files +# ---------------------------------------------------------------- + +# Clear the DFLAGS environment variable for the compiler call itself +# to work around a discrepancy in argument handling between DMD and LDC. +d_compile: $(SRCS) + DFLAGS="" $(COMPILETOOL) $(DCOMPILER) $(DFLAGS) $(DSRCS) + +# ----------------------------------------------------------------- +# Run D example +# ----------------------------------------------------------------- + +d_run: + env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) ./runme + +# ----------------------------------------------------------------- +# Clean the D examples +# ----------------------------------------------------------------- + +d_clean: + rm -f *_wrap* *~ .~* runme runme.exe `find . -name \*.d | grep -v runme.d` + rm -f core @EXTRA_CLEAN@ + rm -f *.@OBJEXT@ *@SO@ diff --git a/Examples/android/check.list b/Examples/android/check.list new file mode 100644 index 000000000..0068e25ab --- /dev/null +++ b/Examples/android/check.list @@ -0,0 +1,4 @@ +# see top-level Makefile.in +class +extend +simple diff --git a/Examples/android/class/AndroidManifest.xml b/Examples/android/class/AndroidManifest.xml new file mode 100644 index 000000000..45c1fb1c7 --- /dev/null +++ b/Examples/android/class/AndroidManifest.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + diff --git a/Examples/android/class/Makefile b/Examples/android/class/Makefile new file mode 100644 index 000000000..2a3f0ec2d --- /dev/null +++ b/Examples/android/class/Makefile @@ -0,0 +1,30 @@ +TOP = ../.. +SWIG = $(TOP)/../preinst-swig +TARGET = example +INTERFACE = example.i +PACKAGEDIR = src/org/swig +PACKAGENAME= org.swig.classexample +SWIGOPT = -package $(PACKAGENAME) -outdir $(PACKAGEDIR)/classexample +PROJECTNAME= SwigClass +TARGETID = 1 +#INSTALLOPTIONS = -s # To install on SD Card + +all:: android + +android:: + android update project --target $(TARGETID) --name $(PROJECTNAME) --path . + $(SWIG) -c++ -java $(SWIGOPT) -o jni/$(TARGET)_wrap.cpp jni/$(INTERFACE) + ndk-build + ant debug + +install:: + -adb uninstall $(PACKAGENAME) + adb install $(INSTALLOPTIONS) bin/$(PROJECTNAME)-debug.apk + +clean:: + ant clean + rm -f jni/$(TARGET)_wrap.cpp + rm -f `find $(PACKAGEDIR) -name \*.java | grep -v $(PROJECTNAME).java` + + +check: all diff --git a/Examples/android/class/ant.properties b/Examples/android/class/ant.properties new file mode 100644 index 000000000..ee52d86d9 --- /dev/null +++ b/Examples/android/class/ant.properties @@ -0,0 +1,17 @@ +# This file is used to override default values used by the Ant build system. +# +# This file must be checked in Version Control Systems, as it is +# integral to the build system of your project. + +# This file is only used by the Ant script. + +# You can use this to override default values such as +# 'source.dir' for the location of your java source folder and +# 'out.dir' for the location of your output folder. + +# You can also use it define how the release builds are signed by declaring +# the following properties: +# 'key.store' for the location of your keystore and +# 'key.alias' for the name of the key to use. +# The password will be asked during the build when you use the 'release' target. + diff --git a/Examples/android/class/build.xml b/Examples/android/class/build.xml new file mode 100644 index 000000000..fe06943a9 --- /dev/null +++ b/Examples/android/class/build.xml @@ -0,0 +1,85 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Examples/android/class/jni/Android.mk b/Examples/android/class/jni/Android.mk new file mode 100644 index 000000000..25d42b541 --- /dev/null +++ b/Examples/android/class/jni/Android.mk @@ -0,0 +1,10 @@ +# File: Android.mk +LOCAL_PATH := $(call my-dir) + +include $(CLEAR_VARS) + +LOCAL_MODULE := example +LOCAL_SRC_FILES := example_wrap.cpp example.cpp +LOCAL_CFLAGS := -frtti + +include $(BUILD_SHARED_LIBRARY) diff --git a/Examples/android/class/jni/example.cpp b/Examples/android/class/jni/example.cpp new file mode 100644 index 000000000..d59cc7c32 --- /dev/null +++ b/Examples/android/class/jni/example.cpp @@ -0,0 +1,28 @@ +/* File : example.cpp */ + +#include "example.h" +#define M_PI 3.14159265358979323846 + +/* Move the shape to a new location */ +void Shape::move(double dx, double dy) { + x += dx; + y += dy; +} + +int Shape::nshapes = 0; + +double Circle::area(void) { + return M_PI*radius*radius; +} + +double Circle::perimeter(void) { + return 2*M_PI*radius; +} + +double Square::area(void) { + return width*width; +} + +double Square::perimeter(void) { + return 4*width; +} diff --git a/Examples/android/class/jni/example.h b/Examples/android/class/jni/example.h new file mode 100644 index 000000000..64b7684fa --- /dev/null +++ b/Examples/android/class/jni/example.h @@ -0,0 +1,34 @@ +/* File : example.h */ + +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); +}; diff --git a/Examples/android/class/jni/example.i b/Examples/android/class/jni/example.i new file mode 100644 index 000000000..fbdf7249f --- /dev/null +++ b/Examples/android/class/jni/example.i @@ -0,0 +1,9 @@ +/* File : example.i */ +%module example + +%{ +#include "example.h" +%} + +/* Let's just grab the original header file here */ +%include "example.h" diff --git a/Examples/android/class/local.properties b/Examples/android/class/local.properties new file mode 100644 index 000000000..14b8d63b4 --- /dev/null +++ b/Examples/android/class/local.properties @@ -0,0 +1,10 @@ +# This file is automatically generated by Android Tools. +# Do not modify this file -- YOUR CHANGES WILL BE ERASED! +# +# This file must *NOT* be checked in Version Control Systems, +# as it contains information specific to your local configuration. + +# location of the SDK. This is only used by Ant +# For customization when using a Version Control System, please read the +# header note. +sdk.dir=/home/william/android/android-sdk-linux_x86 diff --git a/Examples/android/class/proguard.cfg b/Examples/android/class/proguard.cfg new file mode 100644 index 000000000..b1cdf17b5 --- /dev/null +++ b/Examples/android/class/proguard.cfg @@ -0,0 +1,40 @@ +-optimizationpasses 5 +-dontusemixedcaseclassnames +-dontskipnonpubliclibraryclasses +-dontpreverify +-verbose +-optimizations !code/simplification/arithmetic,!field/*,!class/merging/* + +-keep public class * extends android.app.Activity +-keep public class * extends android.app.Application +-keep public class * extends android.app.Service +-keep public class * extends android.content.BroadcastReceiver +-keep public class * extends android.content.ContentProvider +-keep public class * extends android.app.backup.BackupAgentHelper +-keep public class * extends android.preference.Preference +-keep public class com.android.vending.licensing.ILicensingService + +-keepclasseswithmembernames class * { + native ; +} + +-keepclasseswithmembers class * { + public (android.content.Context, android.util.AttributeSet); +} + +-keepclasseswithmembers class * { + public (android.content.Context, android.util.AttributeSet, int); +} + +-keepclassmembers class * extends android.app.Activity { + public void *(android.view.View); +} + +-keepclassmembers enum * { + public static **[] values(); + public static ** valueOf(java.lang.String); +} + +-keep class * implements android.os.Parcelable { + public static final android.os.Parcelable$Creator *; +} diff --git a/Examples/android/class/project.properties b/Examples/android/class/project.properties new file mode 100644 index 000000000..ea89160e0 --- /dev/null +++ b/Examples/android/class/project.properties @@ -0,0 +1,11 @@ +# This file is automatically generated by Android Tools. +# Do not modify this file -- YOUR CHANGES WILL BE ERASED! +# +# This file must be checked in Version Control Systems. +# +# To customize properties used by the Ant build system use, +# "ant.properties", and override values to adapt the script to your +# project structure. + +# Project target. +target=android-8 diff --git a/Examples/android/class/res/layout/main.xml b/Examples/android/class/res/layout/main.xml new file mode 100644 index 000000000..d4e5d7fe8 --- /dev/null +++ b/Examples/android/class/res/layout/main.xml @@ -0,0 +1,25 @@ + + +