diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 000000000..596615322 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +.gitattributes export-ignore +.gitignore export-ignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..c375a7c77 --- /dev/null +++ b/.gitignore @@ -0,0 +1,130 @@ +# 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/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 +/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 +CCache/ccache-swig.1 +Lib/swigwarn.swg +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/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 + +# Scratch directories +Examples/scratch diff --git a/.project b/.project deleted file mode 100644 index a7f89f57a..000000000 --- a/.project +++ /dev/null @@ -1,32 +0,0 @@ - - - SWIG - - - - - - org.eclipse.cdt.autotools.core.genmakebuilderV2 - - - - - org.eclipse.cdt.managedbuilder.core.genmakebuilder - - - - - org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder - full,incremental, - - - - - - org.eclipse.cdt.core.cnature - org.eclipse.cdt.core.ccnature - org.eclipse.cdt.managedbuilder.core.managedBuildNature - org.eclipse.cdt.managedbuilder.core.ScannerConfigNature - org.eclipse.cdt.autotools.core.autotoolsNatureV2 - - diff --git a/.travis.yml b/.travis.yml index c41027bc0..7983d0ecd 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,8 +1,73 @@ language: cpp compiler: - - gcc - clang -script: ./autogen.sh && ./configure && make -s + - gcc +env: + - SWIGLANG= +matrix: + include: + - compiler: gcc + env: SWIGLANG=csharp + - compiler: gcc + env: SWIGLANG=go + - compiler: gcc + env: SWIGLANG=guile + - compiler: gcc + env: SWIGLANG=java + - compiler: gcc + env: SWIGLANG=lua + - compiler: gcc + env: SWIGLANG=octave SWIGJOBS=-j4 + - compiler: gcc + env: SWIGLANG=perl5 + - compiler: gcc + env: SWIGLANG=php + - compiler: gcc + env: SWIGLANG=python VER=2.4 + - compiler: gcc + env: SWIGLANG=python VER=2.5 + - compiler: gcc + env: SWIGLANG=python VER=2.6 + - compiler: gcc + env: SWIGLANG=python # 2.7 + - compiler: gcc + env: SWIGLANG=python PY3=3 # 3.2 + - compiler: gcc + env: SWIGLANG=python PY3=3 VER=3.3 + - compiler: gcc + env: SWIGLANG=python PY3=3 VER=3.4 + - compiler: gcc + env: SWIGLANG=ruby + - compiler: gcc + env: SWIGLANG=tcl + allow_failures: + # None +before_install: + - date -u + - lsb_release -a + - uname -a + - sudo apt-get -qq update + - time sudo apt-get -qq install libboost-dev + - if test -z "$SWIGLANG"; then sudo apt-get -qq install yodl; fi + - if test "$SWIGLANG" = "csharp"; then sudo apt-get -qq install mono-devel; fi + - if test "$SWIGLANG" = "go"; then go env | sed -e 's/^/export /' > goenvsetup && source goenvsetup && rm -f goenvsetup; fi # Until configure.ac is fixed + - if test "$SWIGLANG" = "guile"; then sudo apt-get -qq install guile-2.0-dev; fi + - if test "$SWIGLANG" = "lua"; then sudo apt-get -qq install lua5.1 liblua5.1-dev; fi + - if test "$SWIGLANG" = "octave"; then sudo apt-get -qq install octave3.2 octave3.2-headers; fi + - if test "$SWIGLANG" = "php"; then sudo apt-get install php5-cli php5-dev; fi + - if test "$SWIGLANG" = "python" -a "$PY3" -a -z "$VER"; then sudo apt-get install -qq python3-dev; fi + - if test "$SWIGLANG" = "python" -a "$VER"; then sudo add-apt-repository -y ppa:fkrull/deadsnakes && sudo apt-get -qq update && sudo apt-get -qq install python${VER}-dev && export CONFIGOPTS="--with-python${PY3}=python${VER}"; fi + - if test "$SWIGLANG" = "tcl"; then sudo apt-get -qq install tcl8.4-dev; fi +script: + - ./autogen.sh && ./configure $CONFIGOPTS + - make -s $SWIGJOBS + - ./swig -version && ./swig -pcreversion + - if test -z "$SWIGLANG"; then make -s $SWIGJOBS check-ccache; fi + - if test -z "$SWIGLANG"; then make -s $SWIGJOBS check-errors-test-suite; fi + - if test -z "$SWIGLANG"; then sudo make -s install && swig -version && ccache-swig -V; fi + - if test -n "$SWIGLANG"; then make -s check-$SWIGLANG-version; fi + - if test -n "$SWIGLANG"; then make -k $SWIGJOBS check-$SWIGLANG-examples; fi + - if test -n "$SWIGLANG"; then make -k $SWIGJOBS check-$SWIGLANG-test-suite; fi branches: only: - master diff --git a/ANNOUNCE b/ANNOUNCE index 825837614..6229edc4a 100644 --- a/ANNOUNCE +++ b/ANNOUNCE @@ -1,31 +1,31 @@ -*** ANNOUNCE: SWIG 2.0.6 (30 April 2012) *** +*** ANNOUNCE: SWIG 3.0.1 (in progress) *** http://www.swig.org -We're pleased to announce SWIG-2.0.6, the latest SWIG release. +We're pleased to announce SWIG-3.0.1, 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), D, 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.6.tar.gz + http://prdownloads.sourceforge.net/swig/swig-3.0.1.tar.gz A Windows version is also available at - http://prdownloads.sourceforge.net/swig/swigwin-2.0.6.zip + http://prdownloads.sourceforge.net/swig/swigwin-3.0.1.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/ccache.h b/CCache/ccache.h index 668ce8288..dcbb03f0c 100644 --- a/CCache/ccache.h +++ b/CCache/ccache.h @@ -159,7 +159,7 @@ int asprintf(char **ptr, const char *format, ...); int snprintf(char *,size_t ,const char *, ...); #endif -void cleanup_dir(const char *dir, size_t maxfiles, size_t maxsize); +void cleanup_dir(const char *dir, size_t maxfiles, size_t maxsize, size_t minfiles); void cleanup_all(const char *dir); void wipe_all(const char *dir); @@ -200,6 +200,8 @@ typedef int (*COMPAR_FN_T)(const void *, const void *); /* mkstemp() on some versions of cygwin don't handle binary files, so override */ +/* Seems okay in Cygwin 1.7.0 #ifdef __CYGWIN__ #undef HAVE_MKSTEMP #endif +*/ diff --git a/CCache/cleanup.c b/CCache/cleanup.c index 99312283e..f54ee54d9 100644 --- a/CCache/cleanup.c +++ b/CCache/cleanup.c @@ -75,21 +75,40 @@ static void traverse_fn(const char *fname, struct stat *st) /* sort the files we've found and delete the oldest ones until we are below the thresholds */ -static void sort_and_clean(void) +static void sort_and_clean(size_t minfiles) { unsigned i; + size_t adjusted_minfiles = minfiles; if (num_files > 1) { /* sort in ascending data order */ qsort(files, num_files, sizeof(struct files *), (COMPAR_FN_T)files_compare); } + /* ensure newly cached files (minfiles) are kept - instead of matching + the filenames of those newly cached, a faster and simpler approach + assumes these are the most recent in the cache and if any other + cached files have an identical time stamp, they will also be kept - + this approach would not be needed if the cleanup was done at exit. */ + if (minfiles != 0 && minfiles < num_files) { + unsigned minfiles_index = num_files - minfiles; + time_t minfiles_time = files[minfiles_index]->mtime; + for (i=1; i<=minfiles_index; i++) { + if (files[minfiles_index-i]->mtime == minfiles_time) + adjusted_minfiles++; + else + break; + } + } /* delete enough files to bring us below the threshold */ for (i=0;ifname) != 0 && errno != ENOENT) { fprintf(stderr, "unlink %s - %s\n", files[i]->fname, strerror(errno)); @@ -103,7 +122,7 @@ static void sort_and_clean(void) } /* cleanup in one cache subdir */ -void cleanup_dir(const char *dir, size_t maxfiles, size_t maxsize) +void cleanup_dir(const char *dir, size_t maxfiles, size_t maxsize, size_t minfiles) { unsigned i; @@ -117,7 +136,7 @@ void cleanup_dir(const char *dir, size_t maxfiles, size_t maxsize) traverse(dir, traverse_fn); /* clean the cache */ - sort_and_clean(); + sort_and_clean(minfiles); stats_set_sizes(dir, total_files, total_size); @@ -151,7 +170,8 @@ void cleanup_all(const char *dir) cleanup_dir(dname, counters[STATS_MAXFILES], - counters[STATS_MAXSIZE]); + counters[STATS_MAXSIZE], + 0); free(dname); free(sfile); } 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/CCache/stats.c b/CCache/stats.c index 92bc4a835..d2122bcd3 100644 --- a/CCache/stats.c +++ b/CCache/stats.c @@ -168,7 +168,8 @@ static void stats_update_size(enum stats stat, size_t size, size_t numfiles) if (need_cleanup) { char *p = dirname(stats_file); - cleanup_dir(p, counters[STATS_MAXFILES], counters[STATS_MAXSIZE]); + cleanup_dir(p, counters[STATS_MAXFILES], counters[STATS_MAXSIZE], + numfiles); free(p); } } diff --git a/CCache/test.sh b/CCache/test.sh index 9581c85e3..f64c3e3de 100755 --- a/CCache/test.sh +++ b/CCache/test.sh @@ -142,7 +142,7 @@ basetests() { testname="non-regular" mkdir testd $CCACHE_COMPILE -o testd -c test1.c > /dev/null 2>&1 - rmdir testd + rm -rf testd checkstat 'output to a non-regular file' 1 testname="no-input" @@ -315,7 +315,7 @@ swigtests() { testname="non-regular" mkdir testd $CCACHE_COMPILE -o testd -java testswig1.i > /dev/null 2>&1 - rmdir testd + rm -rf testd checkstat 'output to a non-regular file' 1 testname="no-input" diff --git a/CCache/util.c b/CCache/util.c index bba232492..66f9823b9 100644 --- a/CCache/util.c +++ b/CCache/util.c @@ -82,7 +82,7 @@ void copy_fd(int fd_in, int fd_out) #ifndef HAVE_MKSTEMP /* cheap and nasty mkstemp replacement */ -static int mkstemp(char *template) +int mkstemp(char *template) { mktemp(template); return open(template, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600); diff --git a/CHANGES b/CHANGES index 70af78333..821d76b2c 100644 --- a/CHANGES +++ b/CHANGES @@ -3,6 +3,1220 @@ 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 3.0.0 (16 Mar 2014) +=========================== + +2014-03-16: wsfulton + C++11 support initially developed as C++0x support by Matevz Jekovec as a Google Summer of Code + project has been further extended. The C++11 support is comprehensive, but by no means complete + or without limitations. Full details for each new feature in C++11 is covered in the + CPlusPlus11.html chapter in the documentation which is included in SWIG and also available + online at http://www.swig.org/Doc3.0/CPlusPlus11.html. + +2014-03-14: v-for-vandal + [Lua] Numerous Lua improvements: + 1. %nspace support has been added. Namespaces are mapped to tables in the module, with the same + name as the C++ namespace. + 2. Inheritance is now handled differently. Each class metatable keeps a list of class bases instead + of merging all members of all bases into the derived class. + 3. The new metatables result in differences in accessing class members. For example: + + %module example + struct Test { + enum { TEST1 = 10, TEST2 = 20 }; + static const int ICONST = 12; + }; + + Now this can be used as follows: + print(example.Test.TEST1) + print(example.Test.ICONST) + The old way was: + print(example.Test_TEST1) + print(example.Test_ICONST) + + 4. The special class metatable member ".constructor" was removed. Now SWIG generates the proxy + function by itself and assigns it directly to the class table "__call" method. + 5. eLua should also now support inheritance. + 6. 'const' subtable in eLua is considered deprecated. + + Changes in behaviour: + a. You can no longer assign to non-existing class members in classes without a __setitem__ method. + It will cause a Lua error. + b. You can no longer iterate over a module table and copy everything into the global namespace. + Actually, this was never the case, but it is now explicitly prohibited. + c. Now changing a base class will immediately affect all derived classes. + d. There might be some issues with inheritance. Although the bases iteration scheme is the same + as was used for merging base classes into derived one, some unknown issues may arise. + + The old metatable behaviour can be restored by using the -no-old-metatable-bindings option. + + *** POTENTIAL INCOMPATIBILITY *** + +2014-03-06: wsfulton + [Python] Change in default behaviour wrapping C++ bool. Only a Python True or False + will now work for C++ bool parameters. This fixes overloading bool with other types. + Python 2.3 minimum is now required for wrapping bool. + + When wrapping: + + const char* overloaded(bool value) { return "bool"; } + const char* overloaded(int value) { return "int"; } + + Previous behaviour: + >>> overloaded(False) + 'int' + >>> overloaded(True) + 'int' + >>> overloaded(0) + 'int' + + Now we get the expected behaviour: + >>> overloaded(False) + 'bool' + >>> overloaded(0) + 'int' + + The consequence is when wrapping bool in non-overloaded functions: + + const char* boolfunction(bool value) { return value ? "true" : "false"; } + + The previous behaviour was very Pythonic: + >>> boolfunction("") + 'false' + >>> boolfunction("hi") + 'true' + >>> boolfunction(12.34) + 'true' + >>> boolfunction(0) + 'false' + >>> boolfunction(1) + 'true' + + Now the new behaviour more along the lines of C++ due to stricter type checking. The + above calls result in an exception and need to be explicitly converted into a bool as + follows: + >>> boolfunction(0) + Traceback (most recent call last): + File "", line 1, in + TypeError: in method 'boolfunction', argument 1 of type 'bool' + >>> boolfunction(bool(0)) + 'false' + + The old behaviour can be resurrected by passing the -DSWIG_PYTHON_LEGACY_BOOL command line + parameter when executing SWIG. Typemaps can of course be written to customise the behaviour + for specific parameters. + + *** POTENTIAL INCOMPATIBILITY *** + +2014-03-06: wsfulton + Fix SF Bug #1363 - Problem with method overloading when some methods are added by %extend + and others are real methods and using template default parameters with smart pointers. + This is noticeable as a regression since 2.0.12 when using the default smart pointer + handling for some languages when the smart pointer wraps std::map and other STL containers. + +2014-03-02: wsfulton + [Python] SF Patch #346 from Jens Krueger. Correct exception thrown attempting to + access a non-existent C/C++ global variable on the 'cvar' object. The exception thrown + used to be a NameError. However, as this access is via a primary, an AttributeError + is more correct and so the exception thrown now is an AttributeError. Reference: + http://docs.python.org/2/reference/expressions.html#attribute-references + + *** POTENTIAL INCOMPATIBILITY *** + +2014-03-01: wsfulton + [Python] Patch #143 Fix type shown when using type() to include the module and package + name when using -builtin. + +2014-03-01: wsfulton + [Python] SF patch #347 Fix missing argument count checking with -modern. + Fixes regression introduced when builtin changes were introduced in SWIG-2.0.3. + +2014-02-21: wsfulton + [PHP] Fix warning suppression using %warnfilter for PHP reserved class names. + +2014-02-19: olly + [Lua] Add keyword warnings for Lua keywords and Basic Functions. + +2014-02-19: olly + -Wallkw now includes keywords for all languages with keyword + warnings (previously Go and R were missing). + +2014-02-19: olly + [PHP] Update the lists of PHP keywords with new ones from PHP 5.4 + and newer (and some missing ones from 5.3). Reserved PHP constants + names are now checked against enum values and constants, instead + of against function and method names. Built-in PHP function names + no longer match methods added by %extend. Functions and methods + named '__sleep', '__wakeup', 'not', 'parent', or 'virtual' are no + longer needlessly renamed. + +2014-02-15: wsfulton + Fix the %$ismember %rename predicates to also apply to members added via %extend. + + Add %$isextendmember for %rename of members added via %extend. This can be used to + distinguish between normal class/struct members and %extend members. For example + '%$ismember, %$not %$isextendmember' will now identify just class/struct members. + + *** POTENTIAL INCOMPATIBILITY *** + +2014-02-16: hfalcic + [Python] Patch #137 - fix crashes/exceptions in exception handling in Python 3.3 + +2014-02-15: wsfulton + [Java] Add support for the cdata library. + +2014-02-08: vkalinin + Nested class support added. This primarily allows SWIG to properly parse nested + classes and keep the nested class information in the parse tree. Java and C# + have utilised this information wrapping the C++ nested classes as Java/C# + nested classes. The remaining target languages ignore nested classes as in + previous versions. Help is needed by users of these remaining languages to + design how C++ nested classes can be best wrapped. Please talk to us on the + swig-devel mailing list if you think you can help. + + Previously, there was limited nested class support. Nested classes were treated + as opaque pointers. However, the "nestedworkaround" feature provided a way to + wrap a nested class as if it was a global class. This feature no longer exists + and is replaced by the new "flatnested" feature. This effectively does the same + thing with less manual code to be written. Please see the 'Nested classes' + section in the documentation in SWIGPlus.html if you were previously using this + feature. + + SWIG now parses the contents of nested classes where previously it did not. You + may find that you will need to make adjustments to your interface file as + effectively extra code is being wrapped. + + *** POTENTIAL INCOMPATIBILITY *** + +2014-02-06: gjanssens + [Guile] Patch #133. Make scm to string conversion work with non-ascii strings. + Guile 2 has a completely rewritten string implementation. SWIG made some assumptions + that are no longer valid as to the internals of guile's string representation. + +2014-01-30: wsfulton + [C#] Add new swigtype_inout.i library containing SWIGTYPE *& OUTPUT typemaps. + + Example usage wrapping: + + void f(XXX *& x) { x = new XXX(111); } + + would be: + + XXX x = null; + f(out x); + // use x + x.Dispose(); // manually clear memory or otherwise leave out and leave it to the garbage collector + +2014-01-21: ianlancetaylor + [Go] Add %go_import directive. + +2014-01-21: ianlancetaylor + [Go] Add support for Go 1.3, not yet released. + +2014-01-20: wsfulton + Director exceptions (Swig::DirectorException) now derive from std::exception + and hence provide the what() method. In Python and Ruby, this replaces the now + deprecated DirectorException::getMessage() method. + +2014-01-14: diorcety + Patch #112 - Fix symbol resolution involving scopes that have multiple levels + of typedefs - fixes some template resolutions as well as some typemap searches. + +2014-01-11: wsfulton + Fix and document the naturalvar feature override behaviour - the naturalvar + feature attached to a variable name has precedence over the naturalvar + feature attached to the variable's type. The overriding was not working + when turning the feature off on the variable's name. + + Fix so that any use of the naturalvar feature will override the global + setting. Previously when set globally by -naturalvar or %module(naturalvar=1), + use of the naturalvar feature was not always honoured. + +2014-01-06: ianlancetaylor + [Go] Fix bug that broke using directors from a thread not + created by Go. + +2013-12-24: ptomulik + [Python] SF Bug #1297 + + Resolve several issues related to python imports. + For example, it's now possible to import modules having the same module + names, but belonging in different packages. + + From the user's viewpoint, this patch gives a little bit more control on + import statements generated by SWIG. The user may choose to use relative + or absolute imports. + + Some details: + - we (still) generate import statements in the form 'import a.b.c' which + corresponds to absolute imports in python3 and (the only available) + ambiguous one in python2. + - added -relativeimport option to use explicit relative import syntax + (python3), + + The "Python Packages" section in the documentation discusses how to work + with importing packages including the new -relativeimport command line option. + +2013-12-23: vadz + [Octave, Perl, Python, R, Ruby, Tcl] Change the length of strings created from fixed-size char + buffers in C code. + + This is a potential backwards compatibility break: a "char buf[5]" containing "ho\0la" was + returned as a string of length 5 before, but is returned as a string of length 2 now. Also, + it was possible to assign a (non-NUL-terminated) string "hello" to such a buffer before but + now this fails and only "helo" can fit. + + Apply "char FIXSIZE[ANY]" typemaps to explicitly choose the old behaviour. + + *** POTENTIAL INCOMPATIBILITY *** + +2013-12-23: talby + [Perl] Add support for directors. + +2013-12-18: ianlancetaylor + [Go] Don't require that Go environment variables be set + when running examples or testsuite when using Go 1 or + later. + +2013-12-17: ianlancetaylor + [Go] Remove -longsize option (for backward compatibility, + ignore it if seen). + +2013-12-17: ianlancetaylor + [Go] Add -go-pkgpath option. + +2013-12-16: ianlancetaylor + [Go] Update for Go 1.2 release. Add support for linking + SWIG code directly into executable, rather than using a + shared library. + +2013-12-13: ianlancetaylor + [Go] Add SWIG source file name as comments in generated + files. This can be used by Go documentation tools. + +2013-12-12: jleveque + [Lua] Fix typo (wchar instead of wchar_t) which made wchar.i + for Lua useless. + +2013-12-12: vmiklos + [PHP] PHP's peculiar call-time pass-by-reference feature was + deprecated in PHP 5.3 and removed in PHP 5.4, so update the REF + typemaps in phppointers.i to specify pass-by-reference in the + function definition. Examples/php/pointer has been updated + accordingly. + +2013-12-12: olly + [PHP] The usage of $input in PHP directorout typemaps has been + changed to be consistent with other languages. The typemaps + provided by SWIG have been updated accordingly, but if you + have written your own directorout typemaps, you'll need to + update $input to &$input (or make equivalent changes). + + *** POTENTIAL INCOMPATIBILITY *** + +2013-11-27: vadz + [C#, Java, Python] Add std_auto_ptr.i defining typemaps for returning std::auto_ptr<>. + +2013-11-09: wsfulton + [C#] Apply patch #79 from Brant Kyser + - Remove using directives from the generated C# code and fully qualify the use of all .NET + framework types in order to minimize potential name collisions from input files defining + types, namespace, etc with the same name as .NET framework members. + - Globally qualify the use of .NET framework types in the System namespace + - Remove .NET 1.1 support, .NET 2 is the minimum for the C# module + + This is a potential backwards compatibility break if code has been added relying on these using + statements that used to be generated: + + using System; + using System.Runtime.InteropServices; + + The quick fix to add these back in is to add the -DSWIG2_CSHARP command line option when + executing SWIG. See CSharp.html documentation for more info. + + *** POTENTIAL INCOMPATIBILITY *** + +2013-11-05: wsfulton + [Java] Fix some corner cases for the $packagepath/$javaclassname special variable substitution. + +2013-11-05: wsfulton + [Java] Apply patch #91 from Marvin Greenberg - Add director:except feature for improved + exception handling in director methods for Java. + +2013-10-15: vadz + Allow using \l, \L, \u, \U and \E in the substitution part of %(regex:/pattern/subst/) + inside %rename to change the case of the text being replaced. + +2013-10-12: wsfulton + [CFFI] Apply #96 - superclass not lispify + +2013-10-12: wsfulton + Merge in C++11 support from the gsoc2009-matevz branch where Matevz Jekovec first + started the C++0x additions. Documentation of the C++11 features supported is in a + new Chapter of the documentation, "SWIG and C++11" in Doc/Manual/CPlusPlus11.html. + +2013-10-04: wsfulton + Fix %naturalvar not having any affect on templated classes instantiated with an + enum as the template parameter type. Problem reported by Vadim Zeitlin. + +2013-09-20: wsfulton + [Java] Fix a memory leak for the java char **STRING_ARRAY typemaps. + +Version 2.0.12 (9 Feb 2014) +=========================== + +2014-01-16: wsfulton + [PHP] Fix compilation error in ZTS mode (64 bit windows) due to incorrect placement + of TSRMLS_FETCH() in SWIG_Php_GetModule() as reported by Mark Dawson-Butterworth. + +2014-01-13: kwwette + [Octave] update support to Octave version 3.8.0 + + - Octave 3.8.0 no longer defines OCTAVE_API_VERSION_NUMBER, but 3.8.1 + will define OCTAVE_{MAJOR,MINOR,PATCH}_VERSION instead: see + http://hg.savannah.gnu.org/hgweb/octave/rev/b6b6e0dc700e + So we now use a new macro SWIG_OCTAVE_PREREQ(major,minor,patch) to + enable features requiring Octave version major.minor.patch or later. + + For Octave versions prior to 3.8.1, we reconstruct values for + OCTAVE_{MAJOR,MINOR,PATCH}_VERSION based on OCTAVE_API_VERSION_NUMBER, + extracted from Octave's ChangeLogs. An additional hack is needed to + distinguish between Octave <= 3.2.x and 3.8.0, neither of which define + OCTAVE_API_VERSION_NUMBER. + + - Octave 3.8.0 deprecates symbol_table::varref(), so remove its use + for this and future versions of Octave. + + - Octave 3.8.0 removes octave_value::is_real_nd_array(), used in + octave_swig_type::dims(). Its use is not required here, so remove it. + + - Retested against Octave versions 3.0.5, 3.2.4, 3.4.3, 3.6.4, and 3.8.0. + + - Updated Octave documentation with tested Octave versions, and added a + warning against using versions <= 3.x.x, which are no longer tested. + +2013-12-22: wsfulton + C++11 support for new versions of erase and insert in the STL containers. + + The erase and insert methods in the containers use const_iterator instead + of iterator in C++11. There are times when the methods wrapped must match + the parameters exactly. Specifically when full type information for + template types is missing or SWIG fails to look up the type correctly, + for example: + + %include + typedef float Real; + %template(RealVector) std::vector; + + SWIG does not find std::vector::iterator because %template using + typedefs does not always work and so SWIG doesn't know if the type is + copyable and so uses SwigValueWrapper which does + not support conversion to another type (const_iterator). This resulted + in compilation errors when using the C++11 version of the containers. + + Closes #73 + +2013-10-17: wsfulton + [R] Fix SF #1340 - Visual Studio compile error in C++ wrappers due to #include + within extern "C" block. + +2013-10-17: wsfulton + [Python] Fix SF #1345 - Missing #include for offsetof when using -builtin. + +2013-10-12: wsfulton + [Lua] Apply #92 - missing return statements for SWIG_Lua_add_namespace_details() + and SWIG_Lua_namespace_register(). + +Version 2.0.11 (15 Sep 2013) +============================ + +2013-09-15: wsfulton + [R] Fix attempt to free a non-heap object in OUTPUT typemaps for: + unsigned short *OUTPUT + unsigned long *OUTPUT + signed long long *OUTPUT + char *OUTPUT + signed char*OUTPUT + unsigned char*OUTPUT + +2013-09-12: wsfulton + [Lua] Pull Git patch #62. + 1) Static members and static functions inside class can be accessed as + ModuleName.ClassName.FunctionName (MemberName respectively). Old way such as + ModuleName.ClassName_FunctionName still works. + 2) Same goes for enums inside classes: ModuleName.ClassName.EnumValue1 etc. + +2013-09-12: wsfulton + [UTL] Infinity is now by default an acceptable value for type 'float'. This fix makes + the handling of type 'float' and 'double' the same. The implementation requires the + C99 isfinite() macro, or otherwise some platform dependent equivalents, to be available. + + Users requiring the old behaviour of not accepting infinity, can define a 'check' typemap + wherever a float is used, such as: + + %typemap(check,fragment="") float, const float & %{ + if ($1 < -FLT_MAX || $1 > FLT_MAX) { + SWIG_exception_fail(SWIG_TypeError, "Overflow in type float"); + } + %} + + *** POTENTIAL INCOMPATIBILITY *** + +2013-08-30: wsfulton + [Lua] Pull Git patch #81: Include Lua error locus in SWIG error messages. + This is standard information in Lua error messages, and makes it much + easier to find bugs. + +2013-08-29: wsfulton + Pull Git patch #75: Handle UTF-8 files with BOM at beginning of file. Was giving an + 'Illegal token' syntax error. + +2013-08-29: wsfulton + [C#] Pull Git patch #77: Allow exporting std::map using non-default comparison function. + +2013-08-28: wsfulton + [Python] %implicitconv is improved for overloaded functions. Like in C++, the methods + with the actual types are considered before trying implicit conversions. Example: + + %implicitconv A; + struct A { + A(int i); + }; + class CCC { + public: + int xx(int i) { return 11; } + int xx(const A& i) { return 22; } + }; + + The following python code: + + CCC().xx(-1) + + will now return 11 instead of 22 - the implicit conversion is not done. + +2013-08-23: olly + [Python] Fix clang++ warning in generated wrapper code. + +2013-08-16: wsfulton + [Python] %implicitconv will now accept None where the implicit conversion takes a C/C++ pointer. + Problem highlighted by Bo Peng. Closes SF patch #230. + +2013-08-07: wsfulton + [Python] SF Patch #326 from Kris Thielemans - Remove SwigPyObject_print and SwigPyObject_str and + make the generated wrapper use the default python implementations, which will fall back to repr + (for -builtin option). + + Advantages: + - it avoids the swig user having to jump through hoops to get print to work as expected when + redefining repr/str slots. + - typing the name of a variable on the python prompt now prints the result of a (possibly redefined) + repr, without the swig user having to do any extra work. + - when redefining repr, the swig user doesn't necessarily have to redefine str as it will call the + redefined repr + - the behaviour is exactly the same as without the -builtin option while requiring no extra work + by the user (aside from adding the %feature("python:slot...) statements of course) + + Disadvantage: + - default str() will give different (but clearer?) output on swigged classes + +2013-07-30: wsfulton + [Python, Ruby] Fix #64 #65: Missing code in std::multimap wrappers. Previously an instantiation + of a std::map was erroneously required in addition to an instantiation of std::multimap with the + same template parameters to prevent compilation errors for the wrappers of a std::multimap. + +2013-07-14: joequant + [R] Change types file to allow for SEXP return values + +2013-07-05: wsfulton + [Python] Add %pythonbegin directive which works like %pythoncode, except the specified code is + added at the beginning of the generated .py file. This is primarily needed for importing from + __future__ statements required to be at the very beginning of the file. Example: + + %pythonbegin %{ + from __future__ import print_function + print("Loading", "Whizz", "Bang", sep=' ... ') + %} + +2013-07-01: wsfulton + [Python] Apply SF patch #340 - Uninitialized variable fix in SWIG_Python_NonDynamicSetAttr + when using -builtin. + +2013-07-01: wsfulton + [Python, Ruby, Ocaml] Apply SF patch #341 - fix a const_cast in generated code that was generating + a <:: digraph when using the unary scope operator (::) (global scope) in a template type. + +2013-07-01: wsfulton + [Python] Add SF patch #342 from Christian Delbaere to fix some director classes crashing on + object deletion when using -builtin. Fixes SF bug #1301. + +2013-06-11: wsfulton + [Python] Add SWIG_PYTHON_INTERPRETER_NO_DEBUG macro which can be defined to use the Release version + of the Python interpreter in Debug builds of the wrappers. The Visual Studio .dsp example + files have been modified to use this so that Debug builds will now work without having + to install or build a Debug build of the interpreter. + +2013-06-07: wsfulton + [Ruby] Git issue #52. Fix regression with missing rb_complex_new function for Ruby + versions prior to 1.9 using std::complex wrappers if just using std::complex as an output type. + Also fix the Complex helper functions external visibility (to static by default). + +2013-06-04: olly + [PHP] Fix SWIG_ZTS_ConvertResourcePtr() not to dereference NULL + if the type lookup fails. + +Version 2.0.10 (27 May 2013) +============================ + +2013-05-25: wsfulton + [Python] Fix Python 3 inconsistency when negative numbers are passed + where a parameter expects an unsigned C type. An OverFlow error is + now consistently thrown instead of a TypeError. + +2013-05-25: Artem Serebriyskiy + SVN Patch ticket #338 - fixes to %attribute macros for template usage + with %arg. + +2013-05-19: wsfulton + Fix ccache-swig internal error bug due to premature file cleanup. + + Fixes SF bug 1319 which shows up as a failure in the ccache tests on + Debian 64 bit Wheezy, possibly because ENABLE_ZLIB is defined. + + This is a corner case which will be hit when the maximum number of files + in the cache is set to be quite low (-F option), resulting in a cache miss. + +2013-05-09: kwwette + [Octave] Fix bugs in Octave module loading: + - fix a memory leak in setting of global variables + - install functions only once, to speed up module loads + +2013-04-28: gjanssens + [Guile] Updates in guile module: + - Add support for guile 2.0 + - Drop support for guile 1.6 + - Drop support for generating wrappers using guile's gh interface. + All generated wrappers will use the scm interface from now on. + - Deprecate -gh and -scm options. They are no longer needed. + A warning will be issued when these options are still used. + - Fix all tests and examples to have a successful travis test + +2013-04-18: wsfulton + Apply Patch #36 from Jesus Lopez to add support for $descriptor() special variable macro expansion + in fragments. For example: + + %fragment("nameDescriptor", "header") + %{ + static const char *nameDescriptor = "$descriptor(Name)"; + %} + + which will generate into the wrapper if the fragment is used: + + static const char *nameDescriptor = "SWIGTYPE_Name"; + +2013-04-18: wsfulton + Fix SF Bug #428 - Syntax error when preprocessor macros are defined inside of enum lists, such as: + + typedef enum { + eZero = 0 + #define ONE 1 + } EFoo; + + The macros are silently ignored. + +2013-04-17: wsfulton + [C#] Pull patch #34 from BrantKyser to fix smart pointers in conjunction with directors. + +2013-04-15: kwwette + [Octave] Fix bugs in output of cleanup code. + - Cleanup code is now written also after the "fail:" label, so it will be called if + a SWIG_exception is raised by the wrapping function, consistent with other modules. + - Octave module now also recognises the "$cleanup" special variable, if needed. + +2013-04-08: kwwette + Add -MP option to SWIG for generating phony targets for all dependencies. + - Prevents make from complaining if header files have been deleted before + the dependency file has been updated. + - Modelled on similar option in GCC. + +2013-04-09: olly + [PHP] Add missing directorin typemap for char* and char[] which + fixes director_string testcase failure. + +2013-04-05: wsfulton + [Ruby] SF Bug #1292 - Runtime fixes for Proc changes in ruby-1.9 when using STL + wrappers that override the default predicate, such as: + + %template(Map) std::map >; + +2013-04-05: wsfulton + [Ruby] SF Bug #1159 - Correctly check rb_respond_to call return values to fix some + further 1.9 problems with functors and use of Complex wrappers. + +2013-04-02: wsfulton + [Ruby] Runtime fixes for std::complex wrappers for ruby-1.9 - new native Ruby complex numbers are used. + +2013-03-30: wsfulton + [Ruby] Fix seg fault when using STL containers of generic Ruby types, GC_VALUE or LANGUAGE_OBJECT, + on exit of the Ruby interpreter. More frequently observed in ruby-1.9. + +2013-03-29: wsfulton + [Ruby] Fix delete_if (reject!) for the STL container wrappers which previously would + sometimes seg fault or not work. + +2013-03-25: wsfulton + [Python] Fix some undefined behaviour deleting slices in the STL containers. + +2013-03-19: wsfulton + [C#, Java, D] Fix seg fault in SWIG using directors when class and virtual method names are + the same except being in different namespaces when the %nspace feature is not being used. + +2013-02-19: kwwette + Fix bug in SWIG's handling of qualified (e.g. const) variables of array type. Given the typedef + a(7).q(volatile).double myarray // typedef volatile double[7] myarray; + the type + q(const).myarray // const myarray + becomes + a(7).q(const volatile).double // const volatile double[7] + Previously, SwigType_typedef_resolve() produces the type + q(const).a(7).q(volatile).double // non-sensical type + which would never match %typemap declarations, whose types were parsed correctly. + Add typemap_array_qualifiers.i to the test suite which checks for the correct behaviour. + +2013-02-18: wsfulton + Deprecate typedef names used as constructor and destructor names in %extend. The real + class/struct name should be used. + + typedef struct tagEStruct { + int ivar; + } EStruct; + + %extend tagEStruct { + EStruct() // illegal name, should be tagEStruct() + { + EStruct *s = new EStruct(); + s->ivar = ivar0; + return s; + } + ~EStruct() // illegal name, should be ~tagEStruct() + { + delete $self; + } + } + + For now these trigger a warning: + + extend_constructor_destructor.i:107: Warning 522: Use of an illegal constructor name 'EStruct' in + %extend is deprecated, the constructor name should be 'tagEStruct'. + extend_constructor_destructor.i:111: Warning 523: Use of an illegal destructor name 'EStruct' in + %extend is deprecated, the destructor name should be 'tagEStruct'. + + These %extend destructor and constructor names were valid up to swig-2.0.4, however swig-2.0.5 ignored + them altogether for C code as reported in SF bug #1306. The old behaviour of using them has been + restored for now, but is officially deprecated. This does not apply to anonymously defined typedef + classes/structs such as: + + typedef struct {...} X; + +2013-02-17: kwwette + When generating functions provided by %extend, use "(void)" for no-argument functions + instead of "()". This prevents warnings when compiling with "gcc -Wstrict-prototypes". + +2013-02-17: kwwette + [Octave] Minor fix to autodoc generation: get the right type for functions returning structs. + +2013-02-15: wsfulton + Deprecate typedef names used in %extend that are not the real class/struct name. For example: + + typedef struct StructBName { + int myint; + } StructB; + + %extend StructB { + void method() {} + } + + will now trigger a warning: + + swig_extend.i:19: Warning 326: Deprecated %extend name used - the struct name StructBName + should be used instead of the typedef name StructB. + + This is only partially working anyway (the %extend only worked if placed after the class + definition). + +2013-02-09: wsfulton + [CFFI] Apply patch #22 - Fix missing package before &body + +2013-01-29: wsfulton + [Java] Ensure 'javapackage' typemap is used as it stopped working from version 2.0.5. + +2013-01-28: wsfulton + [Python] Apply patch SF #334 - Fix default value conversions "TRUE"->True, "FALSE"->False. + +2013-01-28: wsfulton + [Java] Apply patch SF #335 - Truly ignore constructors in directors with %ignore. + +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. + +2013-01-15: wsfulton + Fix Visual Studio examples to work when SWIG is unzipped into a directory containing spaces. + +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; + }; + +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. + +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) ============================= @@ -349,7 +1563,7 @@ Version 2.0.5 (19 April 2012) namespace std { template struct map { class iterator; - } + }; } iterator was scoped as std::iterator, but now it is correctly std::map::iterator; @@ -361,10 +1575,10 @@ Version 2.0.5 (19 April 2012) template struct Map { typedef Key key_type; typedef T mapped_type; - } + }; } - tyepdef double DOUBLE; - %typemap(MM) Std::Map; + 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 @@ -2512,8 +3726,8 @@ Version 1.3.36 (24 June 2008) Makefile target being generated when generating makefiles with the -M family of options. For example: - $ swig -java -MM -MT overiddenname -c++ example.i - overiddenname: \ + $ swig -java -MM -MT overriddenname -c++ example.i + overriddenname: \ example.i \ example.h @@ -3199,7 +4413,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. @@ -3899,7 +5113,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. @@ -4415,7 +5629,7 @@ Version 1.3.29 (March 21, 2006) 6146 _std_containers.so 174 _std_containers.so.hidden - Excecution times: + Execution times: real 0m0.050s user 0m0.039s sys 0m0.005s _std_containers.so real 0m0.039s user 0m0.026s sys 0m0.007s _std_containers.so.hidden @@ -4501,7 +5715,7 @@ Version 1.3.29 (March 21, 2006) protected methods by default. In previous releases, you needed to use the 'dirprot' - option to acheive the same. + option to achieve the same. If you want, you can disable the new default behaviour, use the 'nodirprot' option: @@ -4707,7 +5921,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. @@ -4828,7 +6042,7 @@ Version 1.3.28 (February 12, 2006) %rename("%(utitle)s",%$isfunction,%$ismember) ""; - to avoid clashings with other swig macros/directives. + to avoid clashes with other swig macros/directives. 01/14/2006: cfisavage [Ruby] @@ -8214,7 +9428,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. @@ -8756,7 +9970,7 @@ Version 1.3.23 (November 11, 2004) - Remove the ability to share type information by using c linking. All type sharing happens through a global variable in the target language. + Remove SWIG_NOIMPORT, SWIG_RUNTIME, and related defines. - + Depreciate -runtime, -noruntime command line options + + Deprecate -runtime, -noruntime command line options + Update test-suite common.mk to correctly build multicpptest + Remove reference to precommon.swg + Update the guile_gh interface to share data by a global var instead @@ -10931,7 +12145,7 @@ Version 1.3.20 (December 17, 2003) 11/30/2003: cheetah (William Fulton) [Java] Fixed [ 766409 ] missing symbol SWIG_JavaThrowException during module load - SWIGs internal functions are all static as there is no need for different SWIG + SWIG's internal functions are all static as there is no need for different SWIG generated modules to share any code at runtime. 11/30/2003: beazley @@ -11728,7 +12942,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) @@ -16162,7 +17376,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 @@ -17203,7 +18417,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 @@ -19117,7 +20331,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 @@ -19998,9 +21212,9 @@ Version 1.3 Alpha 1 (February 11, 2000) *** POTENTIAL INCOMPATIBILITY *** 1/30/00 : loic - Conditionaly compile experimental code with --enable-experiment + Conditionally compile experimental code with --enable-experiment configure flag. - Fix .cvsignore to ignore configrue & yacc generated files + Fix .cvsignore to ignore configure & yacc generated files 1/28/00 : loic Apply automake everywhere @@ -20270,7 +21484,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: @@ -20512,7 +21726,7 @@ Version 1.1 Patch 4 (January 4, 1998) 12/29/97: Fixed configure script and a few makefiles to support Python 1.5 12/29/97: Added 'embed15.i' library file. This file should be used to - staticly link versions of Python 1.5. To make it the default, + statically link versions of Python 1.5. To make it the default, simply copy 'swig_lib/python/embed15.i' to 'swig_lib/python/embed.i' Version 1.1 Patch 3 (November 24, 1997) @@ -20827,7 +22041,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. @@ -20943,7 +22157,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 cb64a7937..11682c9dd 100644 --- a/CHANGES.current +++ b/CHANGES.current @@ -2,16 +2,40 @@ 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.6 (30 April 2012) -============================= +Version 3.0.1 (in progress) +=========================== -2012-04-25: wsfulton - [Lua] Fix uninitialised variable in SWIGTYPE **OUTPUT typemaps as reported by Jim Anderson. +2014-04-08: wsfulton + SF Bug #1366 - Remove duplicate declarations of strtoimax and strtoumax in inttypes.i -2012-04-28: wsfulton - [Python] Fix compilation errors when wrapping STL containers on Mac OSX and possibly other systems. +2014-04-08: wsfulton + [Java C#] Enums which have been ignored via %ignore and are subsequently + used are handled slightly differently. Type wrapper classes are now generated + which are effectively a wrapper of an empty enum. Previously in Java uncompilable + code was generated and in C# an int was used. -2012-04-28: wsfulton - [Java] Patch 3521811 from Leo Davis - char **STRING_ARRAY typemaps fixed to handle - null pointers. +2014-04-04: wsfulton + Fix regression in 3.0.0 where legal code following an operator<< definition might + give a syntax error. SF Bug #1365. +2014-04-03: olly + [PHP] Fix wrapping director constructors with default parameters + with a ZTS-enabled build of PHP. + +2014-04-02: olly + [PHP] Pass the ZTS context we already have to avoid needing to + call TSRMLS_FETCH, which is relatively expensive. + +2014-04-02: olly + [PHP] Pass ZTS context through to t_output_helper() so it works + with a ZTS-enabled build of PHP. Reported by Pierre Labastie in + github PR#155. + +2014-03-28: wsfulton + [Java C# D Go] Fixes for C enums used in an API and the definition of the enum + has not been parsed. For D, this fixes a segfault in SWIG. The other languages + now produce code that compiles, although the definition of the enum is needed + in order to use the enum properly from the target language. + +2014-03-23: v-for-vandal + [Lua] Fix for usage of snprintf in Lua runtime which Visual Studio does not have. diff --git a/COPYRIGHT b/COPYRIGHT index dc61d89b4..188af4876 100644 --- a/COPYRIGHT +++ b/COPYRIGHT @@ -66,7 +66,7 @@ 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: diff --git a/Doc/Devel/cpp11.html b/Doc/Devel/cpp11.html new file mode 100644 index 000000000..fc35465ae --- /dev/null +++ b/Doc/Devel/cpp11.html @@ -0,0 +1,788 @@ + + + + + + + + + + + + + + + +

C++0x/C++11 support for SWIG

+

Summary

+

This is a technical overview of the C++0x/C++11 support for the Swig. +This area of Swig is a work in progress. Initial C++0x/C++11 support for +Swig was written during the Google Summer of Code 2009 period by +Matevž Jekovec.

+

SVN branch

+

branches/gsoc2009-matevz

+

New C++11 features status

+

Wikipedia article: http://en.wikipedia.org/wiki/C%2B%2B0x +

+

Rvalue reference and move semantics [done]

+

The Rvalues are used in practice to speed up the move operations +on different containers.

+

In the following example, we want to swap the given elements:

+
template <class T> swap(T& a, T& b) {
+    T tmp(a);   // now we have two copies of a
+    a = b;      // now we have two copies of b
+    b = tmp;    // now we have two copies of tmp (aka a)
+}

+This can now be solved using the new function std::move():

+
template <class T> swap(T& a, T& b) {
+    T tmp(std::move(a));
+    a = std::move(b);   
+    b = std::move(tmp);
+}

+For the move function to take effect, user needs to reimplement the +move constructor (taking ClassType&& as an argument) and +operator=(ClassType&&):

+
class MyClass {
+  MyClass(MyClass&& p) : ptr(p.ptr) {p.ptr = 0;}
+  MyClass& operator=(MyClass&& p) {
+    std::swap(ptr, p.ptr);
+    return *this;
+  }
+};

+In practice, the Rvalues are used for temporaries (when passing the +result of one function as an argument to another).

+

Done: Added type&& to Swig parser. Added testcase +cpp11_rvalue_reference.i. Operator && is treated the same as +operator &. R11450

+

Article: +http://www.artima.com/cppsource/rvalue.html

+

Generalized constant expressions [done]

+

In C++11 you can define functions as constant expressions. +Functions need to return constant value in form "return expr", +where expr is a constant expression. +

+

A keyword "constexpr" is introduced for this. eg.: +constexpr int getNumber() { return 5; } const int MY_CONSTANT = +getNumber(); +

+

Constants are treated as normal variables in interpreted languages +because they are not compiled into the executable. Java "final" +constants are defined runtime as well. C++ constants need to be +declared in the header file and defined in the implementation file, +so swig doesn't need to know about the constant values when parsing +the header file. +

+

Done: Added the “constexpr “ keyword to Swig. Added testcase +cpp11_constexpr. R11322

+

Problem: No compilers were known to support constexpr yet, so the +testcase was temporarily commented out in common.mk. +

+

Extern template [done]

+

Extern template forces the GCC compiler to not instantiate the +template in the translation unit at that time. It's a feature +specifically aimed at compilers to speed up the compilation process. +

+

Done: Added support for 'extern template class +std::vector<MyClass>;'. Added testcase cpp11_template_explicit. +R11385 , R11386

+

Initializer lists [done]

+

Initializer list is a new type in standard library: +std::initializer_list<T>. New symbols {} are introduced for the +initializer lists. +

+

One can now use: +

+
 class A {
+ public:
+   A( std::initializer_list<int> );
+ };
+ A a1 = {1,2,3,4};

+Languages like Java, C# and Python already support direct creation of +lists natively.

+

Problem: initializer_list cannot be treated as an ordinary list. +The constructor containing initializer_list can only be accessed by +assigning the value using the {} brackets. I also don't think there +is a simple way to convert an ordinary list or a vector to the +initializer_list.

+

Done: Ignored the constructor having initializer_list as its +argument. Show warning to the user. Added testcase +cpp11_initializer_list. R11450

+

Article: +http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1919.pdf

+

Uniform initialization [done]

+

The new C++11 standard will allow the following:

+
struct IdString {
+  std::string name;
+  int identifier;
+};
+ 
+IdString GetString() {
+  return {"SomeName", 4}; //Note the lack of explicit type.
+}

+The feature works exactly as it did now for POD types only (eg. int +a[] = {1,2,3};). The following declarations are the same in the new +C++11:

+
IdString str1 = {„SomeName“, 4};
+IdString str2{„SomeName“, 4};

+The new way of using uniform initialization allows the following:

+
struct BasicStruct {
+ int x;
+ double y;
+};
+ 
+struct AltStruct {
+  AltStruct(int x, double y) : x_{x}, y_{y} {}
+ 
+private:
+  int x_;
+  double y_;
+};
+ 
+BasicStruct var1{5, 3.2}; // only fills the struct components
+AltStruct var2{2, 4.3};   // calls the constructor

+The new syntax is specific to C++. Java, C# and scripting languages +do not support this behaviour, but always need constructors. They +support {} brackets for declaration of arrays as C does + they add +support for creation of arrays on-the-fly (what C++11 introduced with +this feature and more).

+

Done: Added syntax for {} member initialization in class +constructor. Added testcase cpp11_uniform_initialization. R11413

+

Type inference [partially done]

+

A new keyword 'auto' is introduced in C++11:

+
auto a1 = 100;
+auto a2 = myFunc();

+The type of a1 and a2 is automatically determined according to the +initialization value during the semantic phase of the compiler.

+

Another macro 'decltype()' is introduced. The macro takes the +concrete object as an argument and returns its type. User could use +this as:

+
int i = 100;
+decltype(i) j = 200; // decltype(i) = int

+Calling operators are allowed as well:

+
decltype(i+j) k = 300;

+Done: Added support for decltype() syntax. Test cases for normal +decltype members and alternate function members work fine. Currently +only syntax in form decltype(variable name) work. No support for +custom expresions eg. decltype(i+j) yet. R11525

+

TODO: William proposed to support the hidden variables as well +(ones not parsed by Swig and added to symbol table). This also allows +Swig to parse custom expressions like decltype(i+j). The idea is to +introduce a new SwigType for this.

+

Range-based for-loop [ignored]

+

This feature is always present inside the implementation block +only. +

+

Lambda functions and expressions [done]

+

C++11 introduces lambda functions defined as:

+
[](int x, int y) -> int { return x + y; }

+If the lambda function contains a single return statement only or the +function doesn't return any type, the return type '->' can be +omitted. Lambda functions are function objects.

+

The following example prints the number of items stored in a list:

+
std::vector<int> someList;
+int total = 0;
+std::for_each( someList.begin(), someList.end(), [&total](int x) {total += x} );
+std::cout << total;

+Parameters inside the [] are the visible parameters of the lambda +functions. These can be & (references), = (copies), variable name +(variable copy), &variable name (variable reference) or this +(copy of the current object).

+

Lambda functions can be stored using:

+
auto myLambdaFunc = [this]() { this->SomePrivateMemberFunction() };

+Proposal: Lambda functions are most commonly used inside the function +block to quickly define how the sort, find and similar functions +should work (the other way would be overriding a class – the Java +style). The latest GCC does not support lambda functions yet so it is +difficult to test the feature once implemented. I would implement the +syntax support for this feature, but produce no wrapper code. Lambda +functions still work inside the function block though.

+

Article: +http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2550.pdf

+

Done: Added syntax support for the lambda functions. Added +testcase cpp11_lambda_functions.i. R11491, R11492

+

Alternate function syntax [done]

+

The problem with decltype() is that the parameters need to be +defined before the decltype. The following syntax is not valid, +because lhs and rhs hasn't been defined at the time of decltype:

+
template< typename LHS, typename RHS> 
+  decltype(lhs+rhs) AddingFunc(const LHS &lhs, const RHS &rhs) {return lhs + rhs;} //Not legal C++11

+The solution C++11 offers is the combination of the 'auto' keyword +before and '-> rettype' after the function declaration:

+
template< typename LHS, typename RHS> 
+  auto AddingFunc(const LHS &lhs, const RHS &rhs) -> decltype(lhs+rhs) {return lhs + rhs;}

+The new syntax only makes the job for the C++ compilers easier when +parsing such functions. The new syntax can be used for ordinary +functions as well:

+
struct SomeStruct {
+  auto FuncName(int x, int y) -> int;
+};
+ 
+auto SomeStruct::FuncName(int x, int y) -> int {
+  return x + y;
+}

+Done: Added support for the 'auto' return type. Added support for the +'-> type' after the funtion declaration. Added testcases +cpp11_alternate_function_syntax.i and +cpp11_alternate_function_syntax_runme.py. R11414

+

Concepts, Axioms [ignored]

+

In C++ there is a common problem when you use a template in the +class which doesn't support all the operations the functions in the +class actually do on the type. Compiler errors are usually very long +and unreadable. C++11 adds support for the "concepts". The +idea is to define what operations and attributes should the template +have. In contrast to class inheritance and polimorphism, all lookups +are done in compile-time. +

+

Basic syntax (note LessThanComparable? +instead of "class" or "typename"): +

+
 template<LessThanComparable? T>
+ const T& min(const T &x, const T &y) {
+   return y < x ? y : x;
+ }

+Extended syntax (requires conditions are separated with &&, +|| or !): +

+
 template< typename T> requires LessThanComparable?<T>
+ const T& min(const T &x, const T &y) {
+   return y < x ? y : x;
+ }

+Definition of the concepts: +

+
 concept LessThanComparable?< typename T > {
+   bool operator<(T,T);
+   requires GreaterThanComparable?<T>;
+   typename value_type;
+   typename reference;
+ };

+Concept maps allow usage of a specific type: +

+
 template< typename T>
+ concept_map InputIterator?<T*> {
+   typedef T value_type ;
+   typedef T& reference ;
+   typedef T* pointer ;
+   typedef std::ptrdiff_t difference_type ;
+ };

+Concept maps can act as mini-types, with function definitions and +other constructs commonly associated with classes: +

+
 concept Stack< typename X> {
+   typename value_type;
+   void push(X&, const value_type&);
+   void pop(X&);
+   value_type top(const X&);
+   bool empty(const X&);
+ };
+ template< typename T>
+ concept_map Stack<std::vector<T> > {
+   typedef T value_type;
+   void push(std::vector<T>& v, const T& x) { v.push_back(x); }
+   void pop(std::vector<T>& v) { v.pop_back(); }
+   T top(const std::vector<T>& v) { return v.back(); }
+   bool empty(const std::vector<T>& v) { return v.empty(); }
+ };

+Axioms are a facility pertaining to concepts supplied by C++11 to +express the semantic properties of concepts. For example, the concept +Semigroup can be defined with an axiom Associativity as: +

+
 concept Semigroup< typename Op, typename T> : CopyConstructible?<T> {
+   T operator()(Op, T, T);
+   axiom Associativity(Op op, T x, T y, T z) {
+     op(x, op(y, z)) == op(op(x, y), z);
+   }
+ };

+Axioms are more like hints to the compiler to speed-up the process of +compilation. +

+

Ignored: Concepts and axioms were removed from the C++11 standard. +

+

Object construction improvement [done]

+

This feature allows classes constructors to call other +constructors with different arguments (similar to Java and C# +behaviour). +

+

The syntax is as follows: +

+
 class SomeType {
+  int number;
+ public:
+   SomeType(int newNumber) : number(newNumber) {}
+   SomeType() : SomeType(42) {}
+ };

+Also when using the inheritance, the feature introduces inheritance +of all superclass constructors without being defined separately in +the inherited class: +

+
 class BaseClass {
+ public:
+   BaseClass(int iValue);
+ };
+ class DerivedClass: public BaseClass {
+   public:
+   using BaseClass::BaseClass; // Adds DerivedClass(int) constructor
+ };

+Swig already correctly parses and produces the correct wrapper for +the “using” keyword.

+

Done: Added testcase cpp11_constructors.i which covers both +constructor delegation and constructor inheritance. R11532

+

Problem: Constructor delegation and constructor inheritance is not +supported by any compiler yet, so it's impossible to try and test +this feature.

+

Null pointer constant [done]

+

nullptr is part of the standard library. +

+

It's defined as typedef decltype(nullptr) nullptr_t; +

+

nullptr_t is defined in <cstddef>. +

+

As far as the C++ is compatible with 0 as the pointer value, swig +values will work for the C++. And the other way around, nullptr +behaves as the ordinary pointer (false, if empty, true, if not +empty), so it's ok for swig to compare it.

+

Done: Written a testcase cpp11_null_pointer_constant.i and +cpp11_null_pointer_constant_runme.py to prove the nullptr +functionality. R11484

+

Strongly typed enumerations [partially done]

+

C++11 introduces a new syntax for strongly typed enum declaration: +

+
 enum class Enumeration {
+  Val1,
+  Val2,
+  Val3 = 100,
+  Val4 /* = 101 */
+ };

+Typing if (Val4 == 101) will result in compilation error. +

+

The enum itself can now be explicitely of type int, long, unsigned +int etc.: +

+
 enum class Enum2 : unsigned int {Val1, Val2};

+And it can be forward declared as well: +

+
 enum Enum1;                   //Illegal in C++ and C++11; no size is explicitly specified.
+ enum Enum2 : unsigned int;    //Legal in C++11.
+ enum class Enum3;             //Legal in C++11, because enum class declarations have a default type of "int".
+ enum class Enum4: unsigned int; //Legal C++11.
+ enum Enum2 : unsigned short;  //Illegal in C++11, because Enum2 was previously declared with a different type.

+Done: Added syntax 'enum class Name' and forward declarators 'enum +Name : inherited type' or 'enum class Name : inherited type' in +R11449.

+

TODO: Add semantic support for enum elements not clashing with +enum elements in other enum classes. See cpp11_strongly_typed_enums.i +warnings.

+

Problem: Swig currently doesn't support nested classes. This +feature should be implemented using a new nested class when using +“enum class” with a single anonymous “enum {elements}” +element inside. For example:

+
class A { enum class EA { a,b,c,d }; };

+should be mapped to

+
class A { class EA { enum {a,b,c,d}; }; };

+Angle bracket [done]

+

Support for right angled brackets was implemented using the +following article as a base: +http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1757.html +

+

Done: Added support for angle brackets. Used the preferred +"Approach 1". Added a testcase named +cpp11_template_double_brackets. R11245

+

Explicit conversion operators [done]

+

This is used when converting one type to another (eg. if +(myObject) {}, where myObject is your custom class converted to +bool). +

+

Requires both operator and function overloading which is not +supported in any target language (eg. python, php). +

+

Done: Swig already supports the keyword "explicit" for +function types as well. Added test case +cpp11_explicit_conversion_operators. R11323

+

Template typedefs [partially done]

+

The new C++11 will allow creation of wrapper around the template. +For example, if we want to do this:

+
template< typename first, typename second, int third>
+class SomeType;
+ 
+template< typename second>
+typedef SomeType<OtherType, second, 5> TypedefName; //Illegal in C++

+This is still illegal! But we can now use the new syntax for +achieving the same effect:

+
template< typename first, typename second, int third>
+class SomeType;
+
+template< typename second>
+using TypedefName = SomeType<OtherType, second, 5>;

+Here we created a new wrapper TypedefName taking one template +argument <second> which creates a type SomeType<OtherType, +second, 5>. OtherType and 5 are predefined here and hidden from +the user – the user only uses TypedefName type.

+

The same goes for the following example:

+
typedef void (*PFD)(double);            // Old style
+using PF = void (*)(double);            // New introduced syntax

+Swig supports parsing typedefs for templates as well for example:

+
typedef List<int> intList;

+Done: Expanded support for the new 'using' syntax and template +aliasing. Added testcase cpp11_template_typedefs. R11533

+

TODO: Make Swig aware of the newly defined typedef. The TYPEDEF +keyword is part of the storage_class rule and type+declarator (see +c_decl rule) is the right part of the definition – for example void +(*PFD)(double) cannot be transformed to void *(double) easily. To +fully support the new 'using' form, we'll probably have to change the +type, type_right rules and declarator, direct_declarator, +notso_direct_declarator etc., which is PITA.

+

Unrestricted unions [done]

+

C++ currently offers usage of unions for types with trivial +constructors only. The new C++11 standard allows usage of types with +non-trivial constructors as well:

+
 struct point {
+  point() {}
+  point(int x, int y): x_(x), y_(y) {}
+  int x_, y_;
+ };
+ union P {
+  int z;
+  double w;
+  point p;  // Illegal in C++; point has a non-trivial constructor.  However, this is legal in C++11.
+ } p1;

+Swig already parses the given syntax.

+

Done: Added testcase cpp11_unrestricted_unions. R11435, R11447

+

Problem: GCC doesn't support unrestricted unions yet so there is +no way to actually test, if it works.

+

Variadic templates [partially done]

+

The new C++11 offers the following syntax:

+
template<typename... Values> class tuple;

+This can be used for example:

+
class tuple<int, std::vector<int>, std::map<std::string, std::vector<int>>> someInstanceName;

+The ... is used in two cases. One is in the template header where it +marks on the left the keywords 'typename' or 'class' and a type name +on the right. The second case is usually in the function block to +decompose typename on the left of the ... . For example:

+
void printf(const char *s) {
+  while (*s) {
+    if (*s == '%' && *(++s) != '%')
+      throw std::runtime_error("invalid format string: missing arguments");
+    std::cout << *s++;
+  }
+}
+ 
+template<typename T, typename... Args>
+void printf(const char* s, T value, Args... args) { // recursive action – split previous args to value + args
+  while (*s) {
+    if (*s == '%' && *(++s) != '%') {
+      std::cout << value;
+      printf(*s ? ++s : s, args...); // call even when *s == 0 to detect extra arguments
+      return;
+    }
+    std::cout << *s++;
+  }
+  throw std::logic_error("extra arguments provided to printf");
+}

+The tricky part is that variadic templates can unpack actually +anywhere – including the class inheritance :(

+
template <typename... BaseClasses> class ClassName : public BaseClasses... {
+public:
+ 
+   ClassName (BaseClasses&&... baseClasses) : BaseClasses(baseClasses)... {}
+}

+A new extension to sizeof is also introduced with this feature. The +... after sizeof returns number of arguments:

+
template<typename ...Args> struct SomeStruct {
+  static const int size = sizeof...(Args);
+}
+// SomeStruct<Type1, Type2>::size is 2 and SomeStruct<>::size is 0

+Done: Added syntax support for 'typename' or 'class' + ... + id. +Added testcase cpp11_variadic_templates. R11458

+

Done: Added syntax support for BaseClass + ..., type + ... + id in +parameters and baseclass + ... for intializers after constructor. +Extended Swig syntax to support sizeof...(Args). R11467

+

Done: Fixed %template to support variadic number of templates.

+

TODO: Only (if present) first variadically defined argument is +currently used in %template directive. The next ones are ignored.

+

New string literals [partially done]

+

Beside the implementation, the new C++11 Unicode and custom +delimeter constants can occur in templates in the header file. +

+

Done: Added symbols 'u', 'u8' and 'U' to mark the beginning of the +UTF string. Also added test case cpp11_raw_string_literals. R11327

+

Done: Added R"DELIMITER[, ]DELIMITER" for a custom +delimiter for the beginning/end of the string. R11328

+

TODO: Fix the Swig's C++ preprocessor bug when parsing an odd +number of “ inside the string brackets. See +Source/Preprocessor/cpp.c.

+

User-defined literals [partially done]

+

C++ has different suffix literals. eg. 12.5f marks the number 12.5 +as float. +

+

C++11 allows user to define his own suffix for the strings always +starting with the underscore (_). eg. int a = "hello"_mySuffix; +

+

The syntax is similar to other operator overloading functions: +

+
 OutputType operator "" _mySuffix(const char * string_values);

+The null terminated const char* is the string between the "". +The _mySuffix is the name of the suffix operator. And the OutputType +is the outputType the operator returns. +

+

Other forms are: +

+
 OutputType operator "" _mySuffix(const char * string_values, size_t num_chars);
+ OutputType operator "" _mySuffix(const wchar_t * string_values, size_t num_chars);
+ OutputType operator "" _mySuffix(const char16_t * string_values, size_t num_chars);
+ OutputType operator "" _mySuffix(const char32_t * string_values, size_t num_chars);
+ OutputType operator "" _mySuffix(int value); /* cooked version - ie. atoi() of string */

+Another possibility is to use variadic templates: +

+
 template<char...> OutputType operator "" _mySuffix();
+ OutputType someVariable = "1234"_mySuffix;

+This instantiates the literal processing function as +operator""_Suffix<'1', '2', '3', '4'>. In this form, +there is no terminating null character to the string. The main +purpose to doing this is to use C++11's constexpr keyword and the +compiler to allow the literal to be transformed entirely at compile +time, assuming OutputType is a constexpr-constructable and copyable +type, and the literal processing function is a constexpr function.

+

Article: +http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2765.pdf

+

Done: Added syntax support for userdefined literals. Added +testcase cpp11_userdefined_literals.i. R11494

+

TODO: %rename doesn't parse operator”” yet.

+

Thread-local storage [done] +

+

New C++11 introduces keyword "thread_local" which marks +the following variable dynamically located depending on the current +thread when using the address-of (&) operator. +

+

Syntax: +

+
 struct A {
+   thread_local int val;
+ };

+Done: Add "thread_local" keyword to Swig. Added testcase +cpp11_thread_local. R11393

+

Defaulting/deleting of standard functions on C++ objects [done]

+

C++ automatically creates default constructor with empty +parameters, copy constructor, operator= and destructor for any class. +Sometimes user wants to explicitly remove one of them or enable them +(eg. default constructor with empty parameters doesn't work any more, +if any other constructor is defined). +

+

Words "default" and "delete" are introduced. +The syntax is similar to declaration of pure virtual function: +

+
 struct NonCopyable {
+   NonCopyable & operator=(const NonCopyable&) = delete; /* Removes operator= */
+   NonCopyable(const NonCopyable&) = delete; /* Removed copy constructor */
+   NonCopyable() = default; /* Explicitly allows the empty constructor */
+   void *operator new(std::size_t) = delete; /* Removes new NonCopyable */
+ };

+User has the ability by using keyword delete to disallow calling of +the standard functions brought by C++ itself. +

+
 struct A1 {
+   void f(int i);
+   void f(double i) = delete;  /* Don't cast double to int. Compiler returns an error */
+ };
+ struct A2 {
+   void f(int i);
+   template<class T> void f(T) = delete; /* Only accept int */
+ };

+Ignored: Swig already parses the keywords "= delete" and "= +default". These keywords are used for built-in functions (copy +constructor, operator= etc.), which are ignored by Swig anyway.

+

Done: Added testcase cpp11_default_delete. R11535

+

Type long long int [done]

+

Type long long int is an integer type that has at least 64 useful +bits. C99 added it to its standard, but the C++ didn't adopt it until +C++11. Most C++ compilers supported it though. +

+

Done: Swig already parses the C code including the long long type. +

+

Static assertions [done]

+

static_assert() can be used at class scope as well eg.: +

+
 template <typename T>
+ struct Check {
+  static_assert(sizeof(int) <= sizeof(T), "not big enough");
+ };

+Done: Added syntax support for "static_assert()". Added +test case cpp11_static_assert. R11369

+

Allow sizeof to work on members of classes without an explicit +object [done]

+

C++11 allows calls of sizeof to concrete objects as well: +

+
 struct A { int member; };
+ sizeof(A::member); //Does not work with C++03. Okay with C++11

+This kind of syntax is already supported by Swig.

+

Done: Added testcase cpp11_sizeof_objects. R11538 +

+

Threading facilities [ignored]

+

C++11 will add the following classes to the standard library: +

+
 * std::thread
+ * std::mutex, std::recursive_mutex
+ * std::condition_variable, std::condition_variable_any
+ * std::lock_guard, std::unique_lock
+ * std::packaged_task

+Ignored: No changes to the language itself is made. +

+

Tuple types [TODO]

+

Tuple is array of various types. C++11 introduced this feature +using variadic templates. Tuple is defined as:

+
template <class ...Types> class tuple;

+Constructor is automatically generated filling the tuple elements. +get<X> function is introduced to get the Xth element in the +tuple.

+
typedef tuple< int, double, long &, const char * > test_tuple ;
+long lengthy = 12 ;
+test_tuple proof( 18, 6.5, lengthy, "Ciao!" ) ;
+lengthy = get<0>(proof) ;  // Assign to 'lengthy' the value 18.
+get<3>(proof) = " Beautiful!" ;  // Modify the tuple’s fourth element.

+Tuples can be copied to each other, if all the elements are copiable:

+
typedef tuple< int , double, string       > tuple_1 t1 ;
+typedef tuple< char, short , const char * > tuple_2 t2( 'X', 2, "Hola!" ) ;
+t1 = t2 ;  // Ok, first two elements can be converted,
+           // the third one can be constructed from a 'const char *'.

+TODO: Implement wrappers for the tuplet<> class.

+

Hash tables [TODO]

+

C++11 introduces the "unordered" version of existing +types, which in practice work faster than the linear types: +

+
 - unordered set
+ - unordered multiset
+ - unordered map
+ - unordered multimap

+Swig should use the "unordered" types exactly the same as +the original linear types.

+

Problem: Unordered types do not contain exactly same members as +ordered ones (eg. _Hashtable_iterator does not offer operator--() and +constructor with compare function which is required). So simply +aliasing unordered classes to ordered ones doesn't work.

+

TODO: Implement wrappers for unordered_ types. Initial work is +already done in Lib/std/unordered_*.i files.

+

Regular expressions [ignored]

+

Two new classes are introduced in C++11: basic_regex and +match_results. Both are defined in regex header file. +

+

Ignored: The new feature extends the standardy library only. No +changes to Swig needed. +

+

General-purpose smart pointers [done]

+

This feature deprecates auto_ptr and adds shared_ptr, weak_ptr and +unique_ptr to the standard library. +

+

This feature only adds the smart pointers to the standard library +and doesn't effect the C++ syntax.

+

Done: Added test case which uses all three smart pointers in the +class. R11394

+

Problem: GCC standard library doesn't contain the new smart +pointers yet. +

+

Extensible random number facility [ignored]

+

This feature standardize the pseudo random number algorithm +(currently, the random number generator was dependent on the +platform/compiler). It adds functions linear_congruential, +subtract_with_carry and mersenne_twister and symbols +uniform_int_distribution, bernoulli_distribution, +geometric_distribution, poisson_distribution, binomial_distribution, +uniform_real_distribution, exponential_distribution, +normal_distribution and gamma_distribution to the standard library. +

+

Ignored: The new feature extends the standardy library only. No +changes to Swig needed. +

+

Wrapper reference [ignored]

+

This feature adds ref and cref classes to the standard library +(#include <utility>) usually used in tempalte functions. +

+

Ignored: The new feature extends the standardy library only. No +changes to Swig needed. +

+

Polymorphous wrappers for function objects [done]

+

Two features are introduced: +

+
    +
  • The function template wrapper: +

    +
+
 function<int ( int, int )> pF;
+
    +
  • and the function object: +

    +
+
 struct Test {
+   bool operator()( short x, short y );
+ };

+Swig already supports the two.

+

Done: Added a runtime testcase for function objects +cpp11_function_objects. R11419.

+

Type traits for metaprogramming [ignored]

+

C++11 adds a new header file <type_traits> which includes +helper functions to determine the template type while initializing +the object at compile time. +

+

Swig already supports the following code: +

+
 template< int B, int N >
+ struct Pow {
+  // recursive call and recombination.
+  enum{ value = B*Pow< B, N-1 >::value };
+ };
+ template< int B > struct Pow< B, 0 >  // N == 0 condition of termination.
+ {
+  enum{ value = 1 };
+ };
+ int quartic_of_three = Pow< 3, 4 >::value ;

+Functions is_convertible, is_integral, is_integral_const etc. are +part of the new header: +

+
// First way of operating.
+template< bool B > struct algorithm {
+  template< class T1, class T2 > int do_it( T1 &, T2 & )  { /*...*/ }
+};
+// Second way of operating.
+template<> struct algorithm<true> {
+  template< class T1, class T2 > int do_it( T1, T2 )  { /*...*/ }
+};
+// Instantiating 'elaborate' will automatically instantiate the correct way to operate.
+template< class T1, class T2 > int elaborate( T1 A, T2 B ) {
+  // Use the second way only if 'T1' is an integer and if 'T2' is
+  // in floating point, otherwise use the first way.
+  return algorithm< is_integral<T1>::value && is_floating_point<T2>::value >::do_it( A, B );
+}

+Swig correctly parses the syntax for template<bool>, +template<class T> and template<>. +

+

Ignored: Swig requires explicitly defined template class +(%template directive) to export it to the target language.

+

Uniform method for computing return type of function objects +[partially done]

+

The template function is introduced: std::result_of() which +depends on decltype: +

+
template< class Obj >
+class calculus_ver2 {
+ public:
+   template< class Arg >
+   typename std::result_of<Obj(Arg)>::type operator()( Arg& a ) const { 
+     return member(a);
+   }
+ private:
+   Obj member;
+};

+Swig correctly parses the result_of class.

+

TODO: The return type (the result_of::type member) is not +calculated by Swig. This needs a much more complex semantic parser.

+

Done: Added testcase cpp11_result_of. R11534

+ + diff --git a/Doc/Devel/engineering.html b/Doc/Devel/engineering.html index 2e78fbe35..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$";
    -
     #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/internals.html b/Doc/Devel/internals.html index d24869d10..c9082d3f6 100644 --- a/Doc/Devel/internals.html +++ b/Doc/Devel/internals.html @@ -42,6 +42,7 @@
  • 7. Debugging SWIG @@ -346,7 +347,7 @@ Delete(a); /* Destroy a */ All objects are referenced counted and given a reference count of 1 when initially created. The Delete() function only destroys an object when the reference count reaches zero. When -an object is placed in a list or hash table, it's reference count is automatically increased. For example: +an object is placed in a list or hash table, its reference count is automatically increased. For example:
    @@ -843,7 +844,7 @@ Returns a type object corresponding to the type string produced by the Swig_cloc
     
  • char *Swig_clocal_deref(DataType *t, char *name)
    This function is the inverse of the clocal() function. Given a type and a name, it produces a string containing the code needed to cast/convert the type produced by -Swig_clocal() back into it's original type. +Swig_clocal() back into its original type.

  • char *Swig_clocal_assign(DataType *t, char *name)
    @@ -1179,6 +1180,34 @@ Either
    + +

    7.2 Debugging DOH memory allocation problems

    +
    + +

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

    +
    Copyright (C) 1999-2010 SWIG Development Team. diff --git a/Doc/Devel/tree.html b/Doc/Devel/tree.html index db3c6fee4..73a49ed55 100644 --- a/Doc/Devel/tree.html +++ b/Doc/Devel/tree.html @@ -185,7 +185,7 @@ this function merely records that those attributes did not exist in the original
    This function is similar to Swig_save() except that adds additional attribute checking. There are different interpretations of the attribute names. A name of "attr" merely requests that the function check for the presence of an attribute. If the attribute is missing, SWIG will exit with a failed assertion. An attribute name of "?attr" specifies that the attribute "attr" is optional and -that it's old value must be saved (if any). An attribute name of "*attr" specifies that the attribute is required and that +that its old value must be saved (if any). An attribute name of "*attr" specifies that the attribute is required and that its value must be saved. The saving of attributes is performed in the same manner as with Swig_save(). Here is an example:
    diff --git a/Doc/Manual/Allegrocl.html b/Doc/Manual/Allegrocl.html
    index 5d00c4cd0..8295bad1c 100644
    --- a/Doc/Manual/Allegrocl.html
    +++ b/Doc/Manual/Allegrocl.html
    @@ -8,7 +8,7 @@
     
     
     
    -

    17 SWIG and Allegro Common Lisp

    +

    18 SWIG and Allegro Common Lisp

      @@ -135,10 +135,10 @@ be unhappy to see some enterprising folk use this work to add to it.

      -

      17.1 Basics

      +

      18.1 Basics

      -

      17.1.1 Running SWIG

      +

      18.1.1 Running SWIG

      @@ -360,7 +360,7 @@ need to link in the Allegro shared library. The library you create from the C++ wrapper will be what you then load into Allegro CL.

      -

      17.1.2 Command Line Options

      +

      18.1.2 Command Line Options

      @@ -396,7 +396,7 @@ See Section 17.5 Identifier converter functions for more details.

      -

      17.1.3 Inserting user code into generated files

      +

      18.1.3 Inserting user code into generated files

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

      -

      17.2 Wrapping Overview

      +

      18.2 Wrapping Overview

      @@ -446,7 +446,7 @@ New users to SWIG are encouraged to read interested in generating an interface to C++.

      -

      17.2.1 Function Wrapping

      +

      18.2.1 Function Wrapping

      @@ -499,7 +499,7 @@ interested in generating an interface to C++.

    -

    17.2.2 Foreign Wrappers

    +

    18.2.2 Foreign Wrappers

    @@ -512,7 +512,7 @@ interested in generating an interface to C++. typemap.

    -

    17.2.3 FFI Wrappers

    +

    18.2.3 FFI Wrappers

    @@ -593,7 +593,7 @@ char *xxx(); ff:def-foreign-call's.

    -

    17.2.4 Non-overloaded Defuns

    +

    18.2.4 Non-overloaded Defuns

    @@ -606,7 +606,7 @@ char *xxx(); this function can be manipulated via the lout typemap.

    -

    17.2.5 Overloaded Defuns

    +

    18.2.5 Overloaded Defuns

    @@ -622,7 +622,7 @@ char *xxx(); can be manipulated via the lout typemap.

    -

    17.2.6 What about constant and variable access?

    +

    18.2.6 What about constant and variable access?

    @@ -635,7 +635,7 @@ char *xxx(); into the foreign module.

    -

    17.2.7 Object Wrapping

    +

    18.2.7 Object Wrapping

    @@ -657,7 +657,7 @@ char *xxx(); foreign function interface.

    -

    17.3 Wrapping Details

    +

    18.3 Wrapping Details

    @@ -665,7 +665,7 @@ char *xxx(); translated into lisp.

    -

    17.3.1 Namespaces

    +

    18.3.1 Namespaces

    @@ -742,13 +742,13 @@ namespace car { function such as (car '(1 2 3).

    -

    17.3.2 Constants

    +

    18.3.2 Constants

    Constants, as declared by the preprocessor #define macro or SWIG - %constant directive, are included in SWIGs parse tree + %constant directive, are included in SWIG's parse tree when it can be determined that they are, or could be reduced to, a literal value. Such values are translated into defconstant forms in the generated lisp wrapper when the -nocwrap command-line @@ -803,7 +803,7 @@ namespace car { not use the -nocwrap command-line option.

    -

    17.3.3 Variables

    +

    18.3.3 Variables

    @@ -881,13 +881,13 @@ globalvar> (globalvar.nnn::glob_float)

  • -

    17.3.4 Enumerations

    +

    18.3.4 Enumerations

    In C, an enumeration value is an integer value, while in C++ an enumeration value is implicitly convertible to an integer value, - but can also be distinguished by it's enum type. For each enum + but can also be distinguished by its enum type. For each enum declaration a def-foreign-type is generated, assigning the enum a default type of :int. Users may adjust the foreign type of enums via SWIG typemaps. @@ -901,7 +901,7 @@ globalvar> (globalvar.nnn::glob_float) of it not being necessary to probe into foreign space to retrieve enum values. When generating a .cxx wrapper file, a more general solution is employed. A wrapper variable is created in the module_wrap.cxx file, and - a ff:def-foreign-variable call is generated to retrieve it's value into lisp. + a ff:def-foreign-variable call is generated to retrieve its value into lisp.

    For example, the following header file @@ -957,7 +957,7 @@ EXPORT const int ACL_ENUM___FOO3__SWIG_0 = FOO3; -

    17.3.5 Arrays

    +

    18.3.5 Arrays

    @@ -1105,10 +1105,10 @@ namespace BAR { -

    17.3.6 Classes and Structs and Unions (oh my!)

    +

    18.3.6 Classes and Structs and Unions (oh my!)

    -

    17.3.6.1 CLOS wrapping of

    +

    18.3.6.1 CLOS wrapping of

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

    -

    17.3.6.2 CLOS Inheritance

    +

    18.3.6.2 CLOS Inheritance

    @@ -1131,12 +1131,12 @@ namespace BAR { inheritance of the classes in foreign code, with the ff:foreign-pointer class at its root. ff:foreign-pointer is a thin wrapper for pointers that is made available by the foreign function - interface. It's key benefit is that it may be passed as an argument + interface. Its key benefit is that it may be passed as an argument to any ff:def-foreign-call that is expecting a pointer as the parameter.

    -

    17.3.6.3 Member fields and functions

    +

    18.3.6.3 Member fields and functions

    @@ -1152,7 +1152,7 @@ namespace BAR { the interface does nothing for friend directives,

    -

    17.3.6.4 Why not directly access C++ classes using foreign types?

    +

    18.3.6.4 Why not directly access C++ classes using foreign types?

    @@ -1170,11 +1170,11 @@ namespace BAR { use the more robust wrapper functions.

    -

    17.3.7 Templates

    +

    18.3.7 Templates

    -

    17.3.7.1 Generating wrapper code for templates

    +

    18.3.7.1 Generating wrapper code for templates

    @@ -1187,7 +1187,7 @@ namespace BAR { directive.

    -

    17.3.7.2 Implicit Template instantiation

    +

    18.3.7.2 Implicit Template instantiation

    @@ -1197,7 +1197,7 @@ namespace BAR { class schema.

    -

    17.3.8 Typedef, Templates, and Synonym Types

    +

    18.3.8 Typedef, Templates, and Synonym Types

    @@ -1277,7 +1277,7 @@ synonym> -

    17.3.8.1 Choosing a primary type

    +

    18.3.8.1 Choosing a primary type

    @@ -1298,7 +1298,7 @@ synonym>

  • -

    17.3.9 Function overloading/Parameter defaulting

    +

    18.3.9 Function overloading/Parameter defaulting

    @@ -1461,7 +1461,7 @@ overload> -

    17.3.10 Operator wrapping and Operator overloading

    +

    18.3.10 Operator wrapping and Operator overloading

    @@ -1607,28 +1607,28 @@ opoverload> -

    17.3.11 Varargs

    +

    18.3.11 Varargs

    Variable length argument lists are not supported, by default. If such a function is encountered, a warning will generated to - stderr. Varargs are supported via the SWIG %vararg + stderr. Varargs are supported via the SWIG %varargs directive. This directive allows you to specify a (finite) argument list which will be inserted into the wrapper in place of the variable length argument indicator. As an example, - consider the function printf(). It's declaration would + consider the function printf(). Its declaration would appear as follows:

    See the following section on Variable Length arguments - provides examples on how %vararg can be used, along + provides examples on how %varargs can be used, along with other ways such functions can be wrapped.

    -

    17.3.12 C++ Exceptions

    +

    18.3.12 C++ Exceptions

    @@ -1640,7 +1640,7 @@ opoverload> implemented.

    -

    17.3.13 Pass by value, pass by reference

    +

    18.3.13 Pass by value, pass by reference

    @@ -1652,7 +1652,7 @@ opoverload> newly defined types.

    -

    17.4 Typemaps

    +

    18.4 Typemaps

    @@ -1663,7 +1663,7 @@ opoverload> on Typemaps for more information.

    -

    17.4.1 Code Generation in the C++ Wrapper

    +

    18.4.1 Code Generation in the C++ Wrapper

    @@ -1693,7 +1693,7 @@ return-val wrapper-name(parm0, parm1, ..., parmN) -

    17.4.1.1 IN Typemap

    +

    18.4.1.1 IN Typemap

    @@ -1728,14 +1728,14 @@ return-val wrapper-name(parm0, parm1, ..., parmN) -

    17.4.1.2 OUT Typemap

    +

    18.4.1.2 OUT Typemap

    The out typemap is used to generate code to form the return value of the wrapper from the return value of the wrapped function. This code is placed in the <convert and bind result to lresult> - section of the above code diagram. It's default mapping is as follows: + section of the above code diagram. Its default mapping is as follows:

    @@ -1752,13 +1752,13 @@ return-val wrapper-name(parm0, parm1, ..., parmN)
    -

    17.4.1.3 CTYPE Typemap

    +

    18.4.1.3 CTYPE Typemap

    This typemap is not used for code generation, but purely for the transformation of types in the parameter list of the wrapper function. - It's primary use is to handle by-value to by-reference conversion in the + Its primary use is to handle by-value to by-reference conversion in the wrappers parameter list. Its default settings are:

    @@ -1784,7 +1784,7 @@ return-val wrapper-name(parm0, parm1, ..., parmN) these common typemaps here.

    -

    17.4.2 Code generation in Lisp wrappers

    +

    18.4.2 Code generation in Lisp wrappers

    @@ -1803,7 +1803,7 @@ return-val wrapper-name(parm0, parm1, ..., parmN) 16.3.1 Namespaces for details.

    -

    17.4.2.1 LIN Typemap

    +

    18.4.2.1 LIN Typemap

    @@ -1846,7 +1846,7 @@ return-val wrapper-name(parm0, parm1, ..., parmN) -

    17.4.2.2 LOUT Typemap

    +

    18.4.2.2 LOUT Typemap

    @@ -1889,7 +1889,7 @@ return-val wrapper-name(parm0, parm1, ..., parmN) -

    17.4.2.3 FFITYPE Typemap

    +

    18.4.2.3 FFITYPE Typemap

    @@ -1939,7 +1939,7 @@ return-val wrapper-name(parm0, parm1, ..., parmN) -

    17.4.2.4 LISPTYPE Typemap

    +

    18.4.2.4 LISPTYPE Typemap

    @@ -1959,7 +1959,7 @@ return-val wrapper-name(parm0, parm1, ..., parmN) -

    17.4.2.5 LISPCLASS Typemap

    +

    18.4.2.5 LISPCLASS Typemap

    @@ -1983,7 +1983,7 @@ return-val wrapper-name(parm0, parm1, ..., parmN) -

    17.4.3 Modifying SWIG behavior using typemaps

    +

    18.4.3 Modifying SWIG behavior using typemaps

    @@ -2017,10 +2017,10 @@ return-val wrapper-name(parm0, parm1, ..., parmN) -

    17.5 Identifier Converter functions

    +

    18.5 Identifier Converter functions

    -

    17.5.1 Creating symbols in the lisp environment

    +

    18.5.1 Creating symbols in the lisp environment

    @@ -2041,11 +2041,11 @@ return-val wrapper-name(parm0, parm1, ..., parmN) of arguments.

    -

    17.5.2 Existing identifier-converter functions

    +

    18.5.2 Existing identifier-converter functions

    Two basic identifier routines have been defined. -

    17.5.2.1 identifier-convert-null

    +

    18.5.2.1 identifier-convert-null

    @@ -2054,7 +2054,7 @@ return-val wrapper-name(parm0, parm1, ..., parmN) strings, from which a symbol will be created.

    -

    17.5.2.2 identifier-convert-lispify

    +

    18.5.2.2 identifier-convert-lispify

    @@ -2063,7 +2063,7 @@ return-val wrapper-name(parm0, parm1, ..., parmN) same symbol transformations.

    -

    17.5.2.3 Default identifier to symbol conversions

    +

    18.5.2.3 Default identifier to symbol conversions

    @@ -2072,7 +2072,7 @@ return-val wrapper-name(parm0, parm1, ..., parmN) default naming conventions.

    -

    17.5.3 Defining your own identifier-converter

    +

    18.5.3 Defining your own identifier-converter

    @@ -2093,7 +2093,7 @@ foreign environment.

    The :type keyword argument provides more information on the type of -identifier. It's value is a symbol. This allows the +identifier. Its value is a symbol. This allows the identifier-converter to apply different heuristics when mapping different types of identifiers to symbols. SWIG will generate calls to your identifier-converter using the following types. @@ -2123,12 +2123,12 @@ scope in the specified class.

    The :arity keyword argument only appears in swig:swig-defmethod forms -generated for overloaded functions. It's value is an integer +generated for overloaded functions. Its value is an integer indicating the number of arguments passed to the routine indicated by this identifier.

    -

    17.5.4 Instructing SWIG to use a particular identifier-converter

    +

    18.5.4 Instructing SWIG to use a particular identifier-converter

    diff --git a/Doc/Manual/Android.html b/Doc/Manual/Android.html index 443d77691..e62139797 100644 --- a/Doc/Manual/Android.html +++ b/Doc/Manual/Android.html @@ -5,7 +5,7 @@ -

    18 SWIG and Android

    +

    19 SWIG and Android

    @@ -28,7 +30,7 @@ This chapter describes SWIG's support of Android. -

    18.1 Overview

    +

    19.1 Overview

    @@ -38,14 +40,14 @@ Everything in the Java chapter applies to generating cod This chapter contains a few Android specific notes and examples.

    -

    18.2 Android examples

    +

    19.2 Android examples

    -

    18.2.1 Examples introduction

    +

    19.2.1 Examples introduction

    -The examples require the the Android SDK and Android NDK which can be installed as per instructions in the links. +The examples require the Android SDK and Android NDK which can be installed as per instructions in the links. The Eclipse version is not required for these examples as just the command line tools are used (shown for Linux as the host, but Windows will be very similar, if not identical in most places). Add the SDK tools and NDK tools to your path and create a directory somewhere for your Android projects (adjust PATH as necessary to where you installed the tools):

    @@ -74,7 +76,7 @@ $ android list targets The following examples are shipped with SWIG under the Examples/android directory and include a Makefile to build and install each example.

    -

    18.2.2 Simple C example

    +

    19.2.2 Simple C example

    @@ -396,7 +398,7 @@ Run the app again and this time you will see the output pictured below, showing

    Android screenshot of SwigSimple example
    -

    18.2.3 C++ class example

    +

    19.2.3 C++ class example

    @@ -433,11 +435,11 @@ public: } virtual ~Shape() { nshapes--; - }; + } double x, y; void move(double dx, double dy); - virtual double area(void) = 0; - virtual double perimeter(void) = 0; + virtual double area() = 0; + virtual double perimeter() = 0; static int nshapes; }; @@ -445,18 +447,18 @@ class Circle : public Shape { private: double radius; public: - Circle(double r) : radius(r) { }; - virtual double area(void); - virtual double perimeter(void); + Circle(double r) : radius(r) { } + virtual double area(); + virtual double perimeter(); }; class Square : public Shape { private: double width; public: - Square(double w) : width(w) { }; - virtual double area(void); - virtual double perimeter(void); + Square(double w) : width(w) { } + virtual double area(); + virtual double perimeter(); }; @@ -480,19 +482,19 @@ void Shape::move(double dx, double dy) { int Shape::nshapes = 0; -double Circle::area(void) { +double Circle::area() { return M_PI*radius*radius; } -double Circle::perimeter(void) { +double Circle::perimeter() { return 2*M_PI*radius; } -double Square::area(void) { +double Square::area() { return width*width; } -double Square::perimeter(void) { +double Square::perimeter() { return 4*width; } @@ -744,6 +746,36 @@ Run the app to see the result of calling the C++ code from Java:

    Android screenshot of SwigClass example
    +

    19.2.4 Other examples

    + + +

    +The Examples/android directory contains further examples which can be run and installed in a similar manner to the previous two examples. +

    + +

    +Note that the 'extend' example is demonstrates the directors feature. +Normally C++ exception handling and the STL is not available by default in the version of g++ shipped with Android, but this example turns these features on as described in the next section. +

    + +

    19.3 C++ STL

    + + +

    +Should the C++ Standard Template Library (STL) be required, an Application.mk file needs to be created +in the same directory as the Android.mk directory containing information about the STL 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/Arguments.html b/Doc/Manual/Arguments.html index 1ae9a6d2f..3b7713686 100644 --- a/Doc/Manual/Arguments.html +++ b/Doc/Manual/Arguments.html @@ -6,7 +6,7 @@ -

    9 Argument Handling

    +

    10 Argument Handling

      @@ -42,7 +42,7 @@ return multiple values through the arguments of a function. This chapter describes some of the techniques for doing this.

      -

      9.1 The typemaps.i library

      +

      10.1 The typemaps.i library

      @@ -50,7 +50,7 @@ This section describes the typemaps.i library file--commonly used to change certain properties of argument conversion.

      -

      9.1.1 Introduction

      +

      10.1.1 Introduction

      @@ -194,7 +194,7 @@ else. To clear a typemap, the %clear directive should be used. For e

    -

    9.1.2 Input parameters

    +

    10.1.2 Input parameters

    @@ -247,7 +247,7 @@ When the function is used in the scripting language interpreter, it will work li result = add(3,4) -

    9.1.3 Output parameters

    +

    10.1.3 Output parameters

    @@ -314,7 +314,7 @@ iresult, dresult = foo(3.5, 2) -

    9.1.4 Input/Output parameters

    +

    10.1.4 Input/Output parameters

    @@ -379,7 +379,7 @@ rather than directly overwriting the value of the original input object. SWIG. Backwards compatibility is preserved, but deprecated.

    -

    9.1.5 Using different names

    +

    10.1.5 Using different names

    @@ -413,7 +413,7 @@ Typemap declarations are lexically scoped so a typemap takes effect from the poi file or a matching %clear declaration.

    -

    9.2 Applying constraints to input values

    +

    10.2 Applying constraints to input values

    @@ -423,7 +423,7 @@ insure that a value is positive, or that a pointer is non-NULL. This can be accomplished including the constraints.i library file.

    -

    9.2.1 Simple constraint example

    +

    10.2.1 Simple constraint example

    @@ -449,7 +449,7 @@ the arguments violate the constraint condition, a scripting language exception will be raised. As a result, it is possible to catch bad values, prevent mysterious program crashes and so on.

    -

    9.2.2 Constraint methods

    +

    10.2.2 Constraint methods

    @@ -465,7 +465,7 @@ NONNULL Non-NULL pointer (pointers only). -

    9.2.3 Applying constraints to new datatypes

    +

    10.2.3 Applying constraints to new datatypes

    diff --git a/Doc/Manual/CPlusPlus11.html b/Doc/Manual/CPlusPlus11.html new file mode 100644 index 000000000..ce9174254 --- /dev/null +++ b/Doc/Manual/CPlusPlus11.html @@ -0,0 +1,1182 @@ + + + +SWIG and C++11 + + + + +

    7 SWIG and C++11

    + + + + + + +

    7.1 Introduction

    + + +

    This chapter gives you a brief overview about the SWIG +implementation of the C++11 standard. This part of SWIG is still a work in +progress. +

    +

    SWIG supports the new C++ syntax changes with some minor limitations +in some areas such as decltype expressions and variadic templates. Wrappers for the +new STL types (unordered_ containers, result_of, tuples) are incomplete. +The wrappers for the new containers would work much like the C++03 containers and +users are welcome to help by adapting the existing container interface files and submitting them +as a patch for inclusion in future versions of SWIG. +

    + +

    7.2 Core language changes

    + + +

    7.2.1 Rvalue reference and move semantics

    + + +

    +SWIG correctly parses the rvalue reference syntax '&&', +for example the typical usage of it in the move constructor and move assignment operator below: +

    + +
    +class MyClass {
    +...
    +  std::vector<int> numbers;
    +public:
    +  MyClass(MyClass &&other) : numbers(std::move(other.numbers)) {}
    +  MyClass & operator=(MyClass &&other) {
    +    numbers = std::move(other.numbers);
    +    return *this;
    +  }
    +};
    +
    + +

    +Rvalue references are designed for C++ temporaries and so are not very useful when used from non-C++ target languages. +Generally you would just ignore them via %ignore before parsing the class. +For example, ignore the move constructor: +

    + +
    +%ignore MyClass::MyClass(MyClass &&);
    +
    + +

    +The plan is to ignore move constructors by default in a future version of SWIG. Note that both normal assignment operators as well as move assignment operators are ignored by default in most target languages with the following warning: +

    + +
    +
    +example.i:18: Warning 503: Can't wrap 'operator =' unless renamed to a valid identifier.
    +
    +
    + + +

    7.2.2 Generalized constant expressions

    + + +

    SWIG parses and identifies the keyword constexpr, but cannot fully utilise it. +These C++ compile time constants are usable as runtime constants from the target languages. +Below shows example usage for assigning a C++ compile time constant from a compile time constant function: +

    + +
    +constexpr int XXX() { return 10; }
    +constexpr int YYY = XXX() + 100;
    +
    + +

    +When either of these is used from a target language, a runtime call is made to obtain the underlying constant. +

    + +

    7.2.3 Extern template

    + + +

    SWIG correctly parses the keywords extern template. +However, this template instantiation suppression in a translation unit has no relevance outside of the C++ compiler and so is not used by SWIG. +SWIG only uses %template for instantiating and wrapping templates.

    + +
    +template class std::vector<int>;        // C++03 explicit instantiation in C++
    +extern template class std::vector<int>; // C++11 explicit instantiation suppression in C++
    +%template(VectorInt) std::vector<int>;  // SWIG instantiation
    +
    + +

    7.2.4 Initializer lists

    + + +

    +Initializer lists are very much a C++ compiler construct and are not very accessible from wrappers as +they are intended for compile time initialization of classes using the special std::initializer_list type. +SWIG detects usage of initializer lists and will emit a special informative warning each time one is used: +

    + +
    +
    +example.i:33: Warning 476: Initialization using std::initializer_list.
    +
    +
    + +

    +Initializer lists usually appear in constructors but can appear in any function or method. +They often appear in constructors which are overloaded with alternative approaches to initializing a class, +such as the std container's push_back method for adding elements to a container. +The recommended approach then is to simply ignore the initializer-list constructor, for example: +

    + +
    +%ignore Container::Container(std::initializer_list<int>);
    +class Container {
    +public:
    +  Container(std::initializer_list<int>); // initializer-list constructor
    +  Container();
    +  void push_back(const int &);
    +  ...
    +};
    +
    + +

    Alternatively you could modify the class and add another constructor for initialization by some other means, +for example by a std::vector:

    + +
    +%include <std_vector.i>
    +class Container {
    +public:
    +  Container(const std::vector<int> &);
    +  Container(std::initializer_list<int>); // initializer-list constructor
    +  Container();
    +  void push_back(const int &);
    +  ...
    +};
    +
    + +

    And then call this constructor from your target language, for example, in Python, the following will call the constructor taking the std::vector:

    + +
    +>>> c = Container( [1,2,3,4] )
    +
    + +

    +If you are unable to modify the class being wrapped, consider ignoring the initializer-list constructor and using +%extend to add in an alternative constructor: +

    + +
    +%include <std_vector.i>
    +%extend Container {
    +  Container(const std::vector<int> &elements) {
    +    Container *c = new Container();
    +    for (int element : elements)
    +      c->push_back(element);
    +    return c;
    +  }
    +}
    +
    +%ignore Container::Container(std::initializer_list<int>);
    +
    +class Container {
    +public:
    +  Container(std::initializer_list<int>); // initializer-list constructor
    +  Container();
    +  void push_back(const int &);
    +  ...
    +};
    +
    + +

    +The above makes the wrappers look is as if the class had been declared as follows: +

    + +
    +%include <std_vector.i>
    +class Container {
    +public:
    +  Container(const std::vector<int> &);
    +//  Container(std::initializer_list<int>); // initializer-list constructor (ignored)
    +  Container();
    +  void push_back(const int &);
    +  ...
    +};
    +
    + +

    +std::initializer_list is simply a container that can only be initialized at compile time. +As it is just a C++ type, it is possible to write typemaps for a target language container to map onto +std::initializer_list. However, this can only be done for a fixed number of elements as +initializer lists are not designed to be constructed with a variable number of arguments at runtime. +The example below is a very simple approach which ignores any parameters passed in and merely initializes +with a fixed list of fixed integer values chosen at compile time: +

    + +
    +%typemap(in) std::initializer_list<int> {
    +  $1 = {10, 20, 30, 40, 50};
    +}
    +class Container {
    +public:
    +  Container(std::initializer_list<int>); // initializer-list constructor
    +  Container();
    +  void push_back(const int &);
    +  ...
    +};
    +
    + +

    +Any attempt at passing in values from the target language will be ignored and be replaced by {10, 20, 30, 40, 50}. +Needless to say, this approach is very limited, but could be improved upon, but only slightly. +A typemap could be written to map a fixed number of elements on to the std::initializer_list, +but with values decided at runtime. +The typemaps would be target language specific. +

    + +

    +Note that the default typemap for std::initializer_list does nothing but issue the warning +and hence any user supplied typemaps will override it and suppress the warning. +

    + +

    7.2.5 Uniform initialization

    + + +

    The curly brackets {} for member initialization are fully +supported by SWIG:

    + +
    +struct BasicStruct {
    + int x;
    + double y;
    +};
    + 
    +struct AltStruct {
    +  AltStruct(int x, double y) : x_{x}, y_{y} {}
    + 
    +  int x_;
    +  double y_;
    +};
    +
    +BasicStruct var1{5, 3.2}; // only fills the struct components
    +AltStruct var2{2, 4.3};   // calls the constructor
    +
    + +

    Uniform initialization does not affect usage from the target language, for example in Python:

    + +
    +>>> a = AltStruct(10, 142.15)
    +>>> a.x_
    +10
    +>>> a.y_
    +142.15
    +
    + +

    7.2.6 Type inference

    + + +

    SWIG supports decltype() with some limitations. Single +variables are allowed, however, expressions are not supported yet. For +example, the following code will work:

    +
    +int i;
    +decltype(i) j;
    +
    + +

    However, using an expression inside the decltype results in syntax error:

    +
    +int i; int j;
    +decltype(i+j) k;  // syntax error
    +
    + +

    7.2.7 Range-based for-loop

    + + +

    This feature is part of the implementation block only. SWIG +ignores it.

    + +

    7.2.8 Lambda functions and expressions

    + + +

    SWIG correctly parses most of the Lambda functions syntax. For example:

    +
    +auto val = [] { return something; };
    +auto sum = [](int x, int y) { return x+y; };
    +auto sum = [](int x, int y) -> int { return x+y; };
    +
    + +

    The lambda functions are removed from the wrappers for now, because of the lack of support +for closures (scope of the lambda functions) in the target languages.

    + +

    +Lambda functions used to create variables can also be parsed, but due to limited support of auto when +the type is deduced from the expression, the variables are simply ignored. +

    + +
    +auto six = [](int x, int y) { return x+y; }(4, 2);
    +
    + +

    +Better support should be available in a later release. +

    + +

    7.2.9 Alternate function syntax

    + + +

    SWIG fully supports the new definition of functions. For example:

    +
    +struct SomeStruct {
    +  int FuncName(int x, int y);
    +};
    +
    + +

    can now be written as in C++11:

    + +
    +struct SomeStruct {
    +  auto FuncName(int x, int y) -> int;
    +};
    + 
    +auto SomeStruct::FuncName(int x, int y) -> int {
    +  return x + y;
    +}
    +
    + +

    The usage in the target languages remains the same, for example in Python:

    + +
    +>>> a = SomeStruct()
    +>>> a.FuncName(10,5)
    +15
    +
    + +

    SWIG will also deal with type inference for the return type, as per the limitations described earlier. For example:

    +
    +auto square(float a, float b) -> decltype(a);
    +
    + +

    7.2.10 Object construction improvement

    + + +

    +There are three parts to object construction improvement. +The first improvement is constructor delegation such as the following: +

    + +
    +class A {
    +public:
    +  int a;
    +  int b;
    +  int c;
    +
    +  A() : A(10) {}
    +  A(int aa) : A(aa, 20) {}
    +  A(int aa, int bb) : A(aa, bb, 30) {}
    +  A(int aa, int bb, int cc) { a=aa; b=bb; c=cc; }
    +};
    +
    + +

    +where peer constructors can be called. SWIG handles this without any issue. +

    + +

    +The second improvement is constructor inheritance via a using declaration. +This is parsed correctly, but the additional constructors are not currently added to the derived proxy class in the target language. +An example is shown below: + +

    + +
    +class BaseClass {
    +public:
    +  BaseClass(int iValue);
    +};
    +
    +class DerivedClass: public BaseClass {
    +  public:
    +  using BaseClass::BaseClass; // Adds DerivedClass(int) constructor
    +};
    +
    + +

    +The final part is member initialization at the site of the declaration. +This kind of initialization is handled by SWIG. +

    + +
    +class SomeClass {
    +public:
    +    SomeClass() {}
    +    explicit SomeClass(int new_value) : value(new_value) {}
    +
    +    int value = 5;
    +};
    +
    + +

    7.2.11 Explicit overrides and final

    + + +

    +The special identifiers final and override can be used on methods and destructors, +such as in the following example: +

    + +
    +struct BaseStruct {
    +  virtual void ab() const = 0;
    +  virtual void cd();
    +  virtual void ef();
    +  virtual ~BaseStruct();
    +};
    +struct DerivedStruct : BaseStruct {
    +  virtual void ab() const override;
    +  virtual void cd() final;
    +  virtual void ef() final override;
    +  virtual ~DerivedStruct() override;
    +};
    +
    + + +

    7.2.12 Null pointer constant

    + + +

    The nullptr constant is mostly unimportant in wrappers. In the few places it has an effect, it is treated like NULL.

    + +

    7.2.13 Strongly typed enumerations

    + + +

    SWIG parses the new enum class syntax and forward declarator for the enums:

    +
    +enum class MyEnum : unsigned int;
    +
    + +

    The strongly typed enumerations are treated the same as the ordinary and anonymous enums. +This is because the required nested class support in SWIG is new and has not yet been incorporated into the wrapping of these strongly typed enum classes. +This is usually not a problem, however, +there may be some name clashes. For example, the following code:

    + +
    +class Color {
    +  enum class PrintingColors : unsigned int {
    +    Cyan, Magenta, Yellow, Black
    +  };
    +  
    +  enum class BasicColors {
    +    Red, Green, Blue
    +  };
    +  
    +  enum class AllColors {
    +    // produces warnings because of duplicate names
    +    Yellow, Orange, Red, Magenta, Blue, Cyan, Green, Pink, Black, White
    +  };
    +};
    +
    + +

    A workaround is to write these as a series of separate classes containing anonymous enums:

    + +
    +class PrintingColors {
    +  enum : unsigned int {
    +    Cyan, Magenta, Yellow, Black
    +  };
    +};
    +
    +class BasicColors {
    +  enum : unsigned int {
    +    Red, Green, Blue
    +  };
    +};
    +
    +class AllColors {
    +  enum : unsigned int {
    +    Yellow, Orange, Red, Magenta, Blue, Cyan, Green, Pink, Black, White
    +  };
    +};
    +
    + +

    +Expect to see this improved in a future version of SWIG. +

    + +

    7.2.14 Double angle brackets

    + + +

    SWIG correctly parses the symbols >> as closing the +template block, if found inside it at the top level, or as the right +shift operator >> otherwise.

    + +
    +std::vector<std::vector<int>> myIntTable;
    +
    + +

    7.2.15 Explicit conversion operators

    + + +

    SWIG correctly parses the keyword explicit for operators in addition to constructors now. +For example:

    + +
    +class U {
    +public:
    +  int u;
    +};
    +
    +class V {
    +public:
    +  int v;
    +};
    +
    +class TestClass {
    +public:
    +  //implicit converting constructor
    +  TestClass(U const &val) { t=val.u; }
    +
    +  // explicit constructor
    +  explicit TestClass(V const &val) { t=val.v; }
    +
    +  int t;
    +};
    +
    +struct Testable {
    +  // explicit conversion operator
    +  explicit operator bool() const {
    +    return false;
    +  }
    +};
    +
    + +

    +The effect of explicit constructors and operators has little relevance for the proxy classes as target +languages don't have the same concepts of implicit conversions as C++. +Conversion operators either with or without explicit need renaming to a valid identifier name in order to make +them available as a normal proxy method. +

    + +

    7.2.16 Alias templates

    + + +

    +The following is an example of an alias template: + +

    +template< typename T1, typename T2, int >
    +class SomeType {
    +  T1 a;
    +  T2 b;
    +  int c;
    +};
    +
    +template< typename T2 >
    +using TypedefName = SomeType<char*, T2, 5>;
    +
    + +

    +These are partially supported as SWIG will parse these and identify them, however, they are ignored as they are not added to the type system. A warning such as the following is issued: +

    + +
    +
    +example.i:13: Warning 342: The 'using' keyword in template aliasing is not fully supported yet.
    +
    +
    + +

    +Similarly for non-template type aliasing: +

    + +
    +using PFD = void (*)(double); // New introduced syntax
    +
    + +

    +A warning will be issued: +

    + +
    +
    +example.i:17: Warning 341: The 'using' keyword in type aliasing is not fully supported yet.
    +
    +
    + + +

    The equivalent old style typedefs can be used as a workaround:

    + +
    +typedef void (*PFD)(double);  // The old style
    +
    + +

    7.2.17 Unrestricted unions

    + + +

    SWIG fully supports any type inside a union even if it does not +define a trivial constructor. For example, the wrapper for the following +code correctly provides access to all members in the union:

    + +
    +struct point {
    +  point() {}
    +  point(int x, int y) : x_(x), y_(y) {}
    +  int x_, y_;
    +};
    +
    +#include <new> // For placement 'new' in the constructor below
    +union P {
    +  int z;
    +  double w;
    +  point p; // Illegal in C++03; legal in C++11.
    +  // Due to the point member, a constructor definition is required.
    +  P() {
    +    new(&p) point();
    +  }
    +} p1;
    +
    + +

    7.2.18 Variadic templates

    + + +

    SWIG supports the variadic templates syntax (inside the <> +block, variadic class inheritance and variadic constructor and +initializers) with some limitations. The following code is correctly parsed:

    + +
    +template <typename... BaseClasses> class ClassName : public BaseClasses... {
    +public:
    +   ClassName (BaseClasses &&... baseClasses) : BaseClasses(baseClasses)... {}
    +}
    +
    + +

    +For now however, the %template directive only accepts one parameter substitution +for the variable template parameters. +

    + +
    +%template(MyVariant1) ClassName<>         // zero argument not supported yet
    +%template(MyVariant2) ClassName<int>      // ok
    +%template(MyVariant3) ClassName<int, int> // too many arguments not supported yet
    +
    + +

    Support for the variadic sizeof() function is correctly parsed:

    + +
    +const int SIZE = sizeof...(ClassName<int, int>);
    +
    + +

    +In the above example SIZE is of course wrapped as a constant. +

    + +

    7.2.19 New string literals

    + + +

    SWIG supports wide string and Unicode string constants and raw string literals.

    + +
    +// New string literals
    +wstring         aa =  L"Wide string";
    +const char     *bb = u8"UTF-8 string";
    +const char16_t *cc =  u"UTF-16 string";
    +const char32_t *dd =  U"UTF-32 string";
    +
    +// Raw string literals
    +const char      *xx =        ")I'm an \"ascii\" \\ string.";
    +const char      *ee =   R"XXX()I'm an "ascii" \ string.)XXX"; // same as xx
    +wstring          ff =  LR"XXX(I'm a "raw wide" \ string.)XXX";
    +const char      *gg = u8R"XXX(I'm a "raw UTF-8" \ string.)XXX";
    +const char16_t  *hh =  uR"XXX(I'm a "raw UTF-16" \ string.)XXX";
    +const char32_t  *ii =  UR"XXX(I'm a "raw UTF-32" \ string.)XXX";
    +
    + +

    +Non-ASCII string support varies quite a bit among the various target languages though. +

    + +

    +Note: There is a bug currently where SWIG's preprocessor incorrectly parses an odd number of double quotes +inside raw string literals. +

    + +

    7.2.20 User-defined literals

    + + +

    +SWIG parses the declaration of user-defined literals, that is, the operator "" _mysuffix() function syntax. +

    + +

    +Some examples are the raw literal: +

    +
    +OutputType operator "" _myRawLiteral(const char * value);
    +
    + +

    +numeric cooked literals: +

    +
    +OutputType operator "" _mySuffixIntegral(unsigned long long);
    +OutputType operator "" _mySuffixFloat(long double);
    +
    + +

    +and cooked string literals: +

    +
    +OutputType operator "" _mySuffix(const char * string_values, size_t num_chars);
    +OutputType operator "" _mySuffix(const wchar_t * string_values, size_t num_chars);
    +OutputType operator "" _mySuffix(const char16_t * string_values, size_t num_chars);
    +OutputType operator "" _mySuffix(const char32_t * string_values, size_t num_chars);
    +
    + +

    +Like other operators that SWIG parses, a warning is given about renaming the operator in order for it to be wrapped: +

    + +
    +example.i:27: Warning 503: Can't wrap 'operator "" _myRawLiteral' unless renamed to a valid identifier.
    +
    + +

    +If %rename is used, then it can be called like any other wrapped method. +Currently you need to specify the full declaration including parameters for %rename: +

    + +
    +%rename(MyRawLiteral)  operator"" _myRawLiteral(const char * value);
    +
    + +

    +Or if you just wish to ignore it altogether: +

    + +
    +%ignore operator "" _myRawLiteral(const char * value);
    +
    + +

    +Note that use of user-defined literals such as the following still give a syntax error: +

    + +
    +OutputType var1 = "1234"_suffix;
    +OutputType var2 = 1234_suffix;
    +OutputType var3 = 3.1416_suffix;
    +
    + +

    7.2.21 Thread-local storage

    + + +

    SWIG correctly parses the thread_local keyword. For example, variables +reachable by the current thread can be defined as:

    + +
    +struct A {
    +   static thread_local int val;
    +};
    +thread_local int global_val;
    +
    + +

    +The use of the thread_local storage specifier does not affect the wrapping process; it does not modify +the wrapper code compared to when it is not specified. +A variable will be thread local if accessed from different threads from the target language in the +same way that it will be thread local if accessed from C++ code. +

    + +

    7.2.22 Explicitly defaulted functions and deleted functions

    + + +

    SWIG handles explicitly defaulted functions, that is, = default added to a function declaration. Deleted definitions, which are also called deleted functions, have = delete added to the function declaration. +For example:

    + +
    +struct NonCopyable {
    +  NonCopyable & operator=(const NonCopyable &) = delete; /* Removes operator= */
    +  NonCopyable(const NonCopyable &) = delete;             /* Removes copy constructor */
    +  NonCopyable() = default;                               /* Explicitly allows the empty constructor */
    +};
    +
    + +

    +Wrappers for deleted functions will not be available in the target language. +Wrappers for defaulted functions will of course be available in the target language. +Explicitly defaulted functions have no direct effect for SWIG wrapping as the declaration is handled +much like any other method declaration parsed by SWIG. +

    + +

    +Deleted functions are also designed to prevent implicit conversions when calling the function. +For example, the C++ compiler will not compile any code which attempts to use an int as the type of the parameter passed to f below: +

    + +
    +struct NoInt {
    +    void f(double i);
    +    void f(int) = delete;
    +};
    +
    + +

    +This is a C++ compile time check and SWIG does not make any attempt to detect if the target language is using an int instead of a double though, +so in this case it is entirely possible to pass an int instead of a double to f from Java, Python etc. +

    + +

    7.2.23 Type long long int

    + + +

    SWIG correctly parses and uses the new long long type already introduced in C99 some time ago.

    + +

    7.2.24 Static assertions

    + + +

    +SWIG correctly parses the new static_assert declarations. +This is a C++ compile time directive so there isn't anything useful that SWIG can do with it. +

    + +
    +template <typename T>
    +struct Check {
    +  static_assert(sizeof(int) <= sizeof(T), "not big enough");
    +};
    +
    + +

    7.2.25 Allow sizeof to work on members of classes without an explicit object

    + + +

    +SWIG can parse the new sizeof() on types as well as on objects. For example: +

    + +
    +struct A {
    +  int member;
    +};
    +
    +const int SIZE = sizeof(A::member); // does not work with C++03. Okay with C++11
    +
    + +

    In Python:

    +
    +>>> SIZE
    +8
    +
    + +

    7.2.26 Exception specifications and noexcept

    + + +

    +C++11 added in the noexcept specification to exception specifications to indicate that a function simply may or may not throw an exception, without actually naming any exception. +SWIG understands these, although there isn't any useful way that this information can be taken advantage of by target languages, +so it is as good as ignored during the wrapping process. +Below are some examples of noexcept in function declarations: +

    + +
    +static void noex1() noexcept;
    +int noex2(int) noexcept(true);
    +int noex3(int, bool) noexcept(false);
    +
    + +

    7.2.27 Control and query object alignment

    + + +

    +An alignof operator is used mostly within C++ to return alignment in number of bytes, but could be used to initialize a variable as shown below. +The variable's value will be available for access by the target language as any other variable's compile time initialised value. + +

    +const int align1 = alignof(A::member);
    +
    + +

    +The alignas specifier for variable alignment is not yet supported. +Example usage: +

    + +
    +struct alignas(16) S {
    +  int num;
    +};
    +alignas(double) unsigned char c[sizeof(double)];
    +
    + +

    +Use the preprocessor to work around this for now: +

    + +
    +#define alignas(T)
    +
    + + +

    7.2.28 Attributes

    + + +

    +Attributes such as those shown below, are not yet supported and will give a syntax error. +

    + +
    +int [[attr1]] i [[attr2, attr3]];
    +
    +[[noreturn, nothrow]] void f [[noreturn]] ();
    +
    + +

    7.3 Standard library changes

    + + +

    7.3.1 Threading facilities

    + + +

    SWIG does not currently wrap or use any of the new threading +classes introduced (thread, mutex, locks, condition variables, task). The main reason is that +SWIG target languages offer their own threading facilities so there is limited use for them. +

    + +

    7.3.2 Tuple types

    + + +

    +SWIG does not provide library files for the new tuple types yet. +Variadic template support requires further work to provide substantial tuple wrappers. +

    + +

    7.3.3 Hash tables

    + + +

    +The new hash tables in the STL are unordered_set, unordered_multiset, unordered_map, unordered_multimap. +These are not available in SWIG, but in principle should be easily implemented by adapting the current STL containers. +

    + +

    7.3.4 Regular expressions

    + + +

    +While SWIG could provide wrappers for the new C++11 regular expressions classes, there is little need as the target languages have their own regular expression facilities. +

    + +

    7.3.5 General-purpose smart pointers

    + + +

    +SWIG provides special smart pointer handling for std::shared_ptr in the same way it has support for boost::shared_ptr. +Please see the shared_ptr smart pointer library section. +There is no special smart pointer handling available for std::weak_ptr and std::unique_ptr yet. +

    + +

    7.3.6 Extensible random number facility

    + + +

    This feature extends and standardizes the standard library only and does not effect the C++ language nor SWIG.

    + +

    7.3.7 Wrapper reference

    + + +

    +Wrapper references are similar to normal C++ references but are copy-constructible and copy-assignable. +They could conceivably be used in public APIs. +There is no special support for std::reference_wrapper in SWIG though. +Users would need to write their own typemaps if wrapper references are being used and these would be similar to the plain C++ reference typemaps. +

    + + +

    7.3.8 Polymorphous wrappers for function objects

    + + +

    +SWIG supports functor classes in a few languages in a very natural way. +However nothing is provided yet for the new std::function template. +SWIG will parse usage of the template like any other template. +

    + +
    +%rename(__call__) Test::operator(); // Default renaming used for Python
    +
    +struct Test {
    +  bool operator()(int x, int y); // function object
    +};
    +
    +#include <functional>
    +std::function<void (int, int)> pF = Test;   // function template wrapper
    +
    +
    + +

    +Example of supported usage of the plain functor from Python is shown below. +It does not involve std::function. +

    + +
    +t = Test()
    +b = t(1,2) # invoke C++ function object
    +
    + +

    7.3.9 Type traits for metaprogramming

    + + +

    The type_traits functions to support C++ metaprogramming is useful at compile time and is aimed specifically at C++ development:

    + +
    +#include <type_traits>
    +
    +// First way of operating.
    +template< bool B > struct algorithm {
    +  template< class T1, class T2 > static int do_it(T1 &, T2 &)  { /*...*/ return 1; }
    +};
    +
    +// Second way of operating.
    +template<> struct algorithm<true> {
    +  template< class T1, class T2 > static int do_it(T1, T2)  { /*...*/ return 2; }
    +};
    +
    +// Instantiating 'elaborate' will automatically instantiate the correct way to operate, depending on the types used.
    +template< class T1, class T2 > int elaborate(T1 A, T2 B) {
    +  // Use the second way only if 'T1' is an integer and if 'T2' is a floating point,
    +  // otherwise use the first way.
    +  return algorithm< std::is_integral<T1>::value && std::is_floating_point<T2>::value >::do_it(A, B);
    +}
    +
    + +

    +SWIG correctly parses the template specialization, template types etc. +However, metaprogramming and the additional support in the type_traits header is really for compile time and is not much use at runtime for the target languages. +For example, as SWIG requires explicit instantiation of templates via %template, there isn't much that std::is_integral<int> is going to provide by itself. +However, template functions using such metaprogramming techniques might be useful to wrap. +For example, the following instantiations could be made: +

    + +
    +%template(Elaborate) elaborate<int, int>;
    +%template(Elaborate) elaborate<int, double>;
    +
    + +

    +Then the appropriate algorithm can be called for the subset of types given by the above %template instantiations from a target language, such as Python: +

    + +
    +>>> Elaborate(0, 0)
    +1
    +>>> Elaborate(0, 0.0)
    +2
    +
    + +

    7.3.10 Uniform method for computing return type of function objects

    + + +

    +The new std::result_of class introduced in the <functional> header provides a generic way to obtain the return type of a function type via std::result_of::type. +There isn't any library interface file to support this type. +With a bit of work, SWIG will deduce the return type of functions when used in std::result_of using the approach shown below. +The technique basically forward declares the std::result_of template class, then partially specializes it for the function types of interest. +SWIG will use the partial specialization and hence correctly use the std::result_of::type provided in the partial specialization. +

    + +
    +%inline %{
    +#include <functional>
    +typedef double(*fn_ptr)(double);
    +%}
    +
    +namespace std {
    +  // Forward declaration of result_of
    +  template<typename Func> struct result_of;
    +  // Add in a partial specialization of result_of
    +  template<> struct result_of< fn_ptr(double) > {
    +    typedef double type;
    +  };
    +}
    +
    +%template() std::result_of< fn_ptr(double) >;
    +
    +%inline %{
    +
    +double square(double x) {
    +  return (x * x);
    +}
    +
    +template<class Fun, class Arg>
    +typename std::result_of<Fun(Arg)>::type test_result_impl(Fun fun, Arg arg) {
    +  return fun(arg);
    +}
    +%}
    +
    +%template(test_result) test_result_impl< fn_ptr, double >;
    +%constant double (*SQUARE)(double) = square;
    +
    + +

    +Note the first use of %template which SWIG requires to instantiate the template. +The empty template instantiation suffices as no proxy class is required for std::result_of<Fun(Arg)>::type as this type is really just a double. +The second %template instantiates the template function which is being wrapped for use as a callback. +The %constant can then be used for any callback function as described in Pointers to functions and callbacks. +

    + +

    +Example usage from Python should give the not too surprising result: +

    + +
    +>>> test_result(SQUARE, 5.0)
    +25.0
    +
    + +

    +Phew, that is a lot of hard work to get a callback working. +You could just go with the more attractive option of just using double as the return type in the function declaration instead of result_of! +

    + + + diff --git a/Doc/Manual/CSharp.html b/Doc/Manual/CSharp.html index b511dc126..7f53423fc 100644 --- a/Doc/Manual/CSharp.html +++ b/Doc/Manual/CSharp.html @@ -5,11 +5,14 @@ -

    19 SWIG and C#

    +

    20 SWIG and C#

    • Introduction +
    • Differences to the Java module
    • Void pointers
    • C# Arrays @@ -38,6 +41,7 @@
    • Memory management for objects passed to the C++ layer
    • Date marshalling using the csin typemap and associated attributes
    • A date example demonstrating marshalling of C# properties +
    • Date example demonstrating the 'pre' and 'post' typemap attributes for directors
    • Turning wrapped classes into partial classes
    • Extending proxy classes with additional C# code
    • Underlying type for enums @@ -48,7 +52,7 @@ -

      19.1 Introduction

      +

      20.1 Introduction

      @@ -68,7 +72,14 @@ The Microsoft Developer Network (MSDN) h Monodoc, available from the Mono project, has a very useful section titled Interop with native libraries.

      -

      19.2 Differences to the Java module

      +

      20.1.1 SWIG 2 Compatibility

      + + +

      +In order to minimize name collisions between names generated based on input to SWIG and names used in the generated code from the .NET framework, SWIG 3 fully qualifies the use of all .NET types. Furthermore, SWIG 3 avoids using directives in generated code. This breaks backwards compatibility with typemaps, pragmas, etc written for use with SWIG 2 that assume the presence of using System; or using System.Runtime.InteropServices; directives in the intermediate class imports, module imports, or proxy imports. SWIG 3 supports backwards compatibility though the use of the SWIG2_CSHARP macro. If SWIG2_CSHARP is defined, SWIG 3 generates using directives in the intermediate class, module class, and proxy class code similar to those generated by SWIG 2. This can be done without modifying any of the input code by passing the -DSWIG2_CSHARP commandline parameter when executing swig. +

      + +

      20.2 Differences to the Java module

      @@ -190,6 +201,20 @@ csattributes C# attributes for attaching to proxy classes/enums

    • +
    • +

      Additional typemap attributes:

      + +

      +The "null" attribute in the "out" typemap can be specified to provide a value for $null to expand into for wrapped functions that return non-void. Normally the default value of 0 is used. +For example this is needed if you change the return type to void: +

      +
      +%typemap(ctype) Status "void"
      +%typemap(out, null="") Status { ... }
      +
      + +
    • +
    • Feature equivalent names:

      @@ -227,10 +252,12 @@ $jnicall                    -> $imcall
       

      Unlike the "javain" typemap, the "csin" typemap does not support the 'pgcpp' attribute as the C# module does not have a premature garbage collection prevention parameter. The "csin" typemap supports additional optional attributes called 'cshin' and 'terminator'. +The "csdirectorin" typemap supports additional optional attributes called 'terminator'. The 'cshin' attribute should contain the parameter type and name whenever a constructor helper function is generated due to the 'pre' or 'post' attributes. The 'terminator' attribute normally just contains a closing brace for when the 'pre' attribute contains an opening brace, such as when a C# using or fixed block is started. Note that 'pre', 'post', 'terminator' and 'cshin' attributes are not used for marshalling the property set. Please see the Date marshalling example and Date marshalling of properties example for further understanding of these "csin" applicable attributes. +Please see the Date marshalling director example for further understanding of the "csdirectorin" attributes.

    • @@ -245,7 +272,7 @@ An example shows that char * could be marshalled in different ways,
      -%typemap(imtype, out="IntPtr") char * "string"
      +%typemap(imtype, out="global::System.IntPtr") char * "string"
       char * function(char *);
       
      @@ -256,7 +283,7 @@ The output type is thus IntPtr and the input type is string. The resulting inter
      -public static extern IntPtr function(string jarg1);
      +public static extern global::System.IntPtr function(string jarg1);
       
      @@ -277,8 +304,8 @@ For example:
       %typemap(imtype,
      -         inattributes="[MarshalAs(UnmanagedType.LPStr)]",
      -         outattributes="[return: MarshalAs(UnmanagedType.LPStr)]") const char * "String"
      +         inattributes="[global::System.Runtime.InteropServices.MarshalAs(UnmanagedType.LPStr)]",
      +         outattributes="[return: global::System.Runtime.InteropServices.MarshalAs(UnmanagedType.LPStr)]") const char * "String"
       
       const char * GetMsg() {}
       void SetMsg(const char *msg) {}
      @@ -293,12 +320,12 @@ The intermediary class will then have the marshalling as specified by everything
       
       class examplePINVOKE {
         ...
      -  [DllImport("example", EntryPoint="CSharp_GetMsg")]
      -  [return: MarshalAs(UnmanagedType.LPStr)]
      +  [global::System.Runtime.InteropServices.DllImport("example", EntryPoint="CSharp_GetMsg")]
      +  [return: global::System.Runtime.InteropServices.MarshalAs(UnmanagedType.LPStr)]
         public static extern String GetMsg();
       
      -  [DllImport("example", EntryPoint="CSharp_SetMsg")]
      -  public static extern void SetMsg([MarshalAs(UnmanagedType.LPStr)]String jarg1);
      +  [global::System.Runtime.InteropServices.DllImport("example", EntryPoint="CSharp_SetMsg")]
      +  public static extern void SetMsg([global::System.Runtime.InteropServices.MarshalAs(UnmanagedType.LPStr)]String jarg1);
       }
       
      @@ -351,7 +378,7 @@ will generate a C# proxy class:
       [ThreadSafe]
      -public class AClass : IDisposable {
      +public class AClass : global::System.IDisposable {
         ...
         [ThreadSafe(false)]
         public AClass(double a) ...
      @@ -375,9 +402,9 @@ An example for attaching attributes to the enum and enum values is shown below.
       
       
      -%typemap(csattributes) Couleur "[System.ComponentModel.Description(\"Colours\")]"
      -%csattributes Rouge "[System.ComponentModel.Description(\"Red\")]"
      -%csattributes Vert "[System.ComponentModel.Description(\"Green\")]"
      +%typemap(csattributes) Couleur "[global::System.ComponentModel.Description(\"Colours\")]"
      +%csattributes Rouge "[global::System.ComponentModel.Description(\"Red\")]"
      +%csattributes Vert "[global::System.ComponentModel.Description(\"Green\")]"
       %inline %{
         enum Couleur { Rouge, Orange, Vert };
       %}
      @@ -390,12 +417,12 @@ which will result in the following C# enum:
       
       
      -[System.ComponentModel.Description("Colours")]
      +[global::System.ComponentModel.Description("Colours")]
       public enum Couleur {
      -  [System.ComponentModel.Description("Red")]
      +  [global::System.ComponentModel.Description("Red")]
         Rouge,
         Orange,
      -  [System.ComponentModel.Description("Green")]
      +  [global::System.ComponentModel.Description("Green")]
         Vert
       }
       
      @@ -465,7 +492,7 @@ Windows users can also get the examples working using a Cygwin or MinGW environment for automatic configuration of the example makefiles. Any one of the three C# compilers (Portable.NET, Mono or Microsoft) can be detected from within a Cygwin or Mingw environment if installed in your path. -

      19.3 Void pointers

      +

      20.3 Void pointers

      @@ -483,7 +510,7 @@ void * f(void *v);

      -

      19.4 C# Arrays

      +

      20.4 C# Arrays

      @@ -495,7 +522,7 @@ with one of the following three approaches; namely the SWIG C arrays library, P/ pinned arrays.

      -

      19.4.1 The SWIG C arrays library

      +

      20.4.1 The SWIG C arrays library

      @@ -532,7 +559,7 @@ example.print_array(c.cast()); // Pass to C

      -

      19.4.2 Managed arrays using P/Invoke default array marshalling

      +

      20.4.2 Managed arrays using P/Invoke default array marshalling

      @@ -601,9 +628,9 @@ 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,
      +[global::System.Runtime.InteropServices.DllImport("example", EntryPoint="CSharp_myArrayCopy")]
      +public static extern void myArrayCopy([global::System.Runtime.InteropServices.In, global::System.Runtime.InteropServices.MarshalAs(UnmanagedType.LPArray)]int[] jarg1, 
      +                                      [global::System.Runtime.InteropServices.Out, global::System.Runtime.InteropServices.MarshalAs(UnmanagedType.LPArray)]int[] jarg2,
                                              int jarg3);
       
      @@ -651,15 +678,15 @@ and intermediary class method
      -  [DllImport("example", EntryPoint="CSharp_myArraySwap")]
      -  public static extern void myArraySwap([In, Out, MarshalAs(UnmanagedType.LPArray)]int[] jarg1, 
      -                                        [In, Out, MarshalAs(UnmanagedType.LPArray)]int[] jarg2,
      +  [global::System.Runtime.InteropServices.DllImport("example", EntryPoint="CSharp_myArraySwap")]
      +  public static extern void myArraySwap([global::System.Runtime.InteropServices.In, global::System.Runtime.InteropServices.Out, global::System.Runtime.InteropServices.MarshalAs(UnmanagedType.LPArray)]int[] jarg1, 
      +                                        [global::System.Runtime.InteropServices.In, global::System.Runtime.InteropServices.Out, global::System.Runtime.InteropServices.MarshalAs(UnmanagedType.LPArray)]int[] jarg2,
                                                int jarg3);
       
      -

      19.4.3 Managed arrays using pinning

      +

      20.4.3 Managed arrays using pinning

      @@ -726,7 +753,7 @@ As a result, we get the following method in the module class: fixed ( int *swig_ptrTo_sourceArray = sourceArray ) { fixed ( int *swig_ptrTo_targetArray = targetArray ) { { - examplePINVOKE.myArrayCopy((IntPtr)swig_ptrTo_sourceArray, (IntPtr)swig_ptrTo_targetArray, + examplePINVOKE.myArrayCopy((global::System.IntPtr)swig_ptrTo_sourceArray, (global::System.IntPtr)swig_ptrTo_targetArray, nitems); } } @@ -747,14 +774,14 @@ example - the method is expecting an IntPtr as the parameter type.

      -[DllImport("example", EntryPoint="CSharp_myArrayCopy")]
      -public static extern void myArrayCopy(IntPtr jarg1, IntPtr jarg2, int jarg3);
      +[global::System.Runtime.InteropServices.DllImport("example", EntryPoint="CSharp_myArrayCopy")]
      +public static extern void myArrayCopy(global::System.IntPtr jarg1, global::System.IntPtr jarg2, int jarg3);
       
      -

      19.5 C# Exceptions

      +

      20.5 C# Exceptions

      @@ -851,11 +878,11 @@ set so should only be used when a C# exception is not created.

      -

      19.5.1 C# exception example using "check" typemap

      +

      20.5.1 C# exception example using "check" typemap

      -Lets say we have the following simple C++ method: +Let's say we have the following simple C++ method:

      @@ -1033,7 +1060,7 @@ method and C# code does not handle pending exceptions via the canthrow attribute Actually it will issue this warning for any function beginning with SWIG_CSharpSetPendingException.

      -

      19.5.2 C# exception example using %exception

      +

      20.5.2 C# exception example using %exception

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

    -

    19.5.3 C# exception example using exception specifications

    +

    20.5.3 C# exception example using exception specifications

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

    -

    19.5.4 Custom C# ApplicationException example

    +

    20.5.4 Custom C# ApplicationException example

    @@ -1203,7 +1230,7 @@ the C# code can be generated into the intermediary class using the imclassco static CustomExceptionDelegate customDelegate = new CustomExceptionDelegate(SetPendingCustomException); - [DllImport("$dllimport", EntryPoint="CustomExceptionRegisterCallback")] + [global::System.Runtime.InteropServices.DllImport("$dllimport", EntryPoint="CustomExceptionRegisterCallback")] public static extern void CustomExceptionRegisterCallback(CustomExceptionDelegate customCallback); @@ -1247,7 +1274,7 @@ The boiler plate code above must be used in addition to a handcrafted Custom

     // Custom C# Exception
    -class CustomApplicationException : System.ApplicationException {
    +class CustomApplicationException : global::System.ApplicationException {
       public CustomApplicationException(string message) 
         : base(message) {
       }
    @@ -1289,7 +1316,7 @@ try {
     
    -

    19.6 C# Directors

    +

    20.6 C# Directors

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

    -

    19.6.1 Directors example

    +

    20.6.1 Directors example

    @@ -1423,7 +1450,7 @@ CSharpDerived - UIntMethod(123) -

    19.6.2 Directors implementation

    +

    20.6.2 Directors implementation

    @@ -1440,20 +1467,17 @@ Below is the generated C# Base director class.

    -using System;
    -using System.Runtime.InteropServices;
    -
    -public class Base : IDisposable {
    -  private HandleRef swigCPtr;
    +public class Base : global::System.IDisposable {
    +  private global::System.Runtime.InteropServices.HandleRef swigCPtr;
       protected bool swigCMemOwn;
     
    -  internal Base(IntPtr cPtr, bool cMemoryOwn) {
    +  internal Base(global::System.IntPtr cPtr, bool cMemoryOwn) {
         swigCMemOwn = cMemoryOwn;
    -    swigCPtr = new HandleRef(this, cPtr);
    +    swigCPtr = new global::System.Runtime.InteropServices.HandleRef(this, cPtr);
       }
     
    -  internal static HandleRef getCPtr(Base obj) {
    -    return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr;
    +  internal static global::System.Runtime.InteropServices.HandleRef getCPtr(Base obj) {
    +    return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr;
       }
     
       ~Base() {
    @@ -1462,12 +1486,12 @@ public class Base : IDisposable {
     
       public virtual void Dispose() {
         lock(this) {
    -      if(swigCPtr.Handle != IntPtr.Zero && swigCMemOwn) {
    +      if(swigCPtr.Handle != global::System.IntPtr.Zero && swigCMemOwn) {
             swigCMemOwn = false;
             examplePINVOKE.delete_Base(swigCPtr);
           }
    -      swigCPtr = new HandleRef(null, IntPtr.Zero);
    -      GC.SuppressFinalize(this);
    +      swigCPtr = new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero);
    +      global::System.GC.SuppressFinalize(this);
         }
       }
     
    @@ -1494,7 +1518,7 @@ public class Base : IDisposable {
         examplePINVOKE.Base_director_connect(swigCPtr, swigDelegate0, swigDelegate1);
       }
     
    -  private bool SwigDerivedClassHasMethod(string methodName, Type[] methodTypes) {
    +  private bool SwigDerivedClassHasMethod(string methodName, global::System.global::System.Type[] methodTypes) {
         System.Reflection.MethodInfo methodInfo = this.GetType().GetMethod(methodName, methodTypes);
         bool hasDerivedMethod = methodInfo.DeclaringType.IsSubclassOf(typeof(Base));
         return hasDerivedMethod;
    @@ -1504,18 +1528,18 @@ public class Base : IDisposable {
         return UIntMethod(x);
       }
     
    -  private void SwigDirectorBaseBoolMethod(IntPtr b, bool flag) {
    +  private void SwigDirectorBaseBoolMethod(global::System.IntPtr b, bool flag) {
         BaseBoolMethod(new Base(b, false), flag);
       }
     
       internal delegate uint SwigDelegateBase_0(uint x);
    -  internal delegate void SwigDelegateBase_1(IntPtr b, bool flag);
    +  internal delegate void SwigDelegateBase_1(global::System.IntPtr b, bool flag);
     
       private SwigDelegateBase_0 swigDelegate0;
       private SwigDelegateBase_1 swigDelegate1;
     
    -  private static Type[] swigMethodTypes0 = new Type[] { typeof(uint) };
    -  private static Type[] swigMethodTypes1 = new Type[] { typeof(Base), typeof(bool) };
    +  private static global::System.Type[] swigMethodTypes0 = new global::System.Type[] { typeof(uint) };
    +  private static global::System.Type[] swigMethodTypes1 = new global::System.Type[] { typeof(Base), typeof(bool) };
     }
     
    @@ -1609,7 +1633,7 @@ void SwigDirector_Base::BaseBoolMethod(Base const &b, bool flag) { -

    19.6.3 Director caveats

    +

    20.6.3 Director caveats

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

    -

    19.7 Multiples modules

    +

    20.7 Multiples modules

    @@ -1692,7 +1716,7 @@ the [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrows if you don't want users to easily stumble upon these so called 'internal workings' of the wrappers.

    -

    19.8 C# Typemap examples

    +

    20.8 C# Typemap examples

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

    19.8.1 Memory management when returning references to member variables

    +

    20.8.1 Memory management when returning references to member variables

    @@ -1738,9 +1762,9 @@ and the following usage from C# after running the code through SWIG: Wheel wheel = new Bike(10).getWheel(); Console.WriteLine("wheel size: " + wheel.size); // Simulate a garbage collection - System.GC.Collect(); - System.GC.WaitForPendingFinalizers(); - Console.WriteLine("wheel size: " + wheel.size); + global::System.GC.Collect(); + global::System.GC.WaitForPendingFinalizers(); + global::System.Console.WriteLine("wheel size: " + wheel.size); @@ -1778,9 +1802,9 @@ is called using the following typemaps. // of dangling C++ pointer. Intended for methods that return pointers or // references to a member variable. %typemap(csout, excode=SWIGEXCODE) Wheel& getWheel { - IntPtr cPtr = $imcall;$excode + global::System.IntPtr cPtr = $imcall;$excode $csclassname ret = null; - if (cPtr != IntPtr.Zero) { + if (cPtr != global::System.IntPtr.Zero) { ret = new $csclassname(cPtr, $owner); ret.addReference(this); } @@ -1796,7 +1820,7 @@ The code in the second typemap constitutes the bulk of the code in the generated

    -public class Wheel : IDisposable {
    +public class Wheel : global::System.IDisposable {
       ...
       // Ensure that the GC doesn't collect any Bike instance set from C#
       private Bike bikeReference;
    @@ -1805,12 +1829,12 @@ public class Wheel : IDisposable {
       }
     }
     
    -public class Bike : IDisposable {
    +public class Bike : global::System.IDisposable {
       ...
       public Wheel getWheel() {
    -    IntPtr cPtr = examplePINVOKE.Bike_getWheel(swigCPtr);
    +    global::System.IntPtr cPtr = examplePINVOKE.Bike_getWheel(swigCPtr);
         Wheel ret = null;
    -    if (cPtr != IntPtr.Zero) {
    +    if (cPtr != global::System.IntPtr.Zero) {
           ret = new Wheel(cPtr, false);
           ret.addReference(this);
         }
    @@ -1824,7 +1848,7 @@ public class Bike : IDisposable {
     Note the addReference call.
     

    -

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

    +

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

    @@ -1887,9 +1911,9 @@ In order to understand why, consider a garbage collection occuring... container.setElement(element); Console.WriteLine("element.value: " + container.getElement().value); // Simulate a garbage collection - System.GC.Collect(); - System.GC.WaitForPendingFinalizers(); - Console.WriteLine("element.value: " + container.getElement().value); + global::System.GC.Collect(); + global::System.GC.WaitForPendingFinalizers(); + global::System.Console.WriteLine("element.value: " + container.getElement().value);

    @@ -1901,14 +1925,14 @@ One solution is to add in the appropriate references in the C# layer...
    -public class Container : IDisposable {
    +public class Container : global::System.IDisposable {
     
       ...
     
       // Ensure that the GC doesn't collect any Element set from C#
       // as the underlying C++ class stores a shallow copy
       private Element elementReference;
    -  private HandleRef getCPtrAndAddReference(Element element) {
    +  private global::System.Runtime.InteropServices.HandleRef getCPtrAndAddReference(Element element) {
         elementReference = element;
         return Element.getCPtr(element);
       }
    @@ -1934,7 +1958,7 @@ The 'cscode' typemap simply adds in the specified code into the C# proxy class.
       // Ensure that the GC doesn't collect any Element set from C#
       // as the underlying C++ class stores a shallow copy
       private Element elementReference;
    -  private HandleRef getCPtrAndAddReference(Element element) {
    +  private global::System.Runtime.InteropServices.HandleRef getCPtrAndAddReference(Element element) {
         elementReference = element;
         return Element.getCPtr(element);
       }
    @@ -1943,7 +1967,7 @@ The 'cscode' typemap simply adds in the specified code into the C# proxy class.
     
    -

    19.8.3 Date marshalling using the csin typemap and associated attributes

    +

    20.8.3 Date marshalling using the csin typemap and associated attributes

    @@ -1983,7 +2007,7 @@ First let's look at the code that is generated by default, where the C# proxy cl

    -public class Action : IDisposable {
    +public class Action : global::System.IDisposable {
       ...
       public Action(CDate dateIn, CDate dateOut) 
           : this(examplePINVOKE.new_Action(CDate.getCPtr(dateIn), CDate.getCPtr(dateOut)), true) {
    @@ -2040,13 +2064,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(),"
    @@ -2064,7 +2088,7 @@ The resulting generated proxy code in the Action class follows:
     
     
    -public class Action : IDisposable {
    +public class Action : global::System.IDisposable {
       ...
       public int doSomething(System.DateTime dateIn, out System.DateTime dateOut) {
         CDate tempdateIn = new CDate(dateIn.Year, dateIn.Month, dateIn.Day);
    @@ -2082,7 +2106,7 @@ public class Action : IDisposable {
         }
       }
     
    -  static private IntPtr SwigConstructAction(System.DateTime dateIn, out System.DateTime dateOut) {
    +  static private global::System.IntPtr SwigConstructAction(System.DateTime dateIn, out System.DateTime dateOut) {
         CDate tempdateIn = new CDate(dateIn.Year, dateIn.Month, dateIn.Day);
         CDate tempdateOut = new CDate();
         try {
    @@ -2229,7 +2253,7 @@ public class example {
     
    -

    19.8.4 A date example demonstrating marshalling of C# properties

    +

    20.8.4 A date example demonstrating marshalling of C# properties

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

    @@ -2282,8 +2306,8 @@ The typemap type required is thus CDate *. Given that the previous sect %typemap(csvarout, excode=SWIGEXCODE2) CDate * %{ /* csvarout typemap code */ get { - IntPtr cPtr = $imcall; - CDate tempDate = (cPtr == IntPtr.Zero) ? null : new CDate(cPtr, $owner);$excode + global::System.IntPtr cPtr = $imcall; + CDate tempDate = (cPtr == global::System.IntPtr.Zero) ? null : new CDate(cPtr, $owner);$excode return new System.DateTime(tempDate.getYear(), tempDate.getMonth(), tempDate.getDay(), 0, 0, 0); } %} @@ -2305,8 +2329,8 @@ public class example { } /* csvarout typemap code */ get { - IntPtr cPtr = examplePINVOKE.ImportantDate_get(); - CDate tempDate = (cPtr == IntPtr.Zero) ? null : new CDate(cPtr, false); + global::System.IntPtr cPtr = examplePINVOKE.ImportantDate_get(); + CDate tempDate = (cPtr == global::System.IntPtr.Zero) ? null : new CDate(cPtr, false); return new System.DateTime(tempDate.getYear(), tempDate.getMonth(), tempDate.getDay(), 0, 0, 0); } @@ -2329,8 +2353,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. +

    20.8.5 Date example demonstrating the 'pre' and 'post' typemap attributes for directors

    -

    19.8.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(global::System.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. +

    + + +

    20.8.6 Turning wrapped classes into partial classes

    @@ -2354,7 +2439,7 @@ The default C# proxy class generated is:

    -public class ExtendMe : IDisposable {
    +public class ExtendMe : global::System.IDisposable {
       ...
       public int Part1() {
         ...
    @@ -2390,7 +2475,7 @@ The C# proxy class becomes a partial class:
     
     
    -public partial class ExtendMe : IDisposable {
    +public partial class ExtendMe : global::System.IDisposable {
       ...
       public int Part1() {
         ...
    @@ -2405,7 +2490,7 @@ You can then of course declare another part of the partial class elsewhere, for
     
     
    -public partial class ExtendMe : IDisposable {
    +public partial class ExtendMe : global::System.IDisposable {
       public int Part2() {
         return 2;
       }
    @@ -2430,7 +2515,7 @@ demonstrating that the class contains methods calling both unmanaged code - 
     The following example is an alternative approach to adding managed code to the generated proxy class.
     

    -

    19.8.6 Extending proxy classes with additional C# code

    +

    20.8.7 Extending proxy classes with additional C# code

    @@ -2457,7 +2542,7 @@ The generated C# proxy class will instead be:

    -public class ExtendMe : IDisposable {
    +public class ExtendMe : global::System.IDisposable {
       ...
       public int Part3() {
         return 3;
    @@ -2469,7 +2554,7 @@ public class ExtendMe : IDisposable {
     
    -

    19.8.7 Underlying type for enums

    +

    20.8.8 Underlying type for enums

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

    20 SWIG and Chicken

    +

    21 SWIG and Chicken

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

      -

      20.1 Preliminaries

      +

      21.1 Preliminaries

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

      -

      20.1.1 Running SWIG in C mode

      +

      21.1.1 Running SWIG in C mode

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

      -

      20.1.2 Running SWIG in C++ mode

      +

      21.1.2 Running SWIG in C++ mode

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

      -

      20.2 Code Generation

      +

      21.2 Code Generation

      -

      20.2.1 Naming Conventions

      +

      21.2.1 Naming Conventions

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

      -

      20.2.2 Modules

      +

      21.2.2 Modules

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

      -

      20.2.3 Constants and Variables

      +

      21.2.3 Constants and Variables

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

      -

      20.2.4 Functions

      +

      21.2.4 Functions

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

      -

      20.2.5 Exceptions

      +

      21.2.5 Exceptions

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

    -

    20.3 TinyCLOS

    +

    21.3 TinyCLOS

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

    -

    20.4 Linkage

    +

    21.4 Linkage

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

    -

    20.4.1 Static binary or shared library linked at compile time

    +

    21.4.1 Static binary or shared library linked at compile time

    We can easily use csc to build a static binary.

    @@ -395,7 +395,7 @@ in which case the test script does not need to be linked with example.so. The t be run with csi.

    -

    20.4.2 Building chicken extension libraries

    +

    21.4.2 Building chicken extension libraries

    Building a shared library like in the above section only works if the library @@ -453,7 +453,7 @@ distributed and used by anyone, even if SWIG is not installed.

    See the Examples/chicken/egg directory in the SWIG source for an example that builds two eggs, one using the first method and one using the second method.

    -

    20.4.3 Linking multiple SWIG modules with TinyCLOS

    +

    21.4.3 Linking multiple SWIG modules with TinyCLOS

    Linking together multiple modules that share type information using the %import @@ -477,7 +477,7 @@ with (declare (uses ...)). To create an extension library or an egg, just create a module_load.scm file that (declare (uses ...)) all the modules.

    -

    20.5 Typemaps

    +

    21.5 Typemaps

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

    Lib/chicken/chicken.swg.

    -

    20.6 Pointers

    +

    21.6 Pointers

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

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

    -

    20.6.1 Garbage collection

    +

    21.6.1 Garbage collection

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

    must be called manually.

    -

    20.7 Unsupported features and known problems

    +

    21.7 Unsupported features and known problems

    -

    20.7.1 TinyCLOS problems with Chicken version <= 1.92

    +

    21.7.1 TinyCLOS problems with Chicken version <= 1.92

    In Chicken versions equal to or below 1.92, TinyCLOS has a limitation such that generic methods do not properly work on methods diff --git a/Doc/Manual/Contents.html b/Doc/Manual/Contents.html index 137c746ab..582f7eb05 100644 --- a/Doc/Manual/Contents.html +++ b/Doc/Manual/Contents.html @@ -16,13 +16,23 @@

    @@ -252,7 +262,61 @@
    -

    7 Preprocessing

    +

    7 SWIG and C++11

    + + + + + +

    8 Preprocessing

    @@ -275,7 +339,7 @@
    -

    8 SWIG library

    +

    9 SWIG library

    @@ -301,6 +365,7 @@
  • std::vector
  • STL exceptions
  • shared_ptr smart pointer +
  • auto_ptr smart pointer
  • Utility Libraries
      @@ -310,7 +375,7 @@
  • -

    9 Argument Handling

    +

    10 Argument Handling

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

    10 Typemaps

    +

    11 Typemaps

    @@ -421,7 +486,7 @@
    -

    11 Customization Features

    +

    12 Customization Features

    @@ -449,7 +514,7 @@
    -

    12 Contracts

    +

    13 Contracts

    @@ -462,7 +527,7 @@
    -

    13 Variable Length Arguments

    +

    14 Variable Length Arguments

    @@ -480,7 +545,7 @@
    -

    14 Warning Messages

    +

    15 Warning Messages

    @@ -508,7 +573,7 @@
    -

    15 Working with Modules

    +

    16 Working with Modules

    @@ -524,7 +589,33 @@
    -

    17 SWIG and Allegro Common Lisp

    +

    17 Using SWIG with ccache - ccache-swig(1) manpage

    + + + + + +

    18 SWIG and Allegro Common Lisp

    @@ -608,7 +699,7 @@
    -

    18 SWIG and Android

    +

    19 SWIG and Android

    -

    19 SWIG and C#

    +

    20 SWIG and C#

    -

    20 SWIG and Chicken

    +

    21 SWIG and Chicken

    @@ -704,7 +801,7 @@
    -

    21 SWIG and D

    +

    22 SWIG and D

    @@ -738,7 +835,7 @@
    -

    22 SWIG and Go

    +

    23 SWIG and Go

    @@ -769,13 +866,14 @@
    -

    23 SWIG and Guile

    +

    24 SWIG and Guile

    -

    24 SWIG and Java

    +

    25 SWIG and Java

    -

    25 SWIG and Common Lisp

    +

    26 SWIG and Common Lisp

    @@ -970,7 +1069,7 @@
    -

    26 SWIG and Lua

    +

    27 SWIG and Lua

    -

    27 SWIG and Modula-3

    +

    28 SWIG and Modula-3

    @@ -1067,7 +1175,7 @@
    -

    28 SWIG and MzScheme/Racket

    +

    29 SWIG and MzScheme/Racket

    @@ -1079,7 +1187,7 @@
    -

    29 SWIG and Ocaml

    +

    30 SWIG and Ocaml

    @@ -1130,7 +1238,7 @@
    -

    30 SWIG and Octave

    +

    31 SWIG and Octave

    @@ -1166,7 +1274,7 @@
    -

    31 SWIG and Perl5

    +

    32 SWIG and Perl5

    -

    32 SWIG and PHP

    +

    33 SWIG and PHP

    @@ -1273,7 +1390,7 @@
    -

    33 SWIG and Pike

    +

    34 SWIG and Pike

    @@ -1297,7 +1414,7 @@
    -

    34 SWIG and Python

    +

    35 SWIG and Python

    -

    35 SWIG and R

    +

    36 SWIG and R

    @@ -1423,7 +1546,7 @@
    -

    36 SWIG and Ruby

    +

    37 SWIG and Ruby

    -

    37 SWIG and Tcl

    +

    38 SWIG and Tcl

    @@ -1623,7 +1746,7 @@
    -

    38 Extending SWIG to support new languages

    +

    39 Extending SWIG to support new languages

    @@ -1691,7 +1814,7 @@
    -

    39 SWIG and Doxygen Translation

    +

    40 SWIG and Doxygen Translation

    diff --git a/Doc/Manual/Contract.html b/Doc/Manual/Contract.html index de390fba4..35bc874ef 100644 --- a/Doc/Manual/Contract.html +++ b/Doc/Manual/Contract.html @@ -6,7 +6,7 @@ -

    12 Contracts

    +

    13 Contracts

      @@ -38,7 +38,7 @@ When one of the rules is violated by a script, a runtime exception is generated rather than having the program continue to execute.

      -

      12.1 The %contract directive

      +

      13.1 The %contract directive

      @@ -94,7 +94,7 @@ RuntimeError: Contract violation: require: (arg1>=0)

    -

    12.2 %contract and classes

    +

    13.2 %contract and classes

    @@ -173,7 +173,7 @@ specified for the derived class all must hold. In the above example, this means that both the arguments to Spam::bar must be positive.

    -

    12.3 Constant aggregation and %aggregate_check

    +

    13.3 Constant aggregation and %aggregate_check

    @@ -262,7 +262,7 @@ Regrettably, there is no automatic way to perform similar checks with enums valu release.

    -

    12.4 Notes

    +

    13.4 Notes

    diff --git a/Doc/Manual/Customization.html b/Doc/Manual/Customization.html index b98fbfc88..a0a89c042 100644 --- a/Doc/Manual/Customization.html +++ b/Doc/Manual/Customization.html @@ -6,7 +6,7 @@ -

    11 Customization Features

    +

    12 Customization Features

      @@ -45,7 +45,7 @@ of exception handling is presented. Then, a more general-purpose customization mechanism known as "features" is described.

      -

      11.1 Exception handling with %exception

      +

      12.1 Exception handling with %exception

      @@ -100,7 +100,7 @@ for exception handling. That directive is deprecated--%exception provides the same functionality, but is substantially more flexible.

      -

      11.1.1 Handling exceptions in C code

      +

      12.1.1 Handling exceptions in C code

      @@ -166,7 +166,7 @@ Each target language has its own approach to creating a runtime error/exception and for Perl it is the croak method shown above.

      -

      11.1.2 Exception handling with longjmp()

      +

      12.1.2 Exception handling with longjmp()

      @@ -240,7 +240,7 @@ Note: This implementation is only intended to illustrate the general idea. To m modify it to handle nested try declarations.

      -

      11.1.3 Handling C++ exceptions

      +

      12.1.3 Handling C++ exceptions

      @@ -275,7 +275,7 @@ class OutOfMemory {};

    -

    11.1.4 Exception handlers for variables

    +

    12.1.4 Exception handlers for variables

    @@ -300,7 +300,7 @@ The %allowexception feature works like any other feature and so can be -

    11.1.5 Defining different exception handlers

    +

    12.1.5 Defining different exception handlers

    @@ -437,7 +437,7 @@ declarations. However, it never really worked that well and the new %exception directive is much better.

    -

    11.1.6 Special variables for %exception

    +

    12.1.6 Special variables for %exception

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

    @@ -525,7 +540,7 @@ Below shows the expansions for the 1st of the overloaded something wrap -

    11.1.7 Using The SWIG exception library

    +

    12.1.7 Using The SWIG exception library

    @@ -577,12 +592,10 @@ SWIG_NullReferenceError

    -Since the SWIG_exception() function is defined at the C-level -it can be used elsewhere in SWIG. This includes typemaps and helper -functions. +The SWIG_exception() function can also be used in typemaps.

    -

    11.2 Object ownership and %newobject

    +

    12.2 Object ownership and %newobject

    @@ -739,7 +752,7 @@ char *strdup(const char *s); The results might not be what you expect.

    -

    11.3 Features and the %feature directive

    +

    12.3 Features and the %feature directive

    @@ -821,7 +834,7 @@ The following are all equivalent: The syntax in the first variation will generate the { } delimiters used whereas the other variations will not.

    -

    11.3.1 Feature attributes

    +

    12.3.1 Feature attributes

    @@ -862,7 +875,7 @@ In the following example, MyExceptionClass is the name of the Java clas Further details can be obtained from the Java exception handling section.

    -

    11.3.2 Feature flags

    +

    12.3.2 Feature flags

    @@ -960,7 +973,7 @@ in the swig.swg Library file. The following shows the alternative synta The concept of clearing features is discussed next.

    -

    11.3.3 Clearing features

    +

    12.3.3 Clearing features

    @@ -1053,7 +1066,7 @@ The three macros below show this for the "except" feature: -

    11.3.4 Features and default arguments

    +

    12.3.4 Features and default arguments

    @@ -1128,7 +1141,7 @@ specifying or not specifying default arguments in a feature is not applicable as in SWIG-1.3.23 when the approach to wrapping methods with default arguments was changed.

    -

    11.3.5 Feature example

    +

    12.3.5 Feature example

    diff --git a/Doc/Manual/D.html b/Doc/Manual/D.html index 43fa69196..47dab50f1 100644 --- a/Doc/Manual/D.html +++ b/Doc/Manual/D.html @@ -6,7 +6,7 @@ -

    21 SWIG and D

    +

    22 SWIG and D

      @@ -41,7 +41,7 @@ -

      21.1 Introduction

      +

      22.1 Introduction

      From the D Programming Language web site: D is a systems programming language. Its focus is on combining the power and high performance of C and C++ with the programmer productivity of modern languages like Ruby and Python. [...] The D language is statically typed and compiles directly to machine code. As such, it is not very surprising that D is able to directly interface with C libraries. Why would a SWIG module for D be needed then in the first place?

      @@ -53,7 +53,7 @@

      To help addressing these issues, the SWIG C# module has been forked to support D. Is has evolved quite a lot since then, but there are still many similarities, so if you do not find what you are looking for on this page, it might be worth having a look at the chapter on C# (and also on Java, since the C# module was in turn forked from it).

      -

      21.2 Command line invocation

      +

      22.2 Command line invocation

      To activate the D module, pass the -d option to SWIG at the command line. The same standard command line switches as with any other language module are available, plus the following D specific ones:

      @@ -83,10 +83,10 @@ -

      21.3 Typemaps

      +

      22.3 Typemaps

      -

      21.3.1 C# <-> D name comparison

      +

      22.3.1 C# <-> D name comparison

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

      @@ -112,7 +112,7 @@
    -

    21.3.2 ctype, imtype, dtype

    +

    22.3.2 ctype, imtype, dtype

    Mapping of types between the C/C++ library, the C/C++ library wrapper exposing the C functions, the D wrapper module importing these functions and the D proxy code.

    @@ -120,7 +120,7 @@

    The ctype typemap is used to determine the types to use in the C wrapper functions. The types from the imtype typemap are used in the extern(C) declarations of these functions in the intermediary D module. The dtype typemap contains the D types used in the D proxy module/class.

    -

    21.3.3 in, out, directorin, directorout

    +

    22.3.3 in, out, directorin, directorout

    Used for converting between the types for C/C++ and D when generating the code for the wrapper functions (on the C++ side).

    @@ -130,7 +130,7 @@

    The directorin typemap is used to convert parameters to the type used in the D director callback function, its return value is processed by directorout (see below).

    -

    21.3.4 din, dout, ddirectorin, ddirectorout

    +

    22.3.4 din, dout, ddirectorin, ddirectorout

    Typemaps for code generation in D proxy and type wrapper classes.

    @@ -157,13 +157,13 @@ dtype DClass.method(dtype a) -

    21.3.5 typecheck typemaps

    +

    22.3.5 typecheck typemaps

    Because, unlike many scripting languages supported by SWIG, D does not need any dynamic dispatch helper to access an overloaded function, the purpose of these is merely to issue a warning for overloaded C++ functions that cannot be overloaded in D (as more than one C++ type maps to a single D type).

    -

    21.3.6 Code injection typemaps

    +

    22.3.6 Code injection typemaps

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

    @@ -175,7 +175,7 @@

    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

    +

    22.3.7 Special variable macros

    The standard SWIG special variables are available for use within typemaps as described in the Typemaps documentation, for example $1, $input, $result etc.

    @@ -295,7 +295,7 @@ $importtype(AnotherInterface) -

    21.4 %features

    +

    22.4 %features

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

    @@ -325,7 +325,7 @@ struct A { -

    21.5 Pragmas

    +

    22.5 Pragmas

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

    @@ -364,7 +364,7 @@ struct A { -

    21.6 D Exceptions

    +

    22.6 D Exceptions

    Out of the box, C++ exceptions are fundamentally incompatible to their equivalent in the D world and cannot simply be propagated to a calling D method. There is, however, an easy way to solve this problem: Just catch the exception in the C/C++ wrapper layer, pass the contents to D, and make the wrapper code rethrow the exception in the D world.

    @@ -374,7 +374,7 @@ struct A {

    As this feature is implemented in exactly the same way it is for C#, please see the C# documentation for a more detailed explanation.

    -

    21.7 D Directors

    +

    22.7 D Directors

    When the directors feature is activated, SWIG generates extra code on both the C++ and the D side to enable cross-language polymorphism. Essentially, this means that if you subclass a proxy class in D, C++ code can access any overridden virtual methods just as if you created a derived class in C++.

    @@ -383,16 +383,16 @@ struct A {

    -

    21.8 Other features

    +

    22.8 Other features

    -

    21.8.1 Extended namespace support (nspace)

    +

    22.8.1 Extended namespace support (nspace)

    By default, SWIG flattens all C++ namespaces into a single target language namespace, but as for Java and C#, the nspace feature is supported for D. If it is active, C++ 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

    +

    22.8.2 Native pointer support

    Contrary to many of the scripting languages supported by SWIG, D fully supports C-style pointers. The D module thus includes a custom mechanism to wrap C pointers directly as D pointers where applicable, that is, if the type that is pointed to is represented the same in C and D (on the bit-level), dubbed a primitive type below.

    @@ -404,7 +404,7 @@ struct A {

    To determine if a type should be considered primitive, the cprimitive attribute on its dtype attribute is used. For example, the dtype typemap for float has cprimitive="1", so the code from the nativepointer attribute is taken into account e.g. for float ** or the function pointer float (*)(float *).

    -

    21.8.3 Operator overloading

    +

    22.8.3 Operator overloading

    The D module comes with basic operator overloading support for both D1 and D2. There are, however, a few limitations arising from conceptual differences between C++ and D:

    @@ -416,7 +416,7 @@ struct A {

    There are also some cases where the operators can be translated to D, but the differences in the implementation details are big enough that a rather involved scheme would be required for automatic wrapping them, which has not been implemented yet. This affects, for example, the array subscript operator, [], in combination with assignments - while operator [] in C++ simply returns a reference which is then written to, D resorts to a separate opIndexAssign method -, or implicit casting (which was introduced in D2 via alias this). Despite the lack of automatic support, manually handling these cases should be perfectly possible.

    -

    21.8.4 Running the test-suite

    +

    22.8.4 Running the test-suite

    As with any other language, the SWIG test-suite can be built for D using the *-d-test-suite targets of the top-level Makefile. By default, D1 is targeted, to build it with D2, use the optional D_VERSION variable, e.g. make check-d-test-suite D_VERSION=2.

    @@ -424,14 +424,14 @@ struct A {

    Note: If you want to use GDC on Linux or another platform which requires you to link libdl for dynamically loading the shared library, you might have to add -ldl manually to the d_compile target in Examples/Makefile, because GDC does not currently honor the pragma(lib,...) statement.

    -

    21.9 D Typemap examples

    +

    22.9 D Typemap examples

    There are no D-specific typemap examples yet. However, with the above name comparison table, you should be able to get an idea what can be done by looking at the corresponding C# section.

    -

    21.10 Work in progress and planned features

    +

    22.10 Work in progress and planned features

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

    diff --git a/Doc/Manual/Extending.html b/Doc/Manual/Extending.html index c3b2740f4..5c209bbb5 100644 --- a/Doc/Manual/Extending.html +++ b/Doc/Manual/Extending.html @@ -6,7 +6,7 @@ -

    38 Extending SWIG to support new languages

    +

    39 Extending SWIG to support new languages

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

      38.1 Introduction

      +

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

      -

      38.2 Prerequisites

      +

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

      -

      38.3 The Big Picture

      +

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

      -

      38.4 Execution Model

      +

      39.4 Execution Model

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

      -

      38.4.1 Preprocessing

      +

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

      -

      38.4.2 Parsing

      +

      39.4.2 Parsing

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

      -

      38.4.3 Parse Trees

      +

      39.4.3 Parse Trees

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

    -

    38.4.4 Attribute namespaces

    +

    39.4.4 Attribute namespaces

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

    -

    38.4.5 Symbol Tables

    +

    39.4.5 Symbol Tables

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

    38.4.6 The %feature directive

    +

    39.4.6 The %feature directive

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

    -

    38.4.7 Code Generation

    +

    39.4.7 Code Generation

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

    -

    38.4.8 SWIG and XML

    +

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

    -

    38.5 Primitive Data Structures

    +

    39.5 Primitive Data Structures

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

    38.5.1 Strings

    +

    39.5.1 Strings

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

    38.5.2 Hashes

    +

    39.5.2 Hashes

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

    38.5.3 Lists

    +

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

    38.5.4 Common operations

    +

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

    38.5.5 Iterating over Lists and Hashes

    +

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

    38.5.6 I/O

    +

    39.5.6 I/O

    Special I/O functions are used for all internal I/O. These operations @@ -1500,12 +1500,11 @@ Create a File object wrapper around an existing FILE * object.

    -int Close(String_or_FILE *f) +There's no explicit function to close a file, just call Delete(f) - +this decreases the reference count, and the file will be closed when the +reference count reaches zero.

    -
    -

    Closes a file. Has no effect on strings.

    -

    The use of the above I/O functions and strings play a critical role in SWIG. It is common to see small code fragments of code generated using code like this: @@ -1529,9 +1528,7 @@ Printf(f, "%s\n", s); Similarly, the preprocessor and parser all operate on string-files.

    -
    - -

    38.6 Navigating and manipulating parse trees

    +

    39.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 +1662,7 @@ Deletes a node from the parse tree. Deletion reconnects siblings and properly u the parent so that sibling nodes are unaffected. -

    38.7 Working with attributes

    +

    39.7 Working with attributes

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

    38.8 Type system

    +

    39.8 Type system

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

    -

    38.8.1 String encoding of types

    +

    39.8.1 String encoding of types

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

    -

    38.8.2 Type construction

    +

    39.8.2 Type construction

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

    38.8.3 Type tests

    +

    39.8.3 Type tests

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

    38.8.4 Typedef and inheritance

    +

    39.8.4 Typedef and inheritance

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

    38.8.5 Lvalues

    +

    39.8.5 Lvalues

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

    38.8.6 Output functions

    +

    39.8.6 Output functions

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

    38.9 Parameters

    +

    39.9 Parameters

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

    38.10 Writing a Language Module

    +

    39.10 Writing a Language Module

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

    -

    38.10.1 Execution model

    +

    39.10.1 Execution model

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

    -

    38.10.2 Starting out

    +

    39.10.2 Starting out

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

    -

    38.10.3 Command line options

    +

    39.10.3 Command line options

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

    -

    38.10.4 Configuration and preprocessing

    +

    39.10.4 Configuration and preprocessing

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

    -

    38.10.5 Entry point to code generation

    +

    39.10.5 Entry point to code generation

    @@ -2747,7 +2744,7 @@ int Python::top(Node *n) { -

    38.10.6 Module I/O and wrapper skeleton

    +

    39.10.6 Module I/O and wrapper skeleton

    @@ -2761,8 +2758,8 @@ Within SWIG wrappers, there are five main sections. These are (in order)
  • 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 +
  • wrapper: This section holds all the wrapper code. +
  • init: This section holds the module initialisation function (the entry point for the interpreter).

    @@ -2832,7 +2829,6 @@ int Python::top(Node *n) { Delete(f_header); Delete(f_wrappers); Delete(f_init); - Close(f_begin); Delete(f_begin); return SWIG_OK; @@ -2896,7 +2892,7 @@ functionWrapper : void Shape_y_set(Shape *self,double y) -

    38.10.7 Low-level code generators

    +

    39.10.7 Low-level code generators

    @@ -2975,7 +2971,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");
    @@ -3005,7 +3001,7 @@ virtual int functionWrapper(Node *n) {
       /* write typemaps(in) */
       ....
     
    -  /* write constriants */
    +  /* write constraints */
       ....
     
       /* Emit the function call */
    @@ -3050,7 +3046,7 @@ but without the typemaps, there is still work to do.
     

    -

    38.10.8 Configuration files

    +

    39.10.8 Configuration files

    @@ -3101,7 +3097,7 @@ As you can see, most usages are direct.
    -
    configure.in +
    configure.ac
    This file is processed by

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

    -

    38.10.9 Runtime support

    +

    39.10.9 Runtime support

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

    -

    38.10.10 Standard library files

    +

    39.10.10 Standard library files

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

    -

    38.10.11 User examples

    +

    39.10.11 User examples

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

    -

    38.10.12 Test driven development and the test-suite

    +

    39.10.12 Test driven development and the test-suite

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

    -

    38.10.12.1 Running the test-suite

    +

    39.10.12.1 Running the test-suite

    @@ -3350,10 +3346,10 @@ Note that if a runtime test is available, a message "(with run test)" is display

     $ make check-python-test-suite
     checking python test-suite
    -checking testcase argcargvtest (with run test) under python
    -checking testcase python_autodoc under python
    -checking testcase python_append (with run test) under python
    -checking testcase callback (with run test) under python
    +checking python testcase argcargvtest (with run test)
    +checking python testcase python_autodoc
    +checking python testcase python_append (with run test)
    +checking python testcase callback (with run test)
     

    @@ -3496,7 +3492,13 @@ The syntax for setting environment variables varies from one shell to the next, make ret_by_value.ctest SWIG_FEATURES="-debug-tmsearch"

    -

    38.10.13 Documentation

    +

    +There is also a special 'errors' test-suite which is a set of regression tests checking SWIG warning and error messages. +It can be run in the same way as the other language test-suites, replacing [lang] with errors, such as make check-errors-test-suite. +The test cases used and the way it works is described in Examples/test-suite/errors/Makefile.in. +

    + +

    39.10.13 Documentation

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

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

    +

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

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

    @@ -3551,7 +3553,7 @@ details being outlined earlier on. a runtime test, see for example Examples/python/class.
  • - Modify configure.in, Makefile.in and Examples/Makefile.in to run + Modify configure.ac, Makefile.in and Examples/Makefile.in to run these examples. Please make sure that if the new language is not installed properly on a box, make -k check should still work by skipping the tests and examples for the new language module. @@ -3578,14 +3580,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.

    -

    38.10.15 Coding style guidelines

    +

    39.10.15 Coding style guidelines

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

    -

    38.11 Debugging Options

    +

    39.11 Debugging Options

    @@ -3636,7 +3638,7 @@ There are various command line options which can aid debugging a SWIG interface The complete list of command line options for SWIG are available by running swig -help.

    -

    38.12 Guide to parse tree nodes

    +

    39.12 Guide to parse tree nodes

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

    38.13 Further Development Information

    +

    39.13 Further Development Information

    diff --git a/Doc/Manual/Go.html b/Doc/Manual/Go.html index 8abeada81..93b87a4a4 100644 --- a/Doc/Manual/Go.html +++ b/Doc/Manual/Go.html @@ -5,7 +5,7 @@ -

    22 SWIG and Go

    +

    23 SWIG and Go

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

      -

      22.1 Overview

      +

      23.1 Overview

      @@ -55,7 +55,7 @@ there is no convenient way to call C++ code. SWIG fills this gap.

      There are (at least) two different Go compilers. One is the gc -compiler, normally invoked under the names 6g, 8g, or 5g. The other +compiler, normally invoked via the go tool. The other is the gccgo compiler, which is a frontend to the gcc compiler suite. The interface to C/C++ code is completely different for the two Go compilers. SWIG supports both, selected by a command line option. @@ -67,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.

      -

      22.2 Running SWIG with Go

      +

      23.2 Running SWIG with Go

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

      -

      22.2.1 Additional Commandline Options

      +

      23.2.1 Additional Commandline Options

      -These are the command line options for SWIG's GO module. They can +These are the command line options for SWIG's Go module. They can also be seen by using:

      @@ -93,23 +93,22 @@ swig -go -help Go specific options + +-intgosize <s> +Set the size for the Go type int. This controls the size + that the C/C++ code expects to see. The <s> argument should + be 32 or 64. This option is currently required during the + transition from Go 1.0 to Go 1.1, as the size of int on + 64-bit x86 systems changes between those releases (from 32 bits to + 64 bits). In the future the option may become optional, and SWIG + will assume that the size of int is the size of a C + pointer. + + -gccgo Generate code for gccgo. The default is to generate code for - 6g/8g/5g. - - - --gccgo-46 -Generate code for gccgo 4.6. The default is set by the configure - script. This generates code that does not use some facilities - that are only available in gccgo 4.7 and later. - - - --no-gccgo-46 -Turn off -gccgo-46, whether set by default or earlier - on the command line. + the gc compiler. @@ -119,30 +118,39 @@ swig -go -help --soname %lt;name%gt; +-use-shlib +Tell SWIG to emit code that uses a shared library. This is only + meaningful for the gc compiler, which needs to know at compile time + whether a shared library will be used. + + + +-soname <name> Set the runtime name of the shared library that the dynamic linker should include at runtime. The default is the package name with ".so" appended. This is only used when generating code for - 6g/8g/5g; when using gccgo, the equivalent name will be taken from - the -soname option passed to the linker. + the gc compiler; when using gccgo, the equivalent name will be taken from + the -soname option passed to the linker. Using this + option implies the -use-shlib option. + + + +-go-pkgpath <pkgpath> +When generating code for gccgo, set the pkgpath to use. This + corresponds to the -fgo-pkgpath option to gccgo. -go-prefix <prefix> When generating code for gccgo, set the prefix to use. This - corresponds to the -fgo-prefix option to gccgo. - - - --long-type-size <s> -Set the size for the C/C++ type long. This controls - whether long is converted to the Go type int32 - or int64. The <s> argument should be 32 or 64. + corresponds to the -fgo-prefix option to gccgo. + If -go-pkgpath is used, -go-prefix will be + ignored. -

      22.2.2 Go Output Files

      +

      23.2.2 Go Output Files

      When generating Go code, SWIG will generate the following @@ -166,28 +174,59 @@ may be helpful to include it in your code, compiled with the usual C or C++ compiler.

    • If using the gc compiler, MODULE_gc.c will contain C code which should -be compiled with the C compiler distributed as part of the gc compiler: 6c, 8c, -or 5c. It should then be combined with the compiled MODULE.go using -gopack. This file will not be generated when using gccgo. +be compiled with the C compiler distributed as part of the gc +compiler. It should then be combined with the compiled MODULE.go +using gopack. This file will not be generated when using gccgo.

    -A typical command sequence would look like this: +Most Go programs are built using the go tool. The go tool has limited +support for SWIG. To use it, put your SWIG interface into a file with +the extension .swig, or, if you are wrapping C++ code, .swigcxx. Put +that file in a GOPATH/src directory as usual for Go sources. Put +other interface code in the same directory with extensions of .c and +.cxx. The go build command and go install commands will automatically +run SWIG for you and will build the interface code. +

    + +

    +You can also use SWIG directly yourself. When using the gc compiler +version 1.2 or later, or when using gccgo, the code generated by SWIG +can be linked directly into the Go program. A typical command +sequence when using the gc compiler would look like this:

     % swig -go example.i
    +% gcc -c code.c	   # The C library being wrapped.
    +% gcc -c example_wrap.c
    +% go tool 6g example.go
    +% go tool 6c example_gc.c
    +% go tool pack grc example.a example.6 example_gc.6 code.o example_wrap.o
    +% go tool 6g main.go
    +% go tool 6l main.6
    +
    + +

    +You can also put the wrapped code into a shared library, and when +using the gc compiler before version 1.2 this is the only supported +option. A typical command sequence for this approach would look like +this: +

    + +
    +% swig -go -use-shlib example.i
     % gcc -c -fpic example.c
     % gcc -c -fpic example_wrap.c
     % gcc -shared example.o example_wrap.o -o example.so
    -% 6g example.go
    -% 6c example_gc.c
    -% gopack grc example.a example.6 example_gc.6
    -% 6g main.go  # your code, not generated by SWIG
    -% 6l main.6
    +% go tool 6g example.go
    +% go tool 6c example_gc.c
    +% go tool pack grc example.a example.6 example_gc.6
    +% go tool 6g main.go  # your code, not generated by SWIG
    +% go tool 6l main.6
     
    -

    22.3 A tour of basic C/C++ wrapping

    +

    23.3 A tour of basic C/C++ wrapping

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

    -

    22.3.1 Go Package Name

    +

    23.3.1 Go Package Name

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

    -

    22.3.2 Go Names

    +

    23.3.2 Go Names

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

    -

    22.3.3 Go Constants

    +

    23.3.3 Go Constants

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

    22.3.4 Go Enumerations

    +

    23.3.4 Go Enumerations

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

    -

    22.3.5 Go Classes

    +

    23.3.5 Go Classes

    @@ -335,7 +374,7 @@ returns a go interface. If the returned pointer can be null, you can check for this by calling the Swigcptr() method.

    -

    22.3.5.1 Go Class Inheritance

    +

    23.3.5.1 Go Class Inheritance

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

    -

    22.3.6 Go Templates

    +

    23.3.6 Go Templates

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

    22.3.7 Go Director Classes

    +

    23.3.7 Go Director Classes

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

    -

    22.3.8 Default Go primitive type mappings

    +

    23.3.8 Default Go primitive type mappings

    @@ -455,12 +494,12 @@ uses a given C/C++ type. long -int32 or int64, depending on -long-type-size +int64 unsigned long -uint32 or uint64, depending on -long-type-size +uint64 @@ -505,13 +544,13 @@ that typemap, or add new values, to control how C/C++ types are mapped into Go types.

    -

    22.3.9 Output arguments

    +

    23.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 ouput value. In go, you supply a slice in the place of the output +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 @@ -558,7 +597,7 @@ void f(char *output);

    -

    22.3.10 Adding additional go code

    +

    23.3.10 Adding additional go code

    Often the APIs generated by swig are not very natural in go, especially if @@ -627,9 +666,31 @@ func (arg SwigcptrWrapped_MyClass) GetAValue() (int, bool) { few, then you might as well define your own struct that includes the swig-wrapped object, instead of adding methods to the swig-generated object.

    -

    This only works if your wrappers do not need to import other go modules. -There is at present no way to insert import statements in the correct place -in swig-generated go. If you need to do that, you must put your go code -in a separate file.

    +

    If you need to import other go packages, you can do this with +%go_import. For example,

    +
    +
    +%go_import("fmt", _ "unusedPackage", rp "renamed/package")
    +
    +%insert(go_wrapper) %{
    +
    +func foo() {
    +  fmt.Println("Some string:", rp.GetString())
    +}
    +
    +// Importing the same package twice is permitted,
    +// Go code will be generated with only the first instance of the import.
    +%go_import("fmt")
    +
    +%insert(go_wrapper) %{
    +
    +func bar() {
    +  fmt.Println("Hello world!")
    +}
    +
    +%}
    +
    +
    + diff --git a/Doc/Manual/Guile.html b/Doc/Manual/Guile.html index 6f1300492..4c1126c7f 100644 --- a/Doc/Manual/Guile.html +++ b/Doc/Manual/Guile.html @@ -8,12 +8,13 @@ -

    23 SWIG and Guile

    +

    24 SWIG and Guile

      +
    • Supported Guile Versions
    • Meaning of "Module" -
    • Using the SCM or GH Guile API +
    • Old GH Guile API
    • Linkage
      • Simple Linkage @@ -26,8 +27,7 @@
      • Typemaps
      • Representation of pointers as smobs
      • Exception Handling @@ -47,7 +47,21 @@

        This section details guile-specific support in SWIG. -

        23.1 Meaning of "Module"

        +

        24.1 Supported Guile Versions

        + + +

        +SWIG works with Guile versions 1.8.x and 2.0.x. Support for version +1.6.x has been dropped. The last version of SWIG that still works with +Guile version 1.6.x is SWIG 2.0.9. + +

        +Note that starting with guile 2.0, the guile sources can be compiled for +improved performance. This is currently not tested with swig +so your mileage may vary. To be safe set environment variable +GUILE_AUTO_COMPILE to 0 when using swig generated guile code. + +

        24.2 Meaning of "Module"

        @@ -55,55 +69,18 @@ There are three different concepts of "module" involved, defined separately for SWIG, Guile, and Libtool. To avoid horrible confusion, we explicitly prefix the context, e.g., "guile-module". -

        23.2 Using the SCM or GH Guile API

        +

        24.3 Old GH Guile API

        -

        The guile module can currently export wrapper files that use the guile GH interface or the -SCM interface. This is controlled by an argument passed to swig. The "-gh" argument causes swig -to output GH code, and the "-scm" argument causes swig to output SCM code. Right now the "-scm" argument -is the default. The "-scm" wrapper generation assumes a guile version >= 1.6 and has several advantages over -the "-gh" wrapper generation including garbage collection and GOOPS support. -The "-gh" wrapper generation can be used for older versions of guile. -The guile GH wrapper code generation is depreciated and the -SCM interface is the default. The SCM and GH interface differ greatly in how they store -pointers and have completely different run-time code. See below for more info. - -

        The GH interface to guile is deprecated. Read more about why in the +

        Guile 1.8 and older could be interfaced using two different api's, the SCM +or the GH API. The GH interface to guile is deprecated. Read more about why in the Guile manual. -The idea of the GH interface was to provide a high level API that other languages and projects -could adopt. This was a good idea, but didn't pan out well for general development. But for the -specific, minimal uses that the SWIG typemaps put the GH interface to use is ideal for -using a high level API. So even though the GH interface is depreciated, SWIG will continue to use -the GH interface and provide mappings from the GH interface to whatever API we need. -We can maintain this mapping where guile failed because SWIG uses a small subset of all the GH functions -which map easily. All the guile typemaps like typemaps.i and std_vector.i -will continue to use the GH functions to do things like create lists of values, convert strings to -integers, etc. Then every language module will define a mapping between the GH interface and -whatever custom API the language uses. This is currently implemented by the guile module to use -the SCM guile API rather than the GH guile API. -For example, here are some of the current mapping file for the SCM API

        -
        +

        Support for the guile GH wrapper code generation has been dropped from SWIG. The last +version of SWIG that can still generate guile GH wrapper code is 2.0.9. Please +use that version if you really need the GH wrapper code. -#define gh_append2(a, b) scm_append(scm_listify(a, b, SCM_UNDEFINED)) -#define gh_apply(a, b) scm_apply(a, b, SCM_EOL) -#define gh_bool2scm SCM_BOOL -#define gh_boolean_p SCM_BOOLP -#define gh_car SCM_CAR -#define gh_cdr SCM_CDR -#define gh_cons scm_cons -#define gh_double2scm scm_make_real -... -

        - -

        This file is parsed by SWIG at wrapper generation time, so every reference to a gh_ function is replaced -by a scm_ function in the wrapper file. Thus the gh_ function calls will never be seen in the wrapper; -the wrapper will look exactly like it was generated -for the specific API. Currently only the guile language module has created a mapping policy from gh_ to scm_, -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.

        - -

        23.3 Linkage

        +

        24.4 Linkage

        @@ -111,7 +88,7 @@ Guile support is complicated by a lack of user community cohesiveness, which manifests in multiple shared-library usage conventions. A set of policies implementing a usage convention is called a linkage. -

        23.3.1 Simple Linkage

        +

        24.4.1 Simple Linkage

        @@ -134,7 +111,7 @@ libraries into Guile.

         (define-module (my module))
        -(define my-so (dynamic-link "./example.so"))
        +(define my-so (dynamic-link "./libexample.so"))
         (dynamic-call "SWIG_init" my-so) ; make SWIG bindings
         ;; Scheme definitions can go here
         
        @@ -147,7 +124,17 @@ and dynamic-call:
        -(load-extension "./example.so" "SWIG_init")
        +(load-extension "./libexample.so" "SWIG_init")
        +
        +
        + +

        +A more portable approach would be to drop the shared library extension: +

        + +
        +
        +(load-extension "./libexample" "SWIG_init")
         
        @@ -190,7 +177,7 @@ information by including a directive like this in the interface file:
        -%scheme %{ (load-extension "./example.so" "SWIG_init") %}
        +%scheme %{ (load-extension "./libexample.so" "SWIG_init") %}
         
        @@ -206,7 +193,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. -

        23.3.2 Passive Linkage

        +

        24.4.2 Passive Linkage

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

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

        23.3.3 Native Guile Module Linkage

        +

        24.4.3 Native Guile Module Linkage

        SWIG can also generate wrapper code that does all the Guile module declarations on its own if you pass it the -Linkage -module command-line option. This requires Guile 1.5.0 or later. +module command-line option.

        The module name is set with the -package and -module command-line options. Suppose you want to define @@ -244,7 +231,7 @@ shared libraries into Guile; all bindings are automatically put in newly created Guile modules.

        -(define my-so (dynamic-link "./foo.so"))
        +(define my-so (dynamic-link "./libfoo"))
         ;; create new module and put bindings there:
         (dynamic-call "scm_init_my_modules_foo_module" my-so) 
         
        @@ -252,12 +239,12 @@ newly created Guile modules. Newer Guile versions have a shorthand procedure for this:
        -(load-extension "./foo.so" "scm_init_my_modules_foo_module")
        +(load-extension "./libfoo.so" "scm_init_my_modules_foo_module")
         
      -

      23.3.4 Old Auto-Loading Guile Module Linkage

      +

      24.4.4 Old Auto-Loading Guile Module Linkage

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

      23.3.5 Hobbit4D Linkage

      +

      24.4.5 Hobbit4D Linkage

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

      -

      23.4 Underscore Folding

      +

      24.5 Underscore Folding

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

      23.5 Typemaps

      +

      24.6 Typemaps

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

      -

      23.6 Representation of pointers as smobs

      +

      24.7 Representation of pointers as smobs

      @@ -433,7 +420,7 @@ representing the expected pointer type. See also If the Scheme object passed was not a SWIG smob representing a compatible pointer, a wrong-type-arg exception is raised. -

      23.6.1 GH Smobs

      +

      24.7.1 Smobs

      @@ -444,44 +431,19 @@ mangled type name. As Guile allows registering user types, so-called implemented now. The details will be discussed in the following.

      -

      A smob is a cons cell where the lower half of the CAR contains the smob type -tag, while the upper half of the CAR and the whole CDR are available. Every -module creates its own smob type in the clientdata field of the module. So the -lower 16 bits of the car of the smob store the tag and the upper 16 bits store -the index this type is in the array. We can then, given a smob, find its -swig_type_info struct by using the tag (lower 16 bits of car) to find which -module this type is in (since each tag is unique for the module). Then we use -the upper 16 bits to index into the array of types attached to this module. -Looking up the module from the tag is worst case O(# of modules) but average -case O(1). This is because the modules are stored in a circularly linked list, -and when we start searching the modules for the tag, we start looking with the -module that the function doing the lookup is in. SWIG_Guile_ConvertPtr() takes -as its first argument the swig_module_info * of the calling function, which is -where we start comparing tags. Most types will be looked up in the same module -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.

      - -

      23.6.2 SCM Smobs

      - - -

      The SCM interface (using the "-scm" argument to swig) uses swigrun.swg. -The whole type system, when it is first initialized, creates two smobs named "swig" and "collected_swig". +

      The whole type system, when it is first initialized, creates two smobs named "swig" and "collected_swig". The swig smob is used for non-garbage collected smobs, while the collected_swig smob is used as described below. Each smob has the same format, which is a double cell created by SCM_NEWSMOB2() The first word of data is the pointer to the object and the second word of data is the swig_type_info * -structure describing this type. This is a lot easier than the GH interface above because we can store -a pointer to the type info structure right in the type. With the GH interface, there was not enough -room in the smob to store two whole words of data so we needed to store part of the "swig_type_info address" -in the smob tag. If a generated GOOPS module has been loaded, smobs will be wrapped by the corresponding -GOOPS class.

      +structure describing this type. If a generated GOOPS module has been loaded, smobs will be wrapped by +the corresponding GOOPS class.

      -

      23.6.3 Garbage Collection

      +

      24.7.2 Garbage Collection

      -

      Garbage collection is a feature of the new SCM interface, and it is automatically included -if you pass the "-scm" flag to swig. Thus the swig garbage collection support requires guile >1.6. +

      Garbage collection is a feature of Guile since version 1.6. As SWIG now requires Guile > 1.8, +it is automatically included. Garbage collection works like this. Every swig_type_info structure stores in its clientdata field a pointer to the destructor for this type. The destructor is the generated wrapper around the delete function. So swig still exports a wrapper for the destructor, it just does not call scm_c_define_gsubr() for @@ -491,7 +453,7 @@ is exactly like described in 23.7 Exception Handling +

      24.8 Exception Handling

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

      23.8 Procedure documentation

      +

      24.9 Procedure documentation

      If invoked with the command-line option -procdoc file, SWIG creates documentation strings for the generated wrapper functions, describing the procedure signature and -return value, and writes them to file. You need Guile 1.4 -or later to make use of the documentation files. +return value, and writes them to file.

      SWIG can generate documentation strings in three formats, which are selected via the command-line option -procdocformat @@ -553,7 +514,7 @@ like this: typemap argument doc. See Lib/guile/typemaps.i for details. -

      23.9 Procedures with setters

      +

      24.10 Procedures with setters

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

      23.10 GOOPS Proxy Classes

      +

      24.11 GOOPS Proxy Classes

      SWIG can also generate classes and generic functions for use with @@ -589,10 +550,7 @@ Guile's Object-Oriented Programming System (GOOPS). GOOPS is a sophisticated object system in the spirit of the Common Lisp Object System (CLOS). -

      GOOPS support is -only available with the new SCM interface (enabled with the --scm command-line option of SWIG). To enable GOOPS -support, pass the -proxy argument to +

      To enable GOOPS support, pass the -proxy argument to swig. This will export the GOOPS wrapper definitions into the module.scm file in the directory specified by -outdir or the current directory. GOOPS support requires either passive or module linkage.

      @@ -730,7 +688,7 @@ Notice that <Foo> is used before it is defined. The fix is to just put th %import "foo.h" before the %inline block.

      -

      23.10.1 Naming Issues

      +

      24.11.1 Naming Issues

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

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

    23.10.2 Linking

    +

    24.11.2 Linking

    The guile-modules generated above all need to be linked together. GOOPS support requires @@ -787,10 +745,10 @@ and might conflict with names from the GOOPS guile-module (see above). Pass the argument to solve this problem. If the -exportprimitive option is passed to SWIG the (export ...) code that would be exported into the scmstub file is exported at the bottom of the generated GOOPS guile-module. -The %goops directive should contain code to load the .so library. +The %goops directive should contain code to load the shared library.

    -%goops %{ (load-extension "./foo.so" "scm_init_my_modules_foo_module") %}
    +%goops %{ (load-extension "./libfoo.so" "scm_init_my_modules_foo_module") %}
     

    @@ -802,7 +760,7 @@ Produces the following code at the top of the generated GOOPS guile-module (define-module (my modules foo)) ;; %goops directive goes here -(load-extension "./foo.so" "scm_init_my_modules_foo_module") +(load-extension "./libfoo.so" "scm_init_my_modules_foo_module") (use-modules (oop goops) (Swig common)) @@ -810,7 +768,7 @@ Produces the following code at the top of the generated GOOPS guile-module

  • Passive Linkage with -scmstub: Here, the name of the scmstub file should be Module-primitive.scm (with primitive replaced with whatever is given with the -primsuffix -argument. The code to load the .so library should be located in the %scheme directive, +argument. The code to load the shared library should be located in the %scheme directive, which will then be added to the scmstub file. SWIG will automatically generate the line (use-modules (Package Module-primitive)) into the GOOPS guile-module. So if Module-primitive.scm is on the autoload path for guile, the @@ -818,7 +776,7 @@ into the GOOPS guile-module. So if Module-primitive.scm is on the autolo whatever code is needed to load the Module-primitive.scm file into guile.

    -%scheme %{ (load-extension "./foo.so" "scm_init_my_modules_foo_module") %}
    +%scheme %{ (load-extension "./libfoo.so" "scm_init_my_modules_foo_module") %}
     // only include the following definition if (my modules foo) cannot
     // be loaded automatically
     %goops %{ 
    @@ -851,7 +809,7 @@ SWIG will also automatically generate the line (use-modules
     directive should contain whatever code is needed to get that module loaded into guile.

    -%goops %{ (load-extension "./foo.so" "scm_init_my_modules_foo_module") %}
    +%goops %{ (load-extension "./libfoo.so" "scm_init_my_modules_foo_module") %}
     

    @@ -862,7 +820,7 @@ Produces the following code at the top of the generated GOOPS guile-module (define-module (my modules foo)) ;; %goops directive goes here (if any) -(load-extension "./foo.so" "scm_init_my_modules_foo_module") +(load-extension "./libfoo.so" "scm_init_my_modules_foo_module") (use-modules (oop goops) (Swig common)) (use-modules ((my modules foo-primitive) :renamer (symbol-prefix-proc diff --git a/Doc/Manual/Introduction.html b/Doc/Manual/Introduction.html index a8d15a5c2..19d59a4df 100644 --- a/Doc/Manual/Introduction.html +++ b/Doc/Manual/Introduction.html @@ -38,7 +38,7 @@ SWIG is a software development tool that simplifies the task of interfacing different languages to C and C++ programs. In a nutshell, SWIG is a compiler that takes C/C++ declarations and creates -the wrappers needed to access those declarations from other languages including +the wrappers needed to access those declarations from other languages including Perl, Python, Tcl, Ruby, Guile, and Java. SWIG normally requires no modifications to existing code and can often be used to build a usable interface in only a few minutes. Possible applications @@ -49,7 +49,7 @@ of SWIG include:

  • Building interpreted interfaces to existing C programs.
  • Rapid prototyping and application development.
  • Interactive debugging. -
  • Reengineering or refactoring of legacy software into a scripting language components. +
  • Reengineering or refactoring of legacy software into scripting language components.
  • Making a graphical user interface (using Tk for example).
  • Testing of C libraries and programs (using scripts).
  • Building high performance C modules for scripting languages. @@ -98,7 +98,7 @@ of other libraries).
  • Testing is time consuming (the compile/debug cycle).
  • Not easy to reconfigure or customize without recompilation.
  • Modularization can be tricky. -
  • Security concerns (buffer overflow for instance). +
  • Security concerns (buffer overflows for instance).

    To address these limitations, many programmers have arrived at the @@ -345,7 +345,7 @@ not only parses C++, it implements the full C++ type system and it is able to understand C++ semantics. SWIG generates its wrappers with full knowledge of this information. As a result, you will find SWIG to be just as capable of dealing with nasty corner cases as it is in -wrapping simple C++ code. In fact, SWIG is able handle C++ code that +wrapping simple C++ code. In fact, SWIG is able to handle C++ code that stresses the very limits of many C++ compilers. @@ -388,8 +388,8 @@ There is growing support for SWIG in some build tools, for example -

    24 SWIG and Java

    +

    25 SWIG and Java

  • Accessing protected members
  • Common customization features @@ -155,7 +157,7 @@ It covers most SWIG features, but certain low-level details are covered in less

    -

    24.1 Overview

    +

    25.1 Overview

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

    -

    24.2 Preliminaries

    +

    25.2 Preliminaries

    @@ -210,7 +212,7 @@ This is the commonly used method to load JNI code so your system will more than Android uses Java JNI and also works with SWIG. Please read the Android chapter in conjunction with this one if you are targeting Android.

    -

    24.2.1 Running SWIG

    +

    25.2.1 Running SWIG

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

    -

    24.2.2 Additional Commandline Options

    +

    25.2.2 Additional Commandline Options

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

    -

    24.2.3 Getting the right header files

    +

    25.2.3 Getting the right header files

    @@ -321,17 +323,18 @@ They are usually in directories like this:

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

    -

    24.2.4 Compiling a dynamic module

    +

    25.2.4 Compiling a dynamic module

    The JNI code exists in a dynamic module or shared library (DLL on Windows) and gets loaded by the JVM. -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 -fPIC -c example_wrap.c -I/usr/java/include -I/usr/java/include/solaris
    +$ gcc -fPIC -c example.c
    +$ ld -G example_wrap.o example.o -o libexample.so
     

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

    -

    24.2.5 Using your module

    +

    25.2.5 Using your module

    @@ -392,7 +395,7 @@ $ If it doesn't work have a look at the following section which discusses problems loading the shared library.

    -

    24.2.6 Dynamic linking problems

    +

    25.2.6 Dynamic linking problems

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

    -

    24.2.7 Compilation problems and compiling with C++

    +

    25.2.7 Compilation problems and compiling with C++

    @@ -490,8 +493,7 @@ compiler. For example:

     % swig -c++ -java example.i
     % g++ -c -fpic example.cxx
    -% g++ -c -fpic example_wrap.cxx -I/usr/java/j2sdk1.4.1/include -I/usr/java/
    -j2sdk1.4.1/include/linux
    +% g++ -c -fpic example_wrap.cxx -I/usr/java/j2sdk1.4.1/include -I/usr/java/j2sdk1.4.1/include/linux
     % g++ -shared example.o example_wrap.o -o libexample.so
     
    @@ -532,7 +534,7 @@ Finally make sure the version of JDK header files matches the version of Java th

    -

    24.2.8 Building on Windows

    +

    25.2.8 Building on Windows

    @@ -541,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.

    -

    24.2.8.1 Running SWIG from Visual Studio

    +

    25.2.8.1 Running SWIG from Visual Studio

    @@ -580,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.

    -

    24.2.8.2 Using NMAKE

    +

    25.2.8.2 Using NMAKE

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

    -

    24.3 A tour of basic C/C++ wrapping

    +

    25.3 A tour of basic C/C++ wrapping

    @@ -649,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.

    -

    24.3.1 Modules, packages and generated Java classes

    +

    25.3.1 Modules, packages and generated Java classes

    @@ -685,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.

    -

    24.3.2 Functions

    +

    25.3.2 Functions

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

  • -

    24.3.3 Global variables

    +

    25.3.3 Global variables

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

    24.3.4 Constants

    +

    25.3.4 Constants

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

    -

    24.3.5 Enumerations

    +

    25.3.5 Enumerations

    @@ -960,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.

    -

    24.3.5.1 Anonymous enums

    +

    25.3.5.1 Anonymous enums

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

    -

    24.3.5.2 Typesafe enums

    +

    25.3.5.2 Typesafe enums

    @@ -1117,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.

    -

    24.3.5.3 Proper Java enums

    +

    25.3.5.3 Proper Java enums

    @@ -1170,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.

    -

    24.3.5.4 Type unsafe enums

    +

    25.3.5.4 Type unsafe enums

    @@ -1218,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.

    -

    24.3.5.5 Simple enums

    +

    25.3.5.5 Simple enums

    @@ -1237,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.

    -

    24.3.6 Pointers

    +

    25.3.6 Pointers

    @@ -1325,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.

    -

    24.3.7 Structures

    +

    25.3.7 Structures

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

    24.3.8 C++ classes

    +

    25.3.8 C++ classes

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

    24.3.9 C++ inheritance

    +

    25.3.9 C++ inheritance

    @@ -1617,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.

    -

    24.3.10 Pointers, references, arrays and pass by value

    +

    25.3.10 Pointers, references, arrays and pass by value

    @@ -1672,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).

    -

    24.3.10.1 Null pointers

    +

    25.3.10.1 Null pointers

    @@ -1696,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.

    -

    24.3.11 C++ overloaded functions

    +

    25.3.11 C++ overloaded functions

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

    24.3.12 C++ default arguments

    +

    25.3.12 C++ default arguments

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

    -

    24.3.13 C++ namespaces

    +

    25.3.13 C++ namespaces

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

    +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

    +

    25.3.14 C++ templates

    @@ -1988,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.

    -

    24.3.15 C++ Smart Pointers

    +

    25.3.15 C++ Smart Pointers

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

    24.4 Further details on the generated Java classes

    +

    25.4 Further details on the generated Java classes

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

    -

    24.4.1 The intermediary JNI class

    +

    25.4.1 The intermediary JNI class

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

    -

    24.4.1.1 The intermediary JNI class pragmas

    +

    25.4.1.1 The intermediary JNI class pragmas

    @@ -2223,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 @@ -2286,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.

    -

    24.4.2 The Java module class

    +

    25.4.2 The Java module class

    @@ -2317,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.

    -

    24.4.2.1 The Java module class pragmas

    +

    25.4.2.1 The Java module class pragmas

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

    -

    24.4.3 Java proxy classes

    +

    25.4.3 Java proxy classes

    @@ -2444,7 +2454,7 @@ int y = f.spam(5, new Foo()); -

    24.4.3.1 Memory management

    +

    25.4.3.1 Memory management

    @@ -2606,7 +2616,7 @@ and

    -

    24.4.3.2 Inheritance

    +

    25.4.3.2 Inheritance

    @@ -2722,7 +2732,7 @@ However, true cross language polymorphism can be achieved using the 24.4.3.3 Proxy classes and garbage collection +

    25.4.3.3 Proxy classes and garbage collection

    @@ -2805,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.

    -

    24.4.3.4 The premature garbage collection prevention parameter for proxy class marshalling

    +

    25.4.3.4 The premature garbage collection prevention parameter for proxy class marshalling

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

    -

    24.4.3.5 Single threaded applications and thread safety

    +

    25.4.3.5 Single threaded applications and thread safety

    @@ -3015,7 +3025,7 @@ for (int i=0; i<100000; i++) { -

    24.4.4 Type wrapper classes

    +

    25.4.4 Type wrapper classes

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

    24.4.5 Enum classes

    +

    25.4.5 Enum classes

    @@ -3111,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.

    -

    24.4.5.1 Typesafe enum classes

    +

    25.4.5.1 Typesafe enum classes

    @@ -3195,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.

    -

    24.4.5.2 Proper Java enum classes

    +

    25.4.5.2 Proper Java enum classes

    @@ -3273,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.

    -

    24.4.5.3 Type unsafe enum classes

    +

    25.4.5.3 Type unsafe enum classes

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

    24.5 Cross language polymorphism using directors

    +

    25.5 Cross language polymorphism using directors

    @@ -3326,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.

    -

    24.5.1 Enabling directors

    +

    25.5.1 Enabling directors

    @@ -3354,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; @@ -3397,7 +3404,7 @@ public: -

    24.5.2 Director classes

    +

    25.5.2 Director classes

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

    -

    24.5.3 Overhead and code bloat

    +

    25.5.3 Overhead and code bloat

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

    -

    24.5.4 Simple directors example

    +

    25.5.4 Simple directors example

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

    24.5.5 Director threading issues

    +

    25.5.5 Director threading issues

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

    24.6 Accessing protected members

    +

    25.5.6 Director performance tuning

    + + +

    +When a new instance of a director (or subclass) is created in Java, the C++ side of the director performs a runtime check per director method to determine if that particular method is overridden in Java or if it should invoke the C++ base implementation directly. Although this makes initialization slightly more expensive, it is generally a good overall tradeoff. +

    + +

    +However, if all director methods are expected to usually be overridden by Java subclasses, then initialization can be made faster by avoiding these checks via the assumeoverride attribute. For example: +

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

    + +

    25.5.7 Java exceptions from directors

    + + +

    +With directors routing method calls to Java, and proxies routing them +to C++, the handling of exceptions is an important concern. +The default behavior from SWIG 3.0 +onwards is to convert the thrown Java exception into a SWIG defined +DirectorException C++ exception. +SWIG 2.0 and earlier versions didn't provide any mechanism to handle the Java director method exceptions in C++. +

    + +

    +Converting Java exceptions into C++ exceptions can be done in two different ways using +the director:except feature. +In the simplest approach, a code block is attached to each director method to +handle the mapping of Java exceptions into C++ exceptions. +

    + +
    +
    +%feature("director:except") MyClass::method(int x) {
    +  jthrowable $error = jenv->ExceptionOccurred();
    +  if ($error) {
    +    jenv->ExceptionClear();
    +    if (Swig::ExceptionMatches(jenv, $error, "java/lang/IndexOutOfBoundsException"))
    +      throw std::out_of_range(Swig::JavaExceptionMessage(jenv, $error).message());
    +    if (Swig::ExceptionMatches(jenv, $error, "$packagepath/MyJavaException"))
    +      throw MyCppException(Swig::JavaExceptionMessage(jenv, $error).message());
    +    throw std::runtime_error("Unexpected exception thrown in MyClass::method");
    +  }
    +}
    +
    +class MyClass {
    +  /** Throws either a std::out_of_range or MyCppException on error */
    +  void method(int x);
    +}
    +
    +
    + +

    +This approach allows a flexible mapping of Java exceptions thrown by director methods into +C++ exceptions expected by a C++ caller. There +need not be any C++ exception specifications on the C++ method. The +utility function Swig::ExceptionMatches +and class Swig::JavaExceptionMessage are provided to simplify +writing code for wrappers that use the director:except feature. The +function Swig::ExceptionMatches matches the type of the +jthrowable thrown against a fully qualified JNI style class +name, such as "java/lang/IOError". If the throwable class is the same +type, or derives from the given type, Swig::ExceptionMatches will return true. Care must be taken to +provide the correct fully qualified name, since for wrapped exceptions the +generated proxy class will have additional package qualification, depending on +the '-package' argument and use of the nspace + feature. The special variable $error is expanded by SWIG into a unique variable name and +should be used for the +assignment of the exception that occurred. The special variable $packagepath is +replaced by the outer package provided for SWIG generation by the -package +option. The utility class Swig::JavaExceptionMessage is a holder +providing access to the message from the thrown Java exception. +The message() method returns the exception message as a const char *, +which is only valid during the lifetime of the holder. Any code using this message +needs to copy it, for example into a std::string or a newly constructed C++ exception. +

    + +

    +Using the above approach to +write handlers for a large number of methods will require +repetitive duplication of the director:except feature code. +To mitigate this, an alternative approach is provided via typemaps in a +fashion analagous to +the "throws" typemap. The +"throws" typemap provides an approach to automatically map all the C++ +exceptions listed in a method's defined exceptions (either from +a C++ exception specification or a %catches +feature) into Java exceptions. +The "directorthrows" typemap provides the inverse mapping and should contain +code to convert a suitably matching Java exception into a C++ exception. +The example below converts a Java java.lang.IndexOutOfBoundsException exception +to the typemap's type, that is std::out_of_range: + +

    +
    +%typemap(directorthrows) std::out_of_range %{
    +  if (Swig::ExceptionMatches(jenv, $error, "java/lang/IndexOutOfBoundsException")) {
    +    throw std::out_of_range(Swig::JavaExceptionMessage(jenv, $error).message());
    +  }
    +%}
    +
    +
    + +

    +The "directorthrows" typemap is then used in conjunction with the +director:except feature if the $directorthrowshandlers special variable +is used in the feature code. Consider the following, which also happens to be the default: +

    + +
    +
    +%feature("director:except") %{
    +   jthrowable $error = jenv->ExceptionOccurred();
    +   if ($error) {
    +     jenv->ExceptionClear();
    +     $directorthrowshandlers
    +     throw Swig::DirectorException(jenv, $error);
    +   }
    +%}
    +
    +
    + +

    The code generated using the director:except feature +replaces the $directorthrowshandlers special variable with the code in +the "directorthrows" typemaps, for each and every exception defined for the method. +The possible exceptions can be defined either with a C++ exception +specification or %catches as described for the +"throws" typemap. +

    + +

    +Consider the following director method: +

    + +
    +
    +  ...
    +  virtual void doSomething(int index) throw (std::out_of_range);
    +  ...
    +
    +
    + +

    +When combined with the default director:except feature and the "directorthrows" typemap above, +the resulting code generated in the director method after calling up to Java will be: +

    + +
    +
    +jthrowable swigerror = jenv->ExceptionOccurred();
    +if (swigerror) {
    +  jenv->ExceptionClear();
    +  if (Swig::ExceptionMatches(jenv, swigerror, "java/lang/IndexOutOfBoundsException")) {
    +    throw std::out_of_range(Swig::JavaExceptionMessage(jenv, swigerror).message());
    +  }
    +  
    +  throw Swig::DirectorException(jenv, swigerror);
    +}
    +
    +
    + +

    +Note: Beware of using exception specifications as the SWIG director methods +will be generated with the same exception specifications and if the +director method throws an exception that is not specified it is likely +to terminate your program. See the C++ standard for more details. +Using the %catches feature instead to define the handled exceptions does not suffer +this potential fate. +

    + +

    Because the default code generation maps any unhandled Java exceptions to +Swig::DirectorException, any director methods that have exception +specifications may cause program termination. To simply ignore +unexpected exceptions, the default handling can be changed with: +

    + +
    +
    +%feature("director:except") %{
    +   jthrowable $error = jenv->ExceptionOccurred();
    +   if ($error) {
    +     jenv->ExceptionClear();
    +     $directorthrowshandlers
    +     return $null; // exception is ignored
    +   }
    +%}
    +
    +
    + +

    Alternatively an exception compatible with the existing director +method exception specifications can be thrown. Assuming that all +methods allow std::runtime_error to be thrown, +the return $null; could be changed to: +

    + +
    +
    +   throw std::runtime_error(Swig::JavaExceptionMessage(jenv, $error).message());
    +
    +
    + +

    In more complex situations, a separate director:except feature +may need to be attached to specific methods. +

    + +

    Below is a complete example demonstrating the use +of the "directorthrows" typemaps. In this example, a +generic "directorthrows" typemap is appropriate for all three exceptions - all +take single string constructors. If the exceptions had different constructors, +it would be neccessary to have separate typemaps for each exception type. + + + +

    +
    +%module(directors="1") example
    +
    +%{
    +  #include <string>
    +  #include <stdexcept>
    +%}
    +
    +// Define exceptions in header section using std::runtime_error
    +%define DEFINE_EXCEPTION(NAME)
    +%{
    +  namespace MyNS {
    +    struct NAME : public std::runtime_error { NAME(const std::string &what) : runtime_error(what) {} };
    +  }
    +%}
    +%enddef
    +
    +// Expose C++ exceptions as Java Exceptions by changing the Java base class and providing a getMessage()
    +%define DECLARE_EXCEPTION(NAME)
    +%typemap(javabase) MyNS::NAME "java.lang.Exception";
    +%rename(getMessage) MyNS::NAME::what;
    +namespace MyNS {
    +  struct NAME {
    +    NAME(const std::string& what);
    +    const char * what();
    +  };
    +}
    +%enddef
    +
    +DEFINE_EXCEPTION(ExceptionA)
    +DEFINE_EXCEPTION(ExceptionB)
    +DEFINE_EXCEPTION(Unexpected)
    +
    +// Mark three methods to map director thrown exceptions.
    +%feature("director:except") MyClass::meth1(int);
    +%feature("director:except") MyClass::meth2;
    +%feature("director:except") meth3;
    +
    +%typemap(directorthrows) MyNS::ExceptionA, MyNS::ExceptionB, MyNS::Unexpected %{
    +  if (Swig::ExceptionMatches(jenv, $error, "$packagepath/$javaclassname"))
    +    throw $1_type(Swig::JavaExceptionMessage(jenv, $error).message());
    +%}
    +
    +DECLARE_EXCEPTION(ExceptionA)
    +DECLARE_EXCEPTION(ExceptionB)
    +DECLARE_EXCEPTION(Unexpected)
    +
    +%catches(MyNS::ExceptionA, MyNS::ExceptionB, MyNS::Unexpected) MyClass::meth2();
    +
    +%inline {
    +  class MyClass {
    +  public:
    +    virtual void meth1(int x) throw(MyNS::ExceptionA, MyNS::ExceptionB) = 0;
    +    virtual void meth2() = 0;   /* throws MyNS::ExceptionA, MyNS::ExceptionB, MyNS::Unexpected */
    +    virtual void meth3(float x) throw(MyNS::Unexpected) = 0;
    +    virtual ~MyClass() {}
    +  };
    +}
    +
    +
    + +

    +In this case the three different "directorthrows" typemaps will be used +to generate the three different exception handlers for +meth1, meth2 and meth3. The generated +handlers will have "if" blocks for each exception type specified, in +the exception specification or %catches feature. +

    + +

    Note that the "directorthrows" typemaps are important +only if it is important for the the exceptions passed through the C++ +layer to be mapped to distinct C++ exceptions. If director methods +are being called by C++ code that is itself wrapped in a +SWIG generated Java wrapper and access is always through this wrapper, +the default Swig::DirectorException class provides enough information +to reconstruct the original exception. In this case removing the +$directorthrowshandlers special variable from the +default director:except feature and simply always +throwing a Swig::DirectorException will achieve the desired result. +Along with this a generic exception feature is added to convert any +caught Swig::DirectorExceptions back into the underlying +Java exceptions via the Swig::DirectorException::raiseJavaException method, +as demonstrated with %javaexception below: +

    + +
    +
    +%javaexception("Exception") MyClass::myMethod %{
    +  try {
    +    $action
    +  } catch (Swig::DirectorException &e) {
    +    // raise/throw the Java exception that originally caused the DirectorException
    +    e.raiseJavaException(jenv);
    +    return $null;
    +  }
    +%}
    +
    +
    + +

    +See the Exception handling with %exception and %javaexception +section for more on converting C++ exceptions to Java exceptions. +

    + +

    25.6 Accessing protected members

    @@ -3623,7 +3959,7 @@ class MyProtectedBase extends ProtectedBase -

    24.7 Common customization features

    +

    25.7 Common customization features

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

    -

    24.7.1 C/C++ helper functions

    +

    25.7.1 C/C++ helper functions

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

    -

    24.7.2 Class extension with %extend

    +

    25.7.2 Class extension with %extend

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

    -

    24.7.3 Exception handling with %exception and %javaexception

    +

    25.7.3 Exception handling with %exception and %javaexception

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

    -

    24.7.4 Method access with %javamethodmodifiers

    +

    25.7.4 Method access with %javamethodmodifiers

    @@ -3949,7 +4285,7 @@ protected static void protect_me() { -

    24.8 Tips and techniques

    +

    25.8 Tips and techniques

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

    -

    24.8.1 Input and output parameters using primitive pointers and references

    +

    25.8.1 Input and output parameters using primitive pointers and references

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

    -

    24.8.2 Simple pointers

    +

    25.8.2 Simple pointers

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

    -

    24.8.3 Wrapping C arrays with Java arrays

    +

    25.8.3 Wrapping C arrays with Java arrays

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

    -

    24.8.4 Unbounded C Arrays

    +

    25.8.4 Unbounded C Arrays

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

    -

    24.8.5 Binary data vs Strings

    +

    25.8.5 Binary data vs Strings

    @@ -4455,7 +4791,7 @@ len: 5 data: 68 69 0 6a 6b -

    24.8.6 Overriding new and delete to allocate from Java heap

    +

    25.8.6 Overriding new and delete to allocate from Java heap

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

    -

    24.9 Java typemaps

    +

    25.9 Java typemaps

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

    24.9.1 Default primitive type mappings

    +

    25.9.1 Default primitive type mappings

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

    -

    24.9.2 Default typemaps for non-primitive types

    +

    25.9.2 Default typemaps for non-primitive types

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

    -

    24.9.3 Sixty four bit JVMs

    +

    25.9.3 Sixty four bit JVMs

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

    -

    24.9.4 What is a typemap?

    +

    25.9.4 What is a typemap?

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

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

    +

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

    @@ -5156,7 +5492,7 @@ These are listed below: -

    24.9.6 Java typemap attributes

    +

    25.9.6 Java typemap attributes

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

    -

    24.9.7 Java special variables

    +

    25.9.7 Java special variables

    @@ -5338,7 +5674,7 @@ can be wrapped with the Java equivalent, that is, static inner proxy classes.

    -$jniinput, $javacall and $packagepath
    +$error, $jniinput, $javacall and $packagepath
    These special variables are used in the directors typemaps. See Director specific typemaps for details.

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

    -

    24.9.8 Typemaps for both C and C++ compilation

    +

    25.9.8 Typemaps for both C and C++ compilation

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

    -

    24.9.9 Java code typemaps

    +

    25.9.9 Java code typemaps

    @@ -5468,6 +5804,22 @@ 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
    +   }
    +]%
    +
    +

    @@ -5612,12 +5964,12 @@ to make the method and constructor public: -

    24.9.10 Director specific typemaps

    +

    25.9.10 Director specific typemaps

    The Java directors feature requires the "javadirectorin", "javadirectorout", "directorin" and the "directorout" typemaps in order to work properly. -The "javapackage" typemap is an optional typemap used to identify the Java package path for individual SWIG generated proxy classes. +The "javapackage" typemap is an optional typemap used to identify the Java package path for individual SWIG generated proxy classes used in director methods.

    %typemap(directorin)

    @@ -5656,6 +6008,10 @@ is the package name passed from the SWIG command line and $javaclassname-package
    commandline option is not used to specify the package, then '$packagepath/' will be removed from the resulting output JNI field descriptor. Do not forget the terminating ';' for JNI field descriptors starting with 'L'. If the ';' is left out, Java will generate a "method not found" runtime error. +Note that the $packagepath substitution always uses the path separator '/' when expanded. +The $javaclassname expansion can be confusing as it is normally expanded using the '.' separator. +However, $javaclassname is expanded using the path separator '/' in typemap's "descriptor" attribute +as well as in the "directorthrows" typemap.

    @@ -5751,6 +6107,40 @@ The target method is the method in the Java proxy class which overrides the virt +

    %typemap(directorthrows)

    +
    + +

    +Conversion of Java exceptions to C++ exceptions in director method's exception handling. +This typemap is expected to test the $error special variable for a matching Java exception +and if successful convert and throw it into a C++ exception given by the typemap's type. +The $error special variable is of type jthrowable and is +substituted with a unique variable name in the generated code. +

    + +

    +The example below converts a Java java.lang.IndexOutOfBoundsException exception +to the typemap's type, that is std::out_of_range: +

    + +
    +
    +%typemap(directorthrows) std::out_of_range %{
    +  if (Swig::ExceptionMatches(jenv, $error, "java/lang/IndexOutOfBoundsException")) {
    +    throw std::out_of_range(Swig::JavaExceptionMessage(jenv, $error).message());
    +  }
    +%}
    +
    +
    + +

    +The utility function Swig::ExceptionMatches +and class Swig::JavaExceptionMessage are helpers available when using directors and are described +in the Java Exceptions from Directors section. +

    + +
    +

    %typemap(javapackage)

    @@ -5758,6 +6148,7 @@ The target method is the method in the Java proxy class which overrides the virt

    The "javapackage" typemap is optional; it serves to identify a class's Java package. This typemap should be used in conjunction with classes that are defined outside of the current SWIG interface file. +The typemap is only used if the type is used in a director method, that is, in a virtual method in a director class. For example:

    @@ -5774,7 +6165,7 @@ For example: class Example { public: virtual ~Example(); - void ping(Foo *arg1, Bar *arg2); + virtual void ping(Foo *arg1, Bar *arg2); }; } @@ -5799,7 +6190,7 @@ The corrected interface file looks like: class Example { public: virtual ~Example(); - void ping(Foo *arg1, Bar *arg2); + virtual void ping(Foo *arg1, Bar *arg2); }; } @@ -5837,7 +6228,7 @@ The basic strategy here is to provide a default package typemap for the majority
    -

    24.10 Typemap Examples

    +

    25.10 Typemap Examples

    @@ -5847,7 +6238,7 @@ the SWIG library.

    -

    24.10.1 Simpler Java enums for enums without initializers

    +

    25.10.1 Simpler Java enums for enums without initializers

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

    -

    24.10.2 Handling C++ exception specifications as Java exceptions

    +

    25.10.2 Handling C++ exception specifications as Java exceptions

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

    -

    24.10.3 NaN Exception - exception handling for a particular type

    +

    25.10.3 NaN Exception - exception handling for a particular type

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

    -

    24.10.4 Converting Java String arrays to char **

    +

    25.10.4 Converting Java String arrays to char **

    @@ -6350,7 +6741,7 @@ Lastly the "jni", "jtype" and "jstype" typemaps are also required to specify what Java types to use.

    -

    24.10.5 Expanding a Java object to multiple arguments

    +

    25.10.5 Expanding a Java object to multiple arguments

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

    24.10.6 Using typemaps to return arguments

    +

    25.10.6 Using typemaps to return arguments

    @@ -6478,7 +6869,7 @@ int spam(double a, double b, double *out1, double *out2) { *out1 = a*10.0; *out2 = b*100.0; return status; -}; +} %} /* @@ -6550,7 +6941,7 @@ $ java runme 1 12.0 340.0 -

    24.10.7 Adding Java downcasts to polymorphic return types

    +

    25.10.7 Adding Java downcasts to polymorphic return types

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

    -

    24.10.8 Adding an equals method to the Java classes

    +

    25.10.8 Adding an equals method to the Java classes

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

    24.10.9 Void pointers and a common Java base class

    +

    25.10.9 Void pointers and a common Java base class

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

    24.10.10 Struct pointer to pointer

    +

    25.10.10 Struct pointer to pointer

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

    -

    24.10.11 Memory management when returning references to member variables

    +

    25.10.11 Memory management when returning references to member variables

    @@ -7162,7 +7553,7 @@ public class Bike { Note the addReference call.

    -

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

    +

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

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

    24.10.13 Date marshalling using the javain typemap and associated attributes

    +

    25.10.13 Date marshalling using the javain typemap and associated attributes

    @@ -7455,7 +7846,7 @@ A few things to note: -

    24.11 Living with Java Directors

    +

    25.11 Living with Java Directors

    @@ -7636,10 +8027,10 @@ public abstract class UserVisibleFoo extends Foo {

  • -

    24.12 Odds and ends

    +

    25.12 Odds and ends

    -

    24.12.1 JavaDoc comments

    +

    25.12.1 JavaDoc comments

    @@ -7695,7 +8086,7 @@ public class Barmy { -

    24.12.2 Functional interface without proxy classes

    +

    25.12.2 Functional interface without proxy classes

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

    24.12.3 Using your own JNI functions

    +

    25.12.3 Using your own JNI functions

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

    -

    24.12.4 Performance concerns and hints

    +

    25.12.4 Performance concerns and hints

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

    -

    24.12.5 Debugging

    +

    25.12.5 Debugging

    @@ -7840,7 +8231,7 @@ where it is possible to step from Java code into a JNI method within one environ

    Alternatively, debugging can involve placing debug printout statements in the JNI layer using the %exception directive. See the special variables for %exception section. -Many of the default typemaps can also be overidden and modified for adding in extra logging/debug display information. +Many of the default typemaps can also be overridden and modified for adding in extra logging/debug display information.

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

    -

    24.13 Java Examples

    +

    25.13 Java Examples

    @@ -7864,4 +8255,3 @@ Many of these have runtime tests in the java subdirectory. - diff --git a/Doc/Manual/Library.html b/Doc/Manual/Library.html index dcec21c90..740988e71 100644 --- a/Doc/Manual/Library.html +++ b/Doc/Manual/Library.html @@ -6,7 +6,7 @@ -

    8 SWIG library

    +

    9 SWIG library

  • Utility Libraries
      @@ -58,7 +59,7 @@ Alternative libraries provide similar functionality. Please read this chapter carefully if you used the old libraries.

      -

      8.1 The %include directive and library search path

      +

      9.1 The %include directive and library search path

      @@ -66,18 +67,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.

      @@ -89,7 +91,7 @@ Set the environment variable to hold an alternative library directory. The directories that are searched are displayed when using -verbose commandline option.

      -

      8.2 C Arrays and Pointers

      +

      9.2 C Arrays and Pointers

      @@ -101,7 +103,7 @@ pointers as class-like objects. Since these functions provide direct access to memory, their use is potentially unsafe and you should exercise caution.

      -

      8.2.1 cpointer.i

      +

      9.2.1 cpointer.i

      @@ -317,7 +319,7 @@ In this example, the function int_to_uint() would be used to cast type Note: When working with simple pointers, typemaps can often be used to provide more seamless operation.

      -

      8.2.2 carrays.i

      +

      9.2.2 carrays.i

      @@ -495,7 +497,7 @@ you should consider using a special array object rather than a bare pointer. used with types of char or char *.

      -

      8.2.3 cmalloc.i

      +

      9.2.3 cmalloc.i

      @@ -656,7 +658,7 @@ Now, in a script:

  • -

    8.2.4 cdata.i

    +

    9.2.4 cdata.i

    @@ -758,7 +760,7 @@ char *cdata_name(type* ptr, int nitems) Clearly they are unsafe.

    -

    8.3 C String Handling

    +

    9.3 C String Handling

    @@ -778,7 +780,7 @@ morality. The modules in this section provide basic functionality for manipulating raw C strings.

    -

    8.3.1 Default string handling

    +

    9.3.1 Default string handling

    @@ -819,7 +821,7 @@ interpreter and lead to a crash). Furthermore, the default behavior does not work well with binary data. Instead, strings are assumed to be NULL-terminated.

    -

    8.3.2 Passing binary data

    +

    9.3.2 Passing binary data

    @@ -861,7 +863,7 @@ In the wrapper function, the passed string will be expanded to a pointer and len The (char *STRING, int LENGTH) multi-argument typemap is also available in addition to (char *STRING, size_t LENGTH).

    -

    8.3.3 Using %newobject to release memory

    +

    9.3.3 Using %newobject to release memory

    @@ -902,7 +904,7 @@ however, you may need to provide your own "newfree" typemap for other types. See Object ownership and %newobject for more details.

    -

    8.3.4 cstring.i

    +

    9.3.4 cstring.i

    @@ -1362,7 +1364,7 @@ structure or class instead. -

    8.4 STL/C++ Library

    +

    9.4 STL/C++ Library

    @@ -1382,6 +1384,7 @@ The following table shows which C++ classes are supported and the equivalent SWI SWIG Interface library file + std::auto_ptr memory std_auto_ptr.i std::deque deque std_deque.i std::list list std_list.i std::map map std_map.i @@ -1399,7 +1402,7 @@ Please look for the library files in the appropriate language library directory.

    -

    8.4.1 std::string

    +

    9.4.1 std::string

    @@ -1483,7 +1486,7 @@ void foo(string s, const String &t); // std_string typemaps still applie -

    8.4.2 std::vector

    +

    9.4.2 std::vector

    @@ -1662,7 +1665,7 @@ if you want to make their head explode. details and the public API exposed to the interpreter vary.

    -

    8.4.3 STL exceptions

    +

    9.4.3 STL exceptions

    @@ -1712,13 +1715,28 @@ The %exception directive can be used by placing the following code befo Any thrown STL exceptions will then be gracefully handled instead of causing a crash.

    -

    8.4.4 shared_ptr smart pointer

    +

    9.4.4 shared_ptr smart pointer

    -Some target languages have support for handling the widely used boost::shared_ptr smart pointer. -This smart pointer is also available as std::tr1::shared_ptr before it becomes fully standardized as std::shared_ptr. -The boost_shared_ptr.i library provides support for boost::shared_ptr and std_shared_ptr.i provides support for std::shared_ptr, but if the following macro is defined as shown, it can be used for std::tr1::shared_ptr: +Some target languages have support for handling the shared_ptr reference counted smart pointer. +This smart pointer is available in the standard C++11 library as std::shared_ptr. +It was also in TR1 as std::tr1::shared_ptr before it was fully standardized. +Support for the widely used boost::shared_ptr is also available. +

    + +

    +In order to use std::shared_ptr, the std_shared_ptr.i library file should be included: +

    + +
    +
    +%include <std_shared_ptr.i>
    +
    +
    + +

    +The pre-standard std::tr1::shared_ptr can be used by including the following macro before including the std_shared_ptr.i library file:

    @@ -1728,6 +1746,16 @@ The boost_shared_ptr.i library provides support for boost::shared_p
    +

    +In order to use boost::shared_ptr, the boost_shared_ptr.i library file should be included: +

    + +
    +
    +%include <boost_shared_ptr.i>
    +
    +
    +

    You can only use one of these variants of shared_ptr in your interface file at a time. and all three variants must be used in conjunction with the %shared_ptr(T) macro, @@ -1871,10 +1899,64 @@ Adding the missing %shared_ptr macros will fix this: -

    8.5 Utility Libraries

    +

    +Note: There is currently no support for %shared_ptr and the director feature. +

    -

    8.5.1 exception.i

    +

    9.4.5 auto_ptr smart pointer

    + + +

    +While std::auto_ptr is deprecated in C++11, some existing code may +still be using it, so SWIG provides limited support for this class: +std_auto_ptr.i defines the typemaps which apply to the functions +returning objects of this type. Any other use of std_auto_ptr.i is not +directly supported. +

    + +

    +A typical example of use would be +

    +
    +
    +%include <std_auto_ptr.i>
    +
    +%auto_ptr(Klass)
    +%inline %{
    +class Klass {
    +public:
    +  // Factory function creating objects of this class:
    +  static std::auto_ptr<Klass> Create(int value) {
    +    return std::auto_ptr<Klass>(new Klass(value));
    +  }
    +
    +  int getValue() const { return m_value; }
    +
    +private:
    +  DerivedIntValue(int value) : m_value(value) {}
    +  int m_value;
    +};
    +%}
    +
    +
    + +

    +The returned objects can be used naturally from the target language, e.g. from +C#: +

    + +
    +
    +Klass k = Klass.Create(17);
    +int value = k.getValue();
    +
    +
    + +

    9.5 Utility Libraries

    + + +

    9.5.1 exception.i

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

    25 SWIG and Common Lisp

    +

    26 SWIG and Common Lisp

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

      -

      25.1 Allegro Common Lisp

      +

      26.1 Allegro Common Lisp

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

      -

      25.2 Common Foreign Function Interface(CFFI)

      +

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

      -

      25.2.1 Additional Commandline Options

      +

      26.2.1 Additional Commandline Options

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

      25.2.2 Generating CFFI bindings

      +

      26.2.2 Generating CFFI bindings

      As we mentioned earlier the ideal way to use SWIG is to use interface - files. To illustrate the use of it, lets assume that we have a + files. To illustrate the use of it, let's assume that we have a file named test.h with the following C code:
      @@ -392,7 +392,7 @@ The feature intern_function ensures that all C names are
       
       
      -

      25.2.3 Generating CFFI bindings for C++ code

      +

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

      25.2.4 Inserting user code into generated files

      +

      26.2.4 Inserting user code into generated files

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

      -

      25.3 CLISP

      +

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

      -

      25.3.1 Additional Commandline Options

      +

      26.3.1 Additional Commandline Options

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

      25.3.2 Details on CLISP bindings

      +

      26.3.2 Details on CLISP bindings

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

    -

    25.4 UFFI

    +

    26.4 UFFI

    diff --git a/Doc/Manual/Lua.html b/Doc/Manual/Lua.html index ec32c4449..c67e08834 100644 --- a/Doc/Manual/Lua.html +++ b/Doc/Manual/Lua.html @@ -6,7 +6,7 @@ -

    26 SWIG and Lua

    +

    27 SWIG and Lua

  • Typemaps -
  • Writing typemaps +
  • Writing typemaps
  • Customization of your Bindings @@ -73,14 +82,14 @@ Lua is an extension programming language designed to support general procedural 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

    +

    27.1 Preliminaries

    -The current SWIG implementation is designed to work with Lua 5.0.x, 5.1.x and 5.2.x. It should work with later versions of Lua, but certainly not with Lua 4.0 due to substantial API changes. It is possible to either static link or dynamic link a Lua module into the interpreter (normally Lua static links its libraries, as dynamic linking is not available on all platforms). SWIG also supports eLua and works with eLua 0.8. SWIG generated code for eLua has been tested on Stellaris ARM Cortex-M3 LM3S and Infineon TriCore. +The current SWIG implementation is designed to work with Lua 5.0.x, 5.1.x and 5.2.x. It should work with later versions of Lua, but certainly not with Lua 4.0 due to substantial API changes. It is possible to either static link or dynamic link a Lua module into the interpreter (normally Lua static links its libraries, as dynamic linking is not available on all platforms). SWIG also has support for eLua starting from eLua 0.8. Due to substantial changes between SWIG 2.x and SWIG 3.0 and unavailability of testing platform, eLua status was downgraded to 'experimental'.

    -

    26.2 Running SWIG

    +

    27.2 Running SWIG

    @@ -128,7 +137,7 @@ $ swig -lua -eluac example.i The -elua option puts all the C function wrappers and variable get/set wrappers in rotables. It also generates a metatable which will control the access to these variables from eLua. It also offers a significant amount of module size compression. On the other hand, the -eluac option puts all the wrappers in a single rotable. With this option, no matter how huge the module, it will consume no additional microcontroller SRAM (crass compression). There is a catch though: Metatables are not generated with -eluac. To access any value from eLua, one must directly call the wrapper function associated with that value.

    -

    26.2.1 Additional command line options

    +

    27.2.1 Additional command line options

    @@ -159,9 +168,17 @@ swig -lua -help Do not register the module name as a global variable but return the module table from calls to require. + + -no-old-metatable-bindings + Disable backward compatibility: old-style binding names generations and a few other things. Explanations are included in appropriate later sections. + + + -squash-bases + Squashes symbols from all inheritance tree of a given class into itself. Emulates pre-SWIG3.0 inheritance. Insignificantly speeds things up, but increases memory consumption. + -

    26.2.2 Compiling and Linking and Interpreter

    +

    27.2.2 Compiling and Linking and Interpreter

    @@ -232,16 +249,16 @@ 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

    +

    27.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
    -$ gcc -I/usr/include/lua -c example_wrap.c -o example_wrap.o
    -$ gcc -c example.c -o example.o
    +$ gcc -fPIC -I/usr/include/lua -c example_wrap.c -o example_wrap.o
    +$ gcc -fPIC -c example.c -o example.o
     $ gcc -shared -I/usr/include/lua -L/usr/lib/lua example_wrap.o example.o -o example.so
     

    @@ -300,7 +317,7 @@ Is quite obvious (Go back and consult the Lua documents on how to enable loadlib -

    26.2.4 Using your module

    +

    27.2.4 Using your module

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

  • -

    26.3 A tour of basic C/C++ wrapping

    +

    27.3 A tour of basic C/C++ wrapping

    By default, SWIG tries to build a very natural Lua interface to your C/C++ code. This section briefly covers the essential aspects of this wrapping.

    -

    26.3.1 Modules

    +

    27.3.1 Modules

    The SWIG module directive specifies the name of the Lua module. If you specify `module example', then everything is wrapped into a Lua table 'example' containing all the functions and variables. When choosing a module name, make sure you don't use the same name as a built-in Lua command or standard module name.

    -

    26.3.2 Functions

    +

    27.3.2 Functions

    @@ -349,7 +366,10 @@ creates a built-in function example.fact(n) that works exactly like you >

    -To avoid name collisions, SWIG create a Lua table which it keeps all the functions and global variables in. It is possible to copy the functions out of this and into the global environment with the following code. This can easily overwrite existing functions, so this must be used with care. +To avoid name collisions, SWIG create a Lua table which keeps all the functions, constants, classes and global variables in. +It is possible to copy the functions, constants and classes (but not variables) out of this and into the global environment with the following code. +This can easily overwrite existing functions, so this must be used with care. +This option is considered deprecated and will be removed in the near future.

     > for k,v in pairs(example) do _G[k]=v end
    @@ -368,7 +388,7 @@ It is also possible to rename the module with an assignment.
     24
     
    -

    26.3.3 Global variables

    +

    27.3.3 Global variables

    @@ -456,7 +476,7 @@ If you have used the -eluac option for your eLua module, you will have In general, functions of the form "variable_get()" and "variable_set()" are automatically generated by SWIG for use with -eluac.

    -

    26.3.4 Constants and enums

    +

    27.3.4 Constants and enums

    @@ -490,7 +510,64 @@ If you're using eLua and have used -elua or -eluac to generate > print(example.const.SCONST) Hello World -

    26.3.5 Pointers

    + +

    27.3.4.1 Constants/enums and classes/structures

    + + +

    +Enums are exported into a class table. For example, given some enums: +

    +
    %module example
    +enum Days { SUNDAY = 0, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY };
    +struct Test {
    +    enum { TEST1 = 10, TEST2 = 20 };
    +#ifdef __cplusplus // There are no static members in C
    +    static const int ICONST = 12;
    +#endif
    +};
    +
    +

    +There is a slight difference in behaviour wrapping C and C++ code due to the different scoping rules of C and C++. +The wrapped C++ code is used as follows from Lua code: +

    +
    +> print(example.SUNDAY)
    +0
    +> print(example.Test.TEST1)
    +10
    +> print(example.Test.ICONST)
    +12
    +
    + +

    Enums within a C struct are in the global namespace and are used as follows from Lua

    +
    +> print(example.SUNDAY)
    +0
    +> -- See the difference here
    +> print(example.TEST1)
    +10
    +
    + +

    +Compatibility Note: Versions of SWIG prior to SWIG-3.0.0 did not generate the class table members above. +There is no change in the C wrappers, but +the following code was the only way to access these constants/enums when wrapping C++ member constants: +

    +
    +> print(example.Test_TEST1)
    +10
    +> print(example.Test_ICONST)
    +12
    +
    +

    +The old-style bindings are still generated in addition to the new ones. +If the -no-old-metatable-bindings option is used, then these old-style bindings are not generated. +

    +

    +It is worth mentioning, that example.Test.TEST1 and example.Test_TEST1 are different entities and changing one does not change the other. +Given the fact that these are constantes and they are not supposed to be changed, it is up to you to avoid such issues. +

    +

    27.3.5 Pointers

    @@ -528,7 +605,7 @@ Lua enforces the integrity of its userdata, so it is virtually impossible to cor nil -

    26.3.6 Structures

    +

    27.3.6 Structures

    @@ -551,7 +628,7 @@ is used as follows:

    Similar access is provided for unions and the data members of C++ classes.
    -C structures are created using a function new_Point(), but for C++ classes are created using just the name Point(). +C structures can be created using a function new_Point(), and both C structures and C++ classes can be created using just the name Point().

    If you print out the value of p in the above example, you will see something like this: @@ -632,7 +709,7 @@ For eLua with the -eluac option, structure manipulation has to be perfo In general, functions of the form "new_struct()", "struct_member_get()", "struct_member_set()" and "free_struct()" are automatically generated by SWIG for each structure defined in C. (Please note: This doesn't apply for modules generated with the -elua option)

    -

    26.3.7 C++ classes

    +

    27.3.7 C++ classes

    @@ -676,12 +753,12 @@ public: };

    -In Lua, the static members can be accessed as follows: +In Lua, C++ static members can be accessed as follows:

    -> example.Spam_foo()            -- calling Spam::foo()
    -> a=example.Spam_bar            -- reading Spam::bar 
    -> example.Spam_bar=b            -- writing to Spam::bar
    +> example.Spam.foo()            -- calling Spam::foo()
    +> a=example.Spam.bar            -- reading Spam::bar 
    +> example.Spam.bar=b            -- writing to Spam::bar
     

    It is not (currently) possible to access static members of an instance: @@ -692,7 +769,22 @@ It is not (currently) possible to access static members of an instance: -- does NOT work -

    26.3.8 C++ inheritance

    +

    +Compatibility Note: In versions prior to SWIG-3.0.0 only the following names would work: +

    + +
    +> example.Spam_foo()            -- calling Spam::foo()
    +> a=example.Spam_bar            -- reading Spam::bar 
    +> example.Spam_bar=b            -- writing to Spam::bar
    +
    + +

    +Both style names are generated by default now. +However, if the -no-old-metatable-bindings option is used, then the backward compatible names are not generated in addition to ordinary ones. +

    + +

    27.3.8 C++ inheritance

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

    It is safe to use multiple inheritance with SWIG.

    -

    26.3.9 Pointers, references, values, and arrays

    +

    27.3.9 Pointers, references, values, and arrays

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

    -

    26.3.10 C++ overloaded functions

    +

    27.3.10 C++ overloaded functions

    @@ -834,7 +926,7 @@ Please refer to the "SWIG and C++" chapter for more information about overloadin

    Dealing with the Lua coercion mechanism, the priority is roughly (integers, floats, strings, userdata). But it is better to rename the functions rather than rely upon the ordering.

    -

    26.3.11 C++ operators

    +

    27.3.11 C++ operators

    @@ -898,7 +990,7 @@ The current list of operators which can be overloaded (and the alternative funct

  • __sub__ operator-
  • __mul__ operator *
  • __div__ operator/ -
  • __neg__ unary minus +
  • __unm__ unary minus
  • __call__ operator() (often used in functor classes)
  • __pow__ the exponential fn (no C++ equivalent, Lua uses ^)
  • __concat__ the concatenation operator (SWIG maps C++'s ~ to Lua's ..) @@ -945,8 +1037,30 @@ It is also possible to overload the operator[], but currently this cann void __setitem__(int i,double d); // i is the index, d is the data }; - -

    26.3.12 Class extension with %extend

    +

    +C++ operators are mapped to Lua predefined metafunctions. Class inherits from its bases the following list of metafunctions ( thus inheriting the folloging +operators and pseudo-operators):

    +
      +
    • __add__ +
    • __sub__ +
    • __mul__ +
    • __div__ +
    • __unm__ +
    • __mod__ +
    • __call__ +
    • __pow__ +
    • __concat__ +
    • __eq__ +
    • __lt__ +
    • __le__ +
    • __len__ +
    • __getitem__ +
    • __setitem__ +
    • __tostring used internally by Lua for tostring() function. __str__ is mapped to this function +
    +

    No other lua metafunction is inherited. For example, __gc is not inherited and must be redefined in every class. __tostring is subject to a special handling. If absent in class and in class bases, a default one will be provided by SWIG

    +

    +

    27.3.12 Class extension with %extend

    @@ -981,7 +1095,7 @@ Now we extend it with some new code return tmp; } bool operator==(const Complex& c) - { return ($self->re()==c.re() && $self->im()==c.im();} + { return ($self->re()==c.re() && $self->im()==c.im());} };

    @@ -1002,7 +1116,7 @@ true Extend works with both C and C++ code, on classes and structs. It does not modify the underlying object in any way---the extensions only show up in the Lua interface. The only item to take note of is the code has to use the '$self' instead of 'this', and that you cannot access protected/private members of the code (as you are not officially part of the class).

    -

    26.3.13 Using %newobject to release memory

    +

    27.3.13 Using %newobject to release memory

    If you have a function that allocates memory like this,

    @@ -1026,7 +1140,7 @@ char *foo();

    This will release the allocated memory.

    -

    26.3.14 C++ templates

    +

    27.3.14 C++ templates

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

    -

    26.3.15 C++ Smart Pointers

    +

    27.3.15 C++ Smart Pointers

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

    26.3.16 C++ Exceptions

    +

    27.3.16 C++ Exceptions

    @@ -1256,13 +1370,164 @@ and the "Exception handling add exception specification to functions or globally (respectively).

    +

    27.3.17 Namespaces

    -

    26.4 Typemaps

    + +

    +Since SWIG-3.0.0 C++ namespaces are supported via the %nspace feature. +

    +

    Namespaces are mapped into Lua tables. Each of those tables contains names that were defined within appropriate namespace. Namespaces structure (a.k.a nested namespaces) is preserved. Consider the following C++ code: +

    +
    %module example
    +%nspace MyWorld::Nested::Dweller;
    +%nspace MyWorld::World;
    +
    +int module_function() { return 7; }
    +int module_variable = 9;
    +
    +namespace MyWorld {
    +  class World {
    +  public:
    +    World() : world_max_count(9) {}
    +    int create_world() { return 17; }
    +    const int world_max_count; // = 9
    +  };
    +  namespace Nested {
    +    class Dweller {
    +      public:
    +        enum Gender { MALE = 0, FEMALE = 1 };
    +        static int count() { return 19; }
    +    };
    +  }
    +}
    +
    + +

    +Now, from Lua usage is as follows: +

    + +
    +> print(example.module_function())
    +7
    +> print(example.module_variable)
    +9
    +> print(example.MyWorld.World():create_world())
    +17
    +> print(example.MyWorld.World.world_max_count)
    +9
    +> print(example.MyWorld.Nested.Dweller.MALE)
    +0
    +> print(example.MyWorld.Nested.Dweller.count())
    +19
    +>
    +
    +

    27.3.17.1 Compatibility Note

    + + +

    +If SWIG is running in a backwards compatible way, i.e. without the -no-old-metatable-bindings option, then additional old-style names are generated (notice the underscore): +

    +
    +9
    +> print(example.MyWorld.Nested.Dweller_MALE)
    +0
    +> print(example.MyWorld.Nested.Dweller_count())
    +11
    +>
    +
    + + +

    27.3.17.2 Names

    + + +

    If SWIG is launched without -no-old-metatable-bindings option, then it enters backward-compatible mode. While in this mode, it tries +to generate additional names for static functions, class static constants and class enums. +Those names are in a form $classname_$symbolname and are added to the scope surrounding the class. +If %nspace is enabled, then class namespace is taken as scope. If there is no namespace, or %nspace is disabled, +then module is considered a class namespace.

    +

    Consider the following C++ code

    +
    %module example
    +%nspace MyWorld::Test;
    +namespace MyWorld {
    +class Test {
    +  public:
    +  enum { TEST1 = 10, TEST2 }
    +  static const int ICONST = 12;
    +};
    +class Test2 {
    +  public:
    +  enum { TEST3 = 20, TEST4 }
    +  static const int ICONST2 = 23;
    +}
    +
    +

    When in backward compatible mode, in addition to the usual names, the following ones will be generated (notice the underscore):

    +
    +9
    +> print(example.MyWorld.Test_TEST1) -- Test has %nspace enabled
    +10
    +> print(example.MyWorld.Test_ICONST) -- Test has %nspace enabled
    +12
    +> print(example.Test2_TEST3) -- Test2 doesn't have %nspace enabled
    +20
    +> print(example.Test2_ICONST2) -- Test2 doesn't have %nspace enabled
    +23
    +>
    +
    +

    There is a slight difference with enums when in C mode. As per C standard, enums from C structures are exported to +surrounding scope without any prefixing. Pretending that Test2 is a struct, not class, that would be:

    +
    +> print(example.TEST3) -- NOT Test2_TEST3
    +20
    +>
    +
    + +

    27.3.17.3 Inheritance

    + + +

    The internal organization of inheritance has changed. +Consider the following C++ code:

    +
    %module example
    +class Base {
    +  public:
    +  int base_func()
    +};
    +class Derived : public Base {
    +  public:
    +  int derived_func()
    +}
    +
    +

    Lets assume for a moment that class member functions are stored in .fn table. Previously, when classes +were exported to Lua during module initialization, for every derived class all service tables ST(i.e. ".fn") +were squashed and added to corresponding derived class ST: Everything from .fn table of class Base +was copied to .fn table of class Derived and so on. This was a recursive procedure, so in the end the whole +inheritance tree of derived class was squashed into derived class.

    +

    That means that any changes done to class Base after module initialization wouldn't affect class Derived:

    +
    +base = example.Base()
    +der = example.Derived()
    +> print(base.base_func)
    +function: 0x1367940
    +> getmetatable(base)[".fn"].new_func = function (x) return x -- Adding new function to class Base (to class, not to an instance!)
    +> print(base.new_func) -- Checking this function
    +function
    +> print(der.new_func) -- Wouldn't work. Derived doesn't check Base any more.
    +nil
    +>
    +
    +

    This behaviour was changed. Now unless -squash-bases option is provided, Derived store a list of it's bases and if some symbol is not found in it's own service tables +then its bases are searched for it. Option -squash-bases will effectively return old behaviour. +

    +> print(der.new_func) -- Now it works
    +function
    +>
    +
    + +

    27.4 Typemaps

    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

    -

    26.4.1 What is a typemap?

    +

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

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

    26.4.2 Using typemaps

    +

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

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

    -

    26.4.3 Typemaps and arrays

    +

    27.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 @@ -1359,7 +1624,7 @@ extern void sort_double(double* arr, int len); 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.

    +

    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 %apply in the correct manner.

    The wrapper file below, shows both the use of carrays as well as the use of the typemap to wrap arrays.

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

    -

    26.4.4 Typemaps and pointer-pointer functions

    +

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

    @@ -1441,7 +1706,7 @@ int Create_Math(iMath** pptr); // its creator (assume it mallocs) ptr=nil -- the iMath* will be GC'ed as normal -

    26.5 Writing typemaps

    +

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

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

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

    -

    26.5.1 Typemaps you can write

    +

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

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

    26.5.2 SWIG's Lua-C API

    +

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

    @@ -1512,7 +1777,7 @@ This macro, when called within the context of a SWIG wrapped function, will disp
    Similar to SWIG_fail_arg, except that it will display the swig_type_info information instead.
    -

    26.6 Customization of your Bindings

    +

    27.6 Customization of your Bindings

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

    26.6.1 Writing your own custom wrappers

    +

    27.6.1 Writing your own custom wrappers

    @@ -1540,7 +1805,7 @@ int native_function(lua_State*L) // my native code The %native directive in the above example, tells SWIG that there is a function int native_function(lua_State*L); which is to be added into the module under the name 'my_func'. SWIG will not add any wrapper for this function, beyond adding it into the function table. How you write your code is entirely up to you.

    -

    26.6.2 Adding additional Lua code

    +

    27.6.2 Adding additional Lua code

    @@ -1578,7 +1843,7 @@ Good uses for this feature is adding of new code, or writing helper functions to See Examples/lua/arrays for an example of this code.

    -

    26.7 Details on the Lua binding

    +

    27.7 Details on the Lua binding

    @@ -1589,7 +1854,7 @@ See Examples/lua/arrays for an example of this code.

    -

    26.7.1 Binding global data into the module.

    +

    27.7.1 Binding global data into the module.

    @@ -1649,7 +1914,7 @@ end

    That way when you call 'a=example.Foo', the interpreter looks at the table 'example' sees that there is no field 'Foo' and calls __index. This will in turn check in '.get' table and find the existence of 'Foo' and then return the value of the C function call 'Foo_get()'. Similarly for the code 'example.Foo=10', the interpreter will check the table, then call the __newindex which will then check the '.set' table and call the C function 'Foo_set(10)'.

    -

    26.7.2 Userdata and Metatables

    +

    27.7.2 Userdata and Metatables

    @@ -1729,7 +1994,7 @@ Note: Both the opaque structures (like the FILE*) and normal wrapped classes/str

    Note: Operator overloads are basically done in the same way, by adding functions such as '__add' & '__call' to the class' metatable. The current implementation is a bit rough as it will add any member function beginning with '__' into the metatable too, assuming its an operator overload.

    -

    26.7.3 Memory management

    +

    27.7.3 Memory management

    diff --git a/Doc/Manual/Modula3.html b/Doc/Manual/Modula3.html index 065313fa2..0bf9f2995 100644 --- a/Doc/Manual/Modula3.html +++ b/Doc/Manual/Modula3.html @@ -5,7 +5,7 @@ -

    27 SWIG and Modula-3

    +

    28 SWIG and Modula-3

      @@ -45,7 +45,7 @@

      -This chapter describes SWIG's support of +This chapter describes SWIG's support for Modula-3. You should be familiar with the basics @@ -54,7 +54,7 @@ especially typemaps.

      -

      27.1 Overview

      +

      28.1 Overview

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

      27.1.1 Motivation

      +

      28.1.1 Motivation

      @@ -109,7 +109,7 @@ into exceptions.

      If the library API is ill designed -writing appropriate typemaps can be still time-consuming. +writing appropriate typemaps can still be time-consuming. E.g. C programmers are very creative to work-around missing data types like (real) enumerations and sets. You should turn such work-arounds back to the Modula-3 way @@ -120,21 +120,21 @@ otherwise you lose static safety and consistency. Without SWIG you would probably never consider trying to call C++ libraries from Modula-3, but with SWIG this is becomes feasible. SWIG can generate C wrappers to C++ functions and object methods -that may throw exceptions, and then wrap these C wrappers for Module-3. +that may throw exceptions, and then wrap these C wrappers for Modula-3. To make it complete you can then hide the C interface with Modula-3 classes and exceptions.

      SWIG allows you to call C and C++ libraries from Modula-3 (even with call back -functions), but it doesn't allow you to easily integrate a Module-3 module into +functions), but it doesn't allow you to easily integrate a Modula-3 module into a C/C++ project.

      -

      27.2 Conception

      +

      28.2 Conception

      -

      27.2.1 Interfaces to C libraries

      +

      28.2.1 Interfaces to C libraries

      @@ -283,7 +283,7 @@ and the principal type must be renamed (%typemap).

      -

      27.2.2 Interfaces to C++ libraries

      +

      28.2.2 Interfaces to C++ libraries

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

      -

      27.3 Preliminaries

      +

      28.3 Preliminaries

      -

      27.3.1 Compilers

      +

      28.3.1 Compilers

      @@ -400,7 +400,7 @@ For testing examples I use Critical Mass cm3.

      -

      27.3.2 Additional Commandline Options

      +

      28.3.2 Additional Commandline Options

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

      27.4 Modula-3 typemaps

      +

      28.4 Modula-3 typemaps

      -

      27.4.1 Inputs and outputs

      +

      28.4.1 Inputs and outputs

      @@ -694,7 +694,7 @@ consist of the following parts: -

      27.4.2 Subranges, Enumerations, Sets

      +

      28.4.2 Subranges, Enumerations, Sets

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

      -

      27.4.3 Objects

      +

      28.4.3 Objects

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

      -

      27.4.4 Imports

      +

      28.4.4 Imports

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

    -

    27.4.5 Exceptions

    +

    28.4.5 Exceptions

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

    -

    27.4.6 Example

    +

    28.4.6 Example

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

    27.5 More hints to the generator

    +

    28.5 More hints to the generator

    -

    27.5.1 Features

    +

    28.5.1 Features

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

    27.5.2 Pragmas

    +

    28.5.2 Pragmas

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

    27.6 Remarks

    +

    28.6 Remarks

      diff --git a/Doc/Manual/Modules.html b/Doc/Manual/Modules.html index 70b0f1181..551fd0750 100644 --- a/Doc/Manual/Modules.html +++ b/Doc/Manual/Modules.html @@ -6,7 +6,7 @@ -

      15 Working with Modules

      +

      16 Working with Modules

        @@ -23,7 +23,7 @@ -

        15.1 Modules Introduction

        +

        16.1 Modules Introduction

        @@ -77,7 +77,7 @@ where you want to create a collection of modules. Each module in the collection is created via separate invocations of SWIG.

        -

        15.2 Basics

        +

        16.2 Basics

        @@ -130,7 +130,7 @@ public:

        To create the wrapper properly, module derived_module needs to know about the base class and that its interface is covered in another module. The -line %import "base_module.i" lets SWIG know exactly that. Oftentimes +line %import "base_module.i" lets SWIG know exactly that. Often the .h file is passed to %import instead of the .i, which unfortunately doesn't work for all language modules. For example, Python requires the name of module that the base class exists in so that the proxy classes can fully inherit the @@ -176,7 +176,7 @@ in parallel from multiple threads as SWIG provides no locking - for more on that issue, read on.

        -

        15.3 The SWIG runtime code

        +

        16.3 The SWIG runtime code

        @@ -242,7 +242,7 @@ can peacefully coexist. So the type structures are separated by the is empty. Only modules compiled with the same pair will share type information.

        -

        15.4 External access to the runtime

        +

        16.4 External access to the runtime

        As described in The run-time type checker, @@ -279,7 +279,7 @@ SWIG_TYPE_TABLE to be the same as the module whose types you are trying to access.

        -

        15.5 A word of caution about static libraries

        +

        16.5 A word of caution about static libraries

        @@ -290,7 +290,7 @@ into it. This is very often NOT what you want and it can lead to unexpect behavior. When working with dynamically loadable modules, you should try to work exclusively with shared libraries.

        -

        15.6 References

        +

        16.6 References

        @@ -298,7 +298,7 @@ Due to the complexity of working with shared libraries and multiple modules, it an outside reference. John Levine's "Linkers and Loaders" is highly recommended.

        -

        15.7 Reducing the wrapper file size

        +

        16.7 Reducing the wrapper file size

        diff --git a/Doc/Manual/Mzscheme.html b/Doc/Manual/Mzscheme.html index 3b49a2974..40173d720 100644 --- a/Doc/Manual/Mzscheme.html +++ b/Doc/Manual/Mzscheme.html @@ -8,7 +8,7 @@ -

        28 SWIG and MzScheme/Racket

        +

        29 SWIG and MzScheme/Racket

          @@ -24,7 +24,7 @@

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

          28.1 Creating native structures

          +

          29.1 Creating native structures

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

        -

        28.2 Simple example

        +

        29.2 Simple example

        @@ -166,7 +166,7 @@ Some points of interest:

      • The above requests mzc to create an extension using the CGC garbage-collector. The alternative -- the 3m collector -- has generally better performance, but work is still required for SWIG to emit code which is compatible with it.
      -

      28.3 External documentation

      +

      29.3 External documentation

      diff --git a/Doc/Manual/Ocaml.html b/Doc/Manual/Ocaml.html index ba8aa5fa9..ec46d6e50 100644 --- a/Doc/Manual/Ocaml.html +++ b/Doc/Manual/Ocaml.html @@ -6,7 +6,7 @@ -

      29 SWIG and Ocaml

      +

      30 SWIG and Ocaml

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

        -

        29.1 Preliminaries

        +

        30.1 Preliminaries

        @@ -99,7 +99,7 @@ file Examples/Makefile illustrate how to compile and link SWIG modules that will be loaded dynamically. This has only been tested on Linux so far.

        -

        29.1.1 Running SWIG

        +

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

        -

        29.1.2 Compiling the code

        +

        30.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,12 +158,12 @@ the user more freedom with respect to custom typing.

      -

      29.1.3 The camlp4 module

      +

      30.1.3 The camlp4 module

      The camlp4 module (swigp4.ml -> swigp4.cmo) contains a simple rewriter which -makes C++ code blend more seamlessly with objective caml code. It's use is +makes C++ code blend more seamlessly with objective caml code. Its use is optional, but encouraged. The source file is included in the Lib/ocaml directory of the SWIG source distribution. You can checkout this file with "swig -ocaml -co swigp4.ml". You should compile the file with @@ -234,7 +234,7 @@ let b = C_string (getenv "PATH") -

      29.1.4 Using your module

      +

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

      -

      29.1.5 Compilation problems and compiling with C++

      +

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

      -

      29.2 The low-level Ocaml/C interface

      +

      30.2 The low-level Ocaml/C interface

      @@ -310,7 +310,7 @@ type c_obj =

    • caml_val_ptr receives a void * and returns a c_obj.
    • caml_val_bool receives a C int and returns a c_obj representing - it's bool value.
    • + its bool value.
    • caml_val_(u)?(char|short|int|long|float|double) receives an appropriate C value and returns a c_obj representing it.
    • caml_val_string receives a char * and returns a string value.
    • @@ -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.

      -

      29.2.1 The generated module

      +

      30.2.1 The generated module

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

      29.2.2 Enums

      +

      30.2.2 Enums

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

      -

      29.2.2.1 Enum typing in Ocaml

      +

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

      -

      29.2.3 Arrays

      +

      30.2.3 Arrays

      -

      29.2.3.1 Simple types of bounded arrays

      +

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

      -

      29.2.3.2 Complex and unbounded arrays

      +

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

      -

      29.2.3.3 Using an object

      +

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

      -

      29.2.3.4 Example typemap for a function taking float * and int

      +

      30.2.3.4 Example typemap for a function taking float * and int

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

      29.2.4 C++ Classes

      +

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

      -

      29.2.4.1 STL vector and string Example

      +

      30.2.4.1 STL vector and string Example

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

      29.2.4.2 C++ Class Example

      +

      30.2.4.2 C++ Class Example

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

      29.2.4.3 Compiling the example

      +

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

      29.2.4.4 Sample Session

      +

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

      -

      29.2.5 Director Classes

      +

      30.2.5 Director Classes

      -

      29.2.5.1 Director Introduction

      +

      30.2.5.1 Director Introduction

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

      -

      29.2.5.2 Overriding Methods in Ocaml

      +

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

      -

      29.2.5.3 Director Usage Example

      +

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

      -

      29.2.5.4 Creating director objects

      +

      30.2.5.4 Creating director objects

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

      -

      29.2.5.5 Typemaps for directors, directorin, directorout, directorargout

      +

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

      -

      29.2.5.6 directorin typemap

      +

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

      -

      29.2.5.7 directorout typemap

      +

      30.2.5.7 directorout typemap

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

      -

      29.2.5.8 directorargout typemap

      +

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

      -

      29.2.6 Exceptions

      +

      30.2.6 Exceptions

      diff --git a/Doc/Manual/Octave.html b/Doc/Manual/Octave.html index 3229299d5..bc6873c4b 100644 --- a/Doc/Manual/Octave.html +++ b/Doc/Manual/Octave.html @@ -8,7 +8,7 @@ -

      30 SWIG and Octave

      +

      31 SWIG and Octave

        @@ -55,18 +55,15 @@ More information can be found at O Also, there are a dozen or so examples in the Examples/octave directory, and hundreds in the test suite (Examples/test-suite and Examples/test-suite/octave).

        -

        30.1 Preliminaries

        +

        31.1 Preliminaries

        -The SWIG implemention was first based on Octave 2.9.12, so this is the minimum version required. Testing has only been done on Linux. +As of SWIG 3.0.0, the Octave module has been tested with Octave versions 3.0.5, 3.2.4, 3.4.3, 3.6.4, and 3.8.0. +Use of Octave versions older than 3.x.x is not recommended, as these versions are no longer tested with SWIG.

        -

        -As of SWIG 2.0.5, the Octave module should work with Octave versions 3.0.5, 3.2.4, and 3.4.0. -

        - -

        30.2 Running SWIG

        +

        31.2 Running SWIG

        @@ -74,7 +71,7 @@ Let's start with a very simple SWIG interface file, example.i:

        -%module example
        +%module swigexample
         %{
         #include "example.h"
         %}
        @@ -95,10 +92,10 @@ The -c++ option is also required when wrapping C++ code:
         
        $ swig -octave -c++ -o example_wrap.cpp example.i 

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

        +

        31.2.1 Command-line options

        @@ -110,21 +107,18 @@ Options specific to the Octave module are:

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

        -The -global and -noglobal options determine whether the Octave module will load all symbols into the global namespace in addition to the global namespace. 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

        +

        31.2.2 Compiling a dynamic module

        @@ -138,7 +132,7 @@ $ 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.

      @@ -146,12 +140,12 @@ $ mkoctfile example_wrap.cpp 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 "swigexample.oct", which contains the compiled extension module. Loading it into Octave is then a matter of invoking

      -
      octave:1> example
      +
      octave:1> swigexample
      -

      30.2.3 Using your module

      +

      31.2.3 Using your module

      @@ -160,75 +154,42 @@ Assuming all goes well, you will be able to do this:

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

      30.3 A tour of basic C/C++ wrapping

      +

      31.3 A tour of basic C/C++ wrapping

      -

      30.3.1 Modules

      +

      31.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 swigexample", then in Octave everything in the module will be accessible under "swigexample", 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 swigexample, it will try to find the ".m" or ".oct" file that defines the function "swigexample". You therefore need to make sure that "swigexample.oct" is in Octave's search path, which can be specified with the environment variable "OCTAVE_PATH".

      -An Octave module takes three options, -global, -noglobal, and -globals, which behave the same as the corresponding swig command-line options. -Here are some example usages: +To load an Octave module, simply type its name:

      -
      -octave:1> example -help
      -usage: example [-global|-noglobal] [-globals <name>]
      -octave:2> example -global
      -octave:3> gcd(4,6)
      +
      +octave:1> swigexample;
      +octave:2> gcd(4,6)
       ans =  2
      -octave:4> cvar.Foo
      -ans =  3
      -octave:5> cvar.Foo=4;
      -octave:6> cvar.Foo
      -ans =  4
      -
      -
      -
      -octave:1> example -noglobal
      -octave:2> gcd(6,9)
      -ans =  3
       octave:3> cvar.Foo
      -error: `cvar' undefined near line 3 column 1
      -octave:3> example.cvar.Foo
      -ans =  3
      -
      -
      -
      -octave:1> example -globals mycvar
      -octave:2> cvar.Foo
      -error: `cvar' undefined near line 2 column 1
      -octave:2> mycvar.Foo
      -ans =  3
      -
      - -

      - It is also possible to rename the module / global variables namespaces with an assignment, as in:
      -

      -octave:1> example
      -octave:2> c=example;
      -octave:3> c.gcd(10,4)
      -ans =  2
      -octave:4> some_vars = cvar;
      -octave:5> some_vars.Foo
       ans =  3
      +octave:4> cvar.Foo=4;
      +octave:5> cvar.Foo
      +ans =  4
       

      @@ -238,64 +199,64 @@ If the module is also used in the base context, however, it must first be loaded

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

      30.3.2 Functions

      +

      31.3.2 Functions

      Global functions are wrapped as new Octave built-in functions. For example,

      -
      %module example
      +      
      %module swigexample
       int fact(int n); 

      - creates a built-in function example.fact(n) that works exactly like you think it does: + creates a built-in function swigexample.fact(n) that works exactly like you think it does:

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

      30.3.3 Global variables

      +

      31.3.3 Global variables

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

      -
      %module example
      +
      %module swigexample
       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.

      -
      octave:1> example;
      -octave:2> c=example.cvar.Foo
      +    
      octave:1> swigexample;
      +octave:2> c=swigexample.cvar.Foo
       c =  3
      -octave:3> example.cvar.Foo=4;
      +octave:3> swigexample.cvar.Foo=4;
       octave:4> c
       c =  3
      -octave:5> example.cvar.Foo
      +octave:5> swigexample.cvar.Foo
       ans =  4

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

      -
      %module example
      +    
      %module swigexample
       %immutable;
       extern double Foo;
       %mutable;
      @@ -305,8 +266,8 @@ extern double Foo;
            SWIG will allow the reading of Foo but when a set attempt is made, an error function will be called. 
       

      -
      octave:1> example
      -octave:2> example.Foo=4
      +    
      octave:1> swigexample
      +octave:2> swigexample.Foo=4
       error: attempt to set immutable member variable
       error: assignment failed, or no method for `swig_type = scalar'
       error: evaluating assignment expression near line 2, column 12 
      @@ -315,19 +276,19 @@ error: evaluating assignment expression near line 2, column 12
      It is possible to add new functions or variables to the module. This also allows the user to rename/remove existing functions and constants (but not linked variables, mutable or immutable). Therefore users are recommended to be careful when doing so.

      -
      octave:1> example;
      -octave:2> example.PI=3.142;
      -octave:3> example.PI
      +    
      octave:1> swigexample;
      +octave:2> swigexample.PI=3.142;
      +octave:3> swigexample.PI
       ans =  3.1420 
      -

      30.3.4 Constants and enums

      +

      31.3.4 Constants and enums

      Because Octave doesn't really have the concept of constants, C/C++ constants are not really constant in Octave. They are actually just a copy of the value into the Octave interpreter. Therefore they can be changed just as any other value. For example given some constants:

      -
      %module example
      +    
      %module swigexample
       %constant int ICONST=42;
       #define    SCONST      "Hello World"
       enum Days{SUNDAY,MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY};
      @@ -337,12 +298,12 @@ enum Days{SUNDAY,MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY};
           This is 'effectively' converted into the following Octave code: 
       

      -
      example.ICONST=42
      -example.SCONST="Hello World"
      -example.SUNDAY=0
      +    
      swigexample.ICONST=42
      +swigexample.SCONST="Hello World"
      +swigexample.SUNDAY=0
       .... 
      -

      30.3.5 Pointers

      +

      31.3.5 Pointers

      @@ -350,7 +311,7 @@ example.SUNDAY=0 C/C++ pointers are fully supported by SWIG. Furthermore, SWIG has no problem working with incomplete type information. Given a wrapping of the <file.h> interface:

      -
      %module example
      +
      %module swigexample
       FILE *fopen(const char *filename, const char *mode);
       int fputs(const char *, FILE *);
       int fclose(FILE *);
      @@ -361,18 +322,18 @@ When wrapped, you will be able to use the functions in a natural way from Octave
       

      -octave:1> example;
      -octave:2> f=example.fopen("w","junk");
      -octave:3> example.fputs("Hello world",f);
      -octave:4> example.fclose(f);
      +octave:1> swigexample;
      +octave:2> f=swigexample.fopen("w","junk");
      +octave:3> swigexample.fputs("Hello world",f);
      +octave:4> swigexample.fclose(f);
       

      - Simply printing the value of a wrapped C++ type will print it's typename. E.g., + Simply printing the value of a wrapped C++ type will print its typename. E.g.,

      -
      octave:1> example;
      -octave:2> f=example.fopen("junk","w");
      +    
      octave:1> swigexample;
      +octave:2> f=swigexample.fopen("junk","w");
       octave:3> f
       f =
       
      @@ -384,12 +345,12 @@ f =
           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 and structs (see below).
       

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

      30.3.6 Structures and C++ classes

      +

      31.3.6 Structures and C++ classes

      @@ -407,8 +368,8 @@ For each wrapped structure and class, a swig_ref will be exposed that h

      -
      octave:1> example;
      -octave:2> p=example.Point();
      +      
      octave:1> swigexample;
      +octave:2> p=swigexample.Point();
       octave:3> p.x=3;
       octave:4> p.y=5;
       octave:5> p.x, p.y
      @@ -442,9 +403,9 @@ public:
       can be used from Octave like this
       

      -
      octave:1> example;
      -octave:2> p1=example.Point(3,5);
      -octave:3> p2=example.Point(1,2);
      +      
      octave:1> swigexample;
      +octave:2> p1=swigexample.Point(3,5);
      +octave:3> p2=swigexample.Point(1,2);
       octave:4> p1.distance(p2)
       ans =  3.6056
       
      @@ -524,7 +485,7 @@ ans = 1 Depending on the ownership setting of a swig_ref, it may call C++ destructors when its reference count goes to zero. See the section on memory management below for details.

      -

      30.3.7 C++ inheritance

      +

      31.3.7 C++ inheritance

      @@ -533,7 +494,7 @@ This information contains the full class hierarchy. When an indexing operation ( the tree is walked to find a match in the current class as well as any of its bases. The lookup is then cached in the swig_ref.

      -

      30.3.8 C++ overloaded functions

      +

      31.3.8 C++ overloaded functions

      @@ -543,7 +504,7 @@ The dispatch function selects which overload to call (if any) based on the passe typecheck typemaps are used to analyze each argument, as well as assign precedence. See the chapter on typemaps for details.

      -

      30.3.9 C++ operators

      +

      31.3.9 C++ operators

      @@ -647,7 +608,7 @@ On the C++ side, the default mappings are as follows: 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

      +

      31.3.10 Class extension with %extend

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

      -

      30.3.11 C++ templates

      +

      31.3.11 C++ templates

      @@ -685,7 +646,7 @@ C++ class and function templates are fully supported as in other modules, in tha For example, function templates can be instantiated as follows:

      -
      %module example
      +
      %module swigexample
       %inline {
        template<class __scalar>
          __scalar mul(__scalar a,__scalar b) {
      @@ -713,7 +674,7 @@ ans =  22 + 46i
       Similarly, class templates can be instantiated as in the following example,
       

      -
      %module example
      +
      %module swigexample
       %include <std_complex.i>
       %include <std_string.i>
       %inline {
      @@ -754,14 +715,14 @@ ans =
       
      -

      30.3.12 C++ Smart Pointers

      +

      31.3.12 C++ Smart Pointers

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

      -

      30.3.13 Directors (calling Octave from C++ code)

      +

      31.3.13 Directors (calling Octave from C++ code)

      @@ -842,14 +803,14 @@ c-side routine called octave-side routine called

      -

      30.3.14 Threads

      +

      31.3.14 Threads

      The use of threads in wrapped Director code is not supported; i.e., an Octave-side implementation of a C++ class must be called from the Octave interpreter's thread. Anything fancier (apartment/queue model, whatever) is left to the user. Without anything fancier, this amounts to the limitation that Octave must drive the module... like, for example, an optimization package that calls Octave to evaluate an objective function.

      -

      30.3.15 Memory management

      +

      31.3.15 Memory management

      @@ -883,14 +844,14 @@ The %newobject directive may be used to control this behavior for pointers retur In the case where one wishes for the C++ side to own an object that was created in Octave (especially a Director object), one can use the __disown() method to invert this logic. Then letting the Octave reference count go to zero will not destroy the object, but destroying the object will invalidate the Octave-side object if it still exists (and call destructors of other C++ bases in the case of multiple inheritance/subclass()'ing).

      -

      30.3.16 STL support

      +

      31.3.16 STL support

      Various STL library files are provided for wrapping STL containers.

      -

      30.3.17 Matrix typemaps

      +

      31.3.17 Matrix typemaps

      diff --git a/Doc/Manual/Perl5.html b/Doc/Manual/Perl5.html index 0a4b61bd5..010eb48df 100644 --- a/Doc/Manual/Perl5.html +++ b/Doc/Manual/Perl5.html @@ -6,7 +6,7 @@ -

      31 SWIG and Perl5

      +

      32 SWIG and Perl5

      @@ -87,7 +96,7 @@ later. We're no longer testing regularly with older versions, but Perl 5.6 seems to mostly work, while older versions don't.

      -

      31.1 Overview

      +

      32.1 Overview

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

      -

      31.2 Preliminaries

      +

      32.2 Preliminaries

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

      -

      31.2.1 Getting the right header files

      +

      32.2.1 Getting the right header files

      @@ -165,13 +174,13 @@ $ perl -e 'use Config; print "$Config{archlib}\n";'

      -

      31.2.2 Compiling a dynamic module

      +

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

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

      -

      31.2.3 Building a dynamic module with MakeMaker

      +

      32.2.3 Building a dynamic module with MakeMaker

      @@ -232,7 +241,7 @@ the preferred approach to compilation. More information about MakeMaker can be found in "Programming Perl, 2nd ed." by Larry Wall, Tom Christiansen, and Randal Schwartz.

      -

      31.2.4 Building a static version of Perl

      +

      32.2.4 Building a static version of Perl

      @@ -301,7 +310,7 @@ added to it. Depending on your machine, you may need to link with additional libraries such as -lsocket, -lnsl, -ldl, etc.

      -

      31.2.5 Using the module

      +

      32.2.5 Using the module

      @@ -454,7 +463,7 @@ system configuration (this requires root access and you will need to read the man pages).

      -

      31.2.6 Compilation problems and compiling with C++

      +

      32.2.6 Compilation problems and compiling with C++

      @@ -484,8 +493,8 @@ Solaris, you often need to add an extra library -lCrun like this:

       $ swig -c++ -perl example.i
      -$ CC -c example.cxx
      -$ CC -c example_wrap.cxx -I/usr/lib/perl/5.14/i386-linux/CORE
      +$ CC -Kpic -c example.cxx
      +$ CC -Kpic -c example_wrap.cxx -I/usr/lib/perl/5.14/i386-linux/CORE
       $ CC -shared example.o example_wrap.o -o example.so -lCrun
       
      @@ -597,7 +606,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.

      -

      31.2.7 Compiling for 64-bit platforms

      +

      32.2.7 Compiling for 64-bit platforms

      @@ -624,7 +633,7 @@ also introduce problems on platforms that support more than one linking standard (e.g., -o32 and -n32 on Irix).

      -

      31.3 Building Perl Extensions under Windows

      +

      32.3 Building Perl Extensions under Windows

      @@ -635,7 +644,7 @@ section assumes you are using SWIG with Microsoft Visual C++ although the procedure may be similar with other compilers.

      -

      31.3.1 Running SWIG from Developer Studio

      +

      32.3.1 Running SWIG from Developer Studio

      @@ -698,7 +707,7 @@ print "$a\n";

      -

      31.3.2 Using other compilers

      +

      32.3.2 Using other compilers

      @@ -706,7 +715,7 @@ SWIG is known to work with Cygwin and may work with other compilers on Windows. For general hints and suggestions refer to the Windows chapter.

      -

      31.4 The low-level interface

      +

      32.4 The low-level interface

      @@ -716,7 +725,7 @@ can be used to control your application. However, it is also used to construct more user-friendly proxy classes as described in the next section.

      -

      31.4.1 Functions

      +

      32.4.1 Functions

      @@ -739,7 +748,7 @@ use example; $a = &example::fact(2);

      -

      31.4.2 Global variables

      +

      32.4.2 Global variables

      @@ -809,7 +818,7 @@ extern char *path; // Declared later in the input

      -

      31.4.3 Constants

      +

      32.4.3 Constants

      @@ -849,7 +858,7 @@ print example::FOO,"\n";

      -

      31.4.4 Pointers

      +

      32.4.4 Pointers

      @@ -958,7 +967,7 @@ as XS and xsubpp. Given the advancement of the SWIG typesystem and the SWIG and XS, this is no longer supported.

      -

      31.4.5 Structures

      +

      32.4.5 Structures

      @@ -1092,7 +1101,7 @@ void Bar_f_set(Bar *b, Foo *val) {

      -

      31.4.6 C++ classes

      +

      32.4.6 C++ classes

      @@ -1157,7 +1166,7 @@ provides direct access to C++ objects. A higher level interface using Perl prox can be built using these low-level accessors. This is described shortly.

      -

      31.4.7 C++ classes and type-checking

      +

      32.4.7 C++ classes and type-checking

      @@ -1193,7 +1202,7 @@ If necessary, the type-checker also adjusts the value of the pointer (as is nece multiple inheritance is used).

      -

      31.4.8 C++ overloaded functions

      +

      32.4.8 C++ overloaded functions

      @@ -1237,7 +1246,7 @@ example::Spam_foo_d($s,3.14); Please refer to the "SWIG Basics" chapter for more information.

      -

      31.4.9 Operators

      +

      32.4.9 Operators

      @@ -1264,7 +1273,7 @@ The following C++ operators are currently supported by the Perl module:

    • operator or
    • -

      31.4.10 Modules and packages

      +

      32.4.10 Modules and packages

      @@ -1359,7 +1368,7 @@ print Foo::fact(4),"\n"; # Call a function in package FooBar

      --> -

      31.5 Input and output parameters

      +

      32.5 Input and output parameters

      @@ -1578,7 +1587,7 @@ print "$c\n"; Note: The REFERENCE feature is only currently supported for numeric types (integers and floating point).

      -

      31.6 Exception handling

      +

      32.6 Exception handling

      @@ -1743,7 +1752,7 @@ This is still supported, but it is deprecated. The newer %exception di functionality, but it has additional capabilities that make it more powerful.

      -

      31.7 Remapping datatypes with typemaps

      +

      32.7 Remapping datatypes with typemaps

      @@ -1760,7 +1769,7 @@ Typemaps are only used if you want to change some aspect of the primitive C-Perl interface.

      -

      31.7.1 A simple typemap example

      +

      32.7.1 A simple typemap example

      @@ -1864,7 +1873,7 @@ example::count("e","Hello World");

      -

      31.7.2 Perl5 typemaps

      +

      32.7.2 Perl5 typemaps

      @@ -1969,7 +1978,7 @@ Return of C++ member data (all languages). Check value of input parameter.

      -

      31.7.3 Typemap variables

      +

      32.7.3 Typemap variables

      @@ -2040,7 +2049,7 @@ properly assigned. The Perl name of the wrapper function being created.

      -

      31.7.4 Useful functions

      +

      32.7.4 Useful functions

      @@ -2109,7 +2118,7 @@ int sv_isa(SV *, char *0;

      -

      31.8 Typemap Examples

      +

      32.8 Typemap Examples

      @@ -2118,7 +2127,7 @@ might look at the files "perl5.swg" and "typemaps.i" in the SWIG library.

      -

      31.8.1 Converting a Perl5 array to a char **

      +

      32.8.1 Converting a Perl5 array to a char **

      @@ -2210,7 +2219,7 @@ print @$b,"\n"; # Print it out

      -

      31.8.2 Return values

      +

      32.8.2 Return values

      @@ -2239,7 +2248,7 @@ can be done using the EXTEND() macro as in: }

      -

      31.8.3 Returning values from arguments

      +

      32.8.3 Returning values from arguments

      @@ -2293,7 +2302,7 @@ print "multout(7,13) = @r\n"; ($x,$y) = multout(7,13);

      -

      31.8.4 Accessing array structure members

      +

      32.8.4 Accessing array structure members

      @@ -2356,7 +2365,7 @@ the "in" typemap in the previous section would be used to convert an to copy the converted array into a C data structure.

      -

      31.8.5 Turning Perl references into C pointers

      +

      32.8.5 Turning Perl references into C pointers

      @@ -2421,7 +2430,7 @@ print "$c\n";

      -

      31.8.6 Pointer handling

      +

      32.8.6 Pointer handling

      @@ -2500,7 +2509,7 @@ For example:

      -

      31.9 Proxy classes

      +

      32.9 Proxy classes

      @@ -2516,7 +2525,7 @@ to the underlying code. This section describes the implementation details of the proxy interface.

      -

      31.9.1 Preliminaries

      +

      32.9.1 Preliminaries

      @@ -2538,7 +2547,7 @@ SWIG creates a collection of high-level Perl wrappers. In your scripts, you wil high level wrappers. The wrappers, in turn, interact with the low-level procedural module.

      -

      31.9.2 Structure and class wrappers

      +

      32.9.2 Structure and class wrappers

      @@ -2664,7 +2673,7 @@ $v->DESTROY();

      -

      31.9.3 Object Ownership

      +

      32.9.3 Object Ownership

      @@ -2751,7 +2760,7 @@ counting, garbage collection, or advanced features one might find in sophisticated languages.

      -

      31.9.4 Nested Objects

      +

      32.9.4 Nested Objects

      @@ -2804,7 +2813,7 @@ $p->{f}->{x} = 0.0; %${$p->{v}} = ( x=>0, y=>0, z=>0);

      -

      31.9.5 Proxy Functions

      +

      32.9.5 Proxy Functions

      @@ -2838,7 +2847,7 @@ This function replaces the original function, but operates in an identical manner.

      -

      31.9.6 Inheritance

      +

      32.9.6 Inheritance

      @@ -2914,7 +2923,7 @@ particular, inheritance of data members is extremely tricky (and I'm not even sure if it really works).

      -

      31.9.7 Modifying the proxy methods

      +

      32.9.7 Modifying the proxy methods

      @@ -2942,7 +2951,7 @@ public: }; -

      31.10 Adding additional Perl code

      +

      32.10 Adding additional Perl code

      @@ -2993,6 +3002,363 @@ set_transform($im, $a); +

      32.11 Cross language polymorphism

      + + +

      +Proxy classes provide a more natural, object-oriented way to access +extension classes. As described above, each proxy instance has an +associated C++ instance, and method calls to the proxy are passed to the +C++ instance transparently via C wrapper functions. +

      + +

      +This arrangement is asymmetric in the sense that no corresponding +mechanism exists to pass method calls down the inheritance chain from +C++ to Perl. In particular, if a C++ class has been extended in Perl +(by extending the proxy class), these extensions will not be visible +from C++ code. Virtual method calls from C++ are thus not able access +the lowest implementation in the inheritance chain. +

      + +

      +Changes have been made to SWIG to address this problem and +make the relationship between C++ classes and proxy classes more +symmetric. To achieve this goal, new classes called directors are +introduced at the bottom of the C++ inheritance chain. The job of the +directors is to route method calls correctly, either to C++ +implementations higher in the inheritance chain or to Perl +implementations lower in the inheritance chain. The upshot is that C++ +classes can be extended in Perl and from C++ these extensions look +exactly like native C++ classes. Neither C++ code nor Perl code needs +to know where a particular method is implemented: the combination of +proxy classes, director classes, and C wrapper functions takes care of +all the cross-language method routing transparently. +

      + +

      32.11.1 Enabling directors

      + + +

      +The director feature is disabled by default. To use directors you +must make two changes to the interface file. First, add the "directors" +option to the %module directive, like this: +

      + +
      +
      +%module(directors="1") modulename
      +
      +
      + +

      +Without this option no director code will be generated. Second, you +must use the %feature("director") directive to tell SWIG which classes +and methods should get directors. The %feature directive can be applied +globally, to specific classes, and to specific methods, like this: +

      + +
      +
      +// generate directors for all classes that have virtual methods
      +%feature("director");         
      +
      +// generate directors for all virtual methods in class Foo
      +%feature("director") Foo;      
      +
      +
      + +

      +You can use the %feature("nodirector") directive to turn off +directors for specific classes or methods. So for example, +

      + +
      +
      +%feature("director") Foo;
      +%feature("nodirector") Foo::bar;
      +
      +
      + +

      +will generate directors for all virtual methods of class Foo except +bar(). +

      + +

      +Directors can also be generated implicitly through inheritance. +In the following, class Bar will get a director class that handles +the methods one() and two() (but not three()): +

      + +
      +
      +%feature("director") Foo;
      +class Foo {
      +public:
      +    Foo(int foo);
      +    virtual void one();
      +    virtual void two();
      +};
      +
      +class Bar: public Foo {
      +public:
      +    virtual void three();
      +};
      +
      +
      + +

      +then at the Perl side you can define +

      + +
      +
      +use mymodule;
      +
      +package MyFoo;
      +use base 'mymodule::Foo';
      +
      +sub one {
      +  print "one from Perl\n";
      +}
      +
      +
      + + +

      32.11.2 Director classes

      + + + + + +

      +For each class that has directors enabled, SWIG generates a new class +that derives from both the class in question and a special +Swig::Director class. These new classes, referred to as director +classes, can be loosely thought of as the C++ equivalent of the Perl +proxy classes. The director classes store a pointer to their underlying +Perl object and handle various issues related to object ownership. +

      + +

      +For simplicity let's ignore the Swig::Director class and refer to the +original C++ class as the director's base class. By default, a director +class extends all virtual methods in the inheritance chain of its base +class (see the preceding section for how to modify this behavior). +Thus all virtual method calls, whether they originate in C++ or in +Perl via proxy classes, eventually end up in at the implementation in +the director class. The job of the director methods is to route these +method calls to the appropriate place in the inheritance chain. By +"appropriate place" we mean the method that would have been called if +the C++ base class and its extensions in Perl were seamlessly +integrated. That seamless integration is exactly what the director +classes provide, transparently skipping over all the messy extension API +glue that binds the two languages together. +

      + +

      +In reality, the "appropriate place" is one of only two possibilities: +C++ or Perl. Once this decision is made, the rest is fairly easy. If +the correct implementation is in C++, then the lowest implementation of +the method in the C++ inheritance chain is called explicitly. If the +correct implementation is in Perl, the Perl API is used to call the +method of the underlying Perl object (after which the usual virtual +method resolution in Perl automatically finds the right +implementation). +

      + +

      +Now how does the director decide which language should handle the method call? +The basic rule is to handle the method in Perl, unless there's a good +reason not to. The reason for this is simple: Perl has the most +"extended" implementation of the method. This assertion is guaranteed, +since at a minimum the Perl proxy class implements the method. If the +method in question has been extended by a class derived from the proxy +class, that extended implementation will execute exactly as it should. +If not, the proxy class will route the method call into a C wrapper +function, expecting that the method will be resolved in C++. The wrapper +will call the virtual method of the C++ instance, and since the director +extends this the call will end up right back in the director method. Now +comes the "good reason not to" part. If the director method were to blindly +call the Perl method again, it would get stuck in an infinite loop. We avoid this +situation by adding special code to the C wrapper function that tells +the director method to not do this. The C wrapper function compares the +pointer to the Perl object that called the wrapper function to the +pointer stored by the director. If these are the same, then the C +wrapper function tells the director to resolve the method by calling up +the C++ inheritance chain, preventing an infinite loop. +

      + +

      +One more point needs to be made about the relationship between director +classes and proxy classes. When a proxy class instance is created in +Perl, SWIG creates an instance of the original C++ class. +This is exactly what happens without directors and +is true even if directors are enabled for the particular class in +question. When a class derived from a proxy class is created, +however, SWIG then creates an instance of the corresponding C++ director +class. The reason for this difference is that user-defined subclasses +may override or extend methods of the original class, so the director +class is needed to route calls to these methods correctly. For +unmodified proxy classes, all methods are ultimately implemented in C++ +so there is no need for the extra overhead involved with routing the +calls through Perl. +

      + +

      32.11.3 Ownership and object destruction

      + + +

      +Memory management issues are slightly more complicated with directors +than for proxy classes alone. Perl instances hold a pointer to the +associated C++ director object, and the director in turn holds a pointer +back to a Perl object. By default, proxy classes own their C++ +director object and take care of deleting it when they are garbage +collected. +

      + +

      +This relationship can be reversed by calling the special +DISOWN() method of the proxy class. After calling this +method the director +class increments the reference count of the Perl object. When the +director class is deleted it decrements the reference count. Assuming no +outstanding references to the Perl object remain, the Perl object +will be destroyed at the same time. This is a good thing, since +directors and proxies refer to each other and so must be created and +destroyed together. Destroying one without destroying the other will +likely cause your program to segfault. +

      + +

      +Also note that due to the proxy implementation, the DESTROY() +method on directors can be called for several reasons, many of which +have little to do with the teardown of an object instance. To help +disambiguate this, a second argument is added to the DESTROY() +call when a C++ director object is being released. So, to avoid running +your clean-up code when an object is not really going away, or after it +has already been reclaimed, it is suggested that custom destructors in +Perl subclasses looks something like: +

      + +
      +
      +sub DESTROY {
      +  my($self, $final) = @_;
      +  if($final) {
      +    # real teardown code
      +  }
      +  shift->SUPER::DESTROY(@_);
      +}
      +
      +
      + + +

      32.11.4 Exception unrolling

      + + +

      +With directors routing method calls to Perl, and proxies routing them +to C++, the handling of exceptions is an important concern. By default, the +directors ignore exceptions that occur during method calls that are +resolved in Perl. To handle such exceptions correctly, it is necessary +to temporarily translate them into C++ exceptions. This can be done with +the %feature("director:except") directive. The following code should +suffice in most cases: +

      + +
      +
      +%feature("director:except") {
      +    if ($error != NULL) {
      +        throw Swig::DirectorMethodException();
      +    }
      +}
      +
      +
      + +

      +This code will check the Perl error state after each method call from +a director into Perl, and throw a C++ exception if an error occurred. +This exception can be caught in C++ to implement an error handler. +

      + +

      +It may be the case that a method call originates in Perl, travels up +to C++ through a proxy class, and then back into Perl via a director +method. If an exception occurs in Perl at this point, it would be nice +for that exception to find its way back to the original caller. This can +be done by combining a normal %exception directive with the +director:except handler shown above. Here is an example of a +suitable exception handler: +

      + +
      +
      +%exception {
      +    try { $action }
      +    catch (Swig::DirectorException &e) { SWIG_fail; }
      +}
      +
      +
      + +

      +The class Swig::DirectorException used in this example is actually a +base class of Swig::DirectorMethodException, so it will trap this +exception. Because the Perl error state is still set when +Swig::DirectorMethodException is thrown, Perl will register the +exception as soon as the C wrapper function returns. +

      + +

      32.11.5 Overhead and code bloat

      + + +

      +Enabling directors for a class will generate a new director method for +every virtual method in the class' inheritance chain. This alone can +generate a lot of code bloat for large hierarchies. Method arguments +that require complex conversions to and from target language types can +result in large director methods. For this reason it is recommended that +you selectively enable directors only for specific classes that are +likely to be extended in Perl and used in C++. +

      + +

      +Compared to classes that do not use directors, the call routing in the +director methods does add some overhead. In particular, at least one +dynamic cast and one extra function call occurs per method call from +Perl. Relative to the speed of Perl execution this is probably +completely negligible. For worst case routing, a method call that +ultimately resolves in C++ may take one extra detour through Perl in +order to ensure that the method does not have an extended Perl +implementation. This could result in a noticeable overhead in some cases. +

      + +

      +Although directors make it natural to mix native C++ objects with Perl +objects (as director objects) via a common base class pointer, one +should be aware of the obvious fact that method calls to Perl objects +will be much slower than calls to C++ objects. This situation can be +optimized by selectively enabling director methods (using the %feature +directive) for only those methods that are likely to be extended in +Perl. +

      + +

      32.11.6 Typemaps

      + + +

      +Typemaps for input and output of most of the basic types from director +classes have been written. These are roughly the reverse of the usual +input and output typemaps used by the wrapper code. The typemap +operation names are 'directorin', 'directorout', and 'directorargout'. +The director code does not currently use any of the other kinds of typemaps. +It is not clear at this point which kinds are appropriate and +need to be supported. +

      + + diff --git a/Doc/Manual/Php.html b/Doc/Manual/Php.html index 19ace7192..493c861f8 100644 --- a/Doc/Manual/Php.html +++ b/Doc/Manual/Php.html @@ -7,7 +7,7 @@ -

      32 SWIG and PHP

      +

      33 SWIG and PHP

        @@ -79,7 +79,7 @@ your extension into php directly, you will need the complete PHP source tree available.

        -

        32.1 Generating PHP Extensions

        +

        33.1 Generating PHP Extensions

        @@ -126,7 +126,7 @@ and it doesn't play nicely with package system. We don't recommend this approach, or provide explicit support for it.

        -

        32.1.1 Building a loadable extension

        +

        33.1.1 Building a loadable extension

        @@ -141,12 +141,12 @@ least work for Linux though): gcc -shared example_wrap.o -o example.so

      -

      32.1.2 Using PHP Extensions

      +

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

      @@ -156,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::

      @@ -164,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:

      @@ -172,7 +172,7 @@ attempts to do the dl() call for you: include("example.php"); -

      32.2 Basic PHP interface

      +

      33.2 Basic PHP interface

      @@ -183,7 +183,7 @@ other symbols unless care is taken to %rename them. At present SWIG doesn't have support for the namespace feature added in PHP 5.3.

      -

      32.2.1 Constants

      +

      33.2.1 Constants

      @@ -260,7 +260,7 @@ is treated as true by the if test, when the value of the intended constant would be treated as false!

      -

      32.2.2 Global Variables

      +

      33.2.2 Global Variables

      @@ -309,7 +309,7 @@ undefined. At this time SWIG does not support custom accessor methods.

      -

      32.2.3 Functions

      +

      33.2.3 Functions

      @@ -362,7 +362,7 @@ print $s; # The value of $s was not changed. --> -

      32.2.4 Overloading

      +

      33.2.4 Overloading

      @@ -418,7 +418,7 @@ taking the integer argument.

      --> -

      32.2.5 Pointers and References

      +

      33.2.5 Pointers and References

      @@ -503,7 +503,20 @@ echo "The sum $in1 + $in2 = $result\n"; Because PHP has a native concept of reference, it may seem more natural to the PHP developer to use references to pass pointers. To enable this, one needs to include phppointers.i which defines the -named typemap REFERENCE. +named typemap REF. +

      + +

      +Prior to SWIG 3.0, the REF typemaps relied on PHP's call-time +pass-by-reference, which was deprecated in PHP 5.3 and removed in PHP 5.4. +So if you use these REF typemaps, you should ensure that SWIG≥3.0 is +used to generate wrappers from your interface file. +

      + +

      +In case you write your own typemaps, SWIG supports an attribute called +byref: if you set that, then SWIG will make sure that the generated +wrapper function will want the input parameter as a reference.

      @@ -526,7 +539,7 @@ include("example.php");
       $in1 = 3;
       $in2 = 5;
       $result = 0;
      -add(&$in1,&$in2,&$result);
      +add($in1,$in2,$result);
       
       echo "The sum $in1 + $in2 = $result\n";
       ?>
      @@ -550,7 +563,7 @@ PHP in a number of ways: by using unset on an existing
       variable, or assigning NULL to a variable.
       

      -

      32.2.6 Structures and C++ classes

      +

      33.2.6 Structures and C++ classes

      @@ -611,7 +624,7 @@ Would be used in the following way from PHP5: Member variables and methods are accessed using the -> operator.

      -

      32.2.6.1 Using -noproxy

      +

      33.2.6.1 Using -noproxy

      @@ -637,7 +650,7 @@ Complex_im_set($obj,$d); Complex_im_get($obj);

      -

      32.2.6.2 Constructors and Destructors

      +

      33.2.6.2 Constructors and Destructors

      @@ -678,7 +691,7 @@ the programmer can either reassign the variable or call unset($v)

      -

      32.2.6.3 Static Member Variables

      +

      33.2.6.3 Static Member Variables

      @@ -705,7 +718,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";
       
       
      @@ -718,10 +731,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"; -

      32.2.6.4 Static Member Functions

      +

      33.2.6.4 Static Member Functions

      @@ -743,7 +756,7 @@ Ko::threats(); -

      32.2.7 PHP Pragmas, Startup and Shutdown code

      +

      33.2.7 PHP Pragmas, Startup and Shutdown code

      @@ -831,7 +844,7 @@ The %rinit and %rshutdown statements are very similar but inse into the request init (PHP_RINIT_FUNCTION) and request shutdown (PHP_RSHUTDOWN_FUNCTION) code respectively.

      -

      32.3 Cross language polymorphism

      +

      33.3 Cross language polymorphism

      @@ -866,7 +879,7 @@ wrapper functions takes care of all the cross-language method routing transparently.

      -

      32.3.1 Enabling directors

      +

      33.3.1 Enabling directors

      @@ -895,9 +908,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; @@ -958,7 +968,7 @@ class MyFoo extends Foo { -

      32.3.2 Director classes

      +

      33.3.2 Director classes

      @@ -1038,7 +1048,7 @@ so there is no need for the extra overhead involved with routing the calls through PHP.

      -

      32.3.3 Ownership and object destruction

      +

      33.3.3 Ownership and object destruction

      @@ -1094,7 +1104,7 @@ In this example, we are assuming that FooContainer will take care of deleting all the Foo pointers it contains at some point.

      -

      32.3.4 Exception unrolling

      +

      33.3.4 Exception unrolling

      @@ -1153,7 +1163,7 @@ Swig::DirectorMethodException is thrown, PHP will register the exception as soon as the C wrapper function returns.

      -

      32.3.5 Overhead and code bloat

      +

      33.3.5 Overhead and code bloat

      @@ -1186,7 +1196,7 @@ optimized by selectively enabling director methods (using the %feature directive) for only those methods that are likely to be extended in PHP.

      -

      32.3.6 Typemaps

      +

      33.3.6 Typemaps

      @@ -1200,7 +1210,7 @@ need to be supported.

      -

      32.3.7 Miscellaneous

      +

      33.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 8c1eb2d36..3ede1a992 100644 --- a/Doc/Manual/Pike.html +++ b/Doc/Manual/Pike.html @@ -6,7 +6,7 @@ -

      33 SWIG and Pike

      +

      34 SWIG and Pike

        @@ -46,10 +46,10 @@ least, make sure you read the "SWIG Basics" chapter.

        -

        33.1 Preliminaries

        +

        34.1 Preliminaries

        -

        33.1.1 Running SWIG

        +

        34.1.1 Running SWIG

        @@ -94,7 +94,7 @@ can use the -o option:

        $ swig -pike -o pseudonym.c example.i
        -

        33.1.2 Getting the right header files

        +

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

        -

        33.1.3 Using your module

        +

        34.1.3 Using your module

        @@ -129,10 +129,10 @@ Pike v7.4 release 10 running Hilfe v3.5 (Incremental Pike Frontend) (1) Result: 24

      -

      33.2 Basic C/C++ Mapping

      +

      34.2 Basic C/C++ Mapping

      -

      33.2.1 Modules

      +

      34.2.1 Modules

      @@ -143,7 +143,7 @@ concerned), SWIG's %module directive doesn't really have any significance.

      -

      33.2.2 Functions

      +

      34.2.2 Functions

      @@ -168,7 +168,7 @@ exactly as you'd expect it to: (1) Result: 24 -

      33.2.3 Global variables

      +

      34.2.3 Global variables

      @@ -197,7 +197,7 @@ will result in two functions, Foo_get() and Foo_set(): (3) Result: 3.141590 -

      33.2.4 Constants and enumerated types

      +

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

      -

      33.2.5 Constructors and Destructors

      +

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

      -

      33.2.6 Static Members

      +

      34.2.6 Static Members

      diff --git a/Doc/Manual/Preface.html b/Doc/Manual/Preface.html index 2d0aa093e..d17dc229c 100644 --- a/Doc/Manual/Preface.html +++ b/Doc/Manual/Preface.html @@ -12,13 +12,23 @@

      @@ -57,13 +67,26 @@ In the late 1990's, the most stable version of SWIG was release over a period of 10 years starting from the year 2000. The final version in the 1.3.x series was 1.3.40, but in truth the 1.3.x series had been stable for many years. An official stable version was released along with the decision to make SWIG -license changes and this gave rise to version 2.0.0 in 2010. The license was clarified +license changes and this gave rise to version 2.0.0 in 2010. +

      + +

      1.3 SWIG License

      + + +

      +The LICENSE file shipped with SWIG in the top level directory contains the SWIG license. +For further insight into the license including the license of SWIG's output code, please visit +the SWIG legal page - http://www.swig.org/legal.html. +

      + +

      +The license was clarified in version 2.0.0 so that the code that SWIG generated could be distributed under license terms of the user's choice/requirements and at the same time the SWIG source was placed under the GNU General Public License version 3.

      -

      1.3 SWIG resources

      +

      1.4 SWIG resources

      @@ -93,16 +116,17 @@ 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:

      -

      1.4 Prerequisites

      + +

      1.5 Prerequisites

      @@ -127,7 +151,7 @@ However, this isn't meant to be a tutorial on C++ programming. For many of the gory details, you will almost certainly want to consult a good C++ reference. If you don't program in C++, you may just want to skip those parts of the manual. -

      1.5 Organization of this manual

      +

      1.6 Organization of this manual

      @@ -139,7 +163,7 @@ can probably skip to that chapter and find almost everything you need to know.

      -

      1.6 How to avoid reading the manual

      +

      1.7 How to avoid reading the manual

      @@ -151,7 +175,7 @@ The SWIG distribution also comes with a large directory of examples that illustrate different topics.

      -

      1.7 Backwards compatibility

      +

      1.8 Backwards compatibility

      @@ -162,8 +186,8 @@ this isn't always possible as the primary goal over time is to make SWIG better---a process that would simply be impossible if the developers are constantly bogged down with backwards compatibility issues. -Potential incompatibilities are clearly marked in the detailed release notes -(CHANGES files). +Potential incompatibilities are clearly marked in the detailed +release notes.

      @@ -187,7 +211,16 @@ Note: The version symbol is not defined in the generated SWIG wrapper file. The SWIG preprocessor has defined SWIG_VERSION since SWIG-1.3.11.

      -

      1.8 Credits

      +

      1.9 Release notes

      + + +

      +The CHANGES.current, CHANGES and RELEASENOTES files shipped with SWIG in the top level directory +contain, respectively, detailed release notes for the current version, +detailed release notes for previous releases and summary release notes from SWIG-1.3.22 onwards. +

      + +

      1.10 Credits

      @@ -200,7 +233,7 @@ who have made contributions at all levels over time. Contributors are mentioned either in the COPYRIGHT file or CHANGES files shipped with SWIG or in submitted bugs.

      -

      1.9 Bug reports

      +

      1.11 Bug reports

      @@ -215,5 +248,204 @@ used, and any important pieces of the SWIG generated wrapper code. We can only fix bugs if we know about them.

      +

      1.12 Installation

      + + +

      1.12.1 Windows installation

      + + +

      +Please see the dedicated Windows chapter for instructions on installing +SWIG on Windows and running the examples. The Windows distribution is +called swigwin and includes a prebuilt SWIG executable, swig.exe, included in +the top level directory. Otherwise it is exactly the same as +the main SWIG distribution. There is no need to download anything else. +

      + +

      1.12.2 Unix installation

      + + +

      +You must use GNU make to build and install SWIG. +

      + +

      +PCRE +needs to be installed on your system to build SWIG, in particular +pcre-config must be available. If you have PCRE headers and libraries but not +pcre-config itself or, alternatively, wish to override the compiler or linker +flags returned by pcre-config, you may set PCRE_LIBS and PCRE_CFLAGS variables +to be used instead. And if you don't have PCRE at all, the configure script +will provide instructions for obtaining it. +

      + +

      +To build and install SWIG, simply type the following: +

      + +
      +$ ./configure
      +$ make
      +$ make install
      +
      + +

      +By default SWIG installs itself in /usr/local. If you need to install SWIG in +a different location or in your home directory, use the --prefix option +to ./configure. For example: +

      + +
      +$ ./configure --prefix=/home/yourname/projects
      +$ make
      +$ make install
      +
      + +

      +Note: the directory given to --prefix must be an absolute pathname. Do not use +the ~ shell-escape to refer to your home directory. SWIG won't work properly +if you do this. +

      + +

      +The INSTALL file shipped in the top level directory details more about using configure. Also try +

      + +
      +$ ./configure --help.
      +
      + +

      +The configure script will attempt to locate various packages on your machine +including Tcl, Perl5, Python and all the other target languages that SWIG +supports. Don't panic if you get 'not found' messages -- SWIG does not need these +packages to compile or run. The configure script is actually looking for +these packages so that you can try out the SWIG examples contained +in the 'Examples' directory without having to hack Makefiles. +Note that the --without-xxx options, where xxx is a target language, have +minimal effect. All they do is reduce the amount of testing done with +'make check'. The SWIG executable and library files installed cannot currently +be configured with a subset of target languages. +

      + +

      +SWIG used to include a set of runtime libraries for some languages for working +with multiple modules. These are no longer built during the installation stage. +However, users can build them just like any wrapper module as described in +the Modules chapter. +The CHANGES file shipped with SWIG in the top level directory +also lists some examples which build the runtime library. +

      + +

      +Note: +

      + +
        +
      • +If you checked the code out via Git, you will have to run ./autogen.sh +before ./configure. In addition, a full build of SWIG requires +a number of packages to be installed. Full instructions at +SWIG bleeding edge. +
      • +
      + +

      1.12.3 Macintosh OS X installation

      + + +

      +SWIG is known to work on various flavors of OS X. Follow the Unix installation +instructions above. However, as of this writing, there is still great deal of +inconsistency with how shared libaries are handled by various scripting languages +on OS X. +

      + +

      +Users of OS X should be aware that Darwin handles shared libraries and linking in +a radically different way than most Unix systems. In order to test SWIG and run +the examples, SWIG configures itself to use flat namespaces and to allow undefined +symbols (-flat_namespace -undefined suppress). This mostly closely follows the Unix +model and makes it more likely that the SWIG examples will work with whatever +installation of software you might have. However, this is generally not the recommended +technique for building larger extension modules. Instead, you should utilize +Darwin's two-level namespaces. Some details about this can be found here + +http://developer.apple.com/documentation/ReleaseNotes/DeveloperTools/TwoLevelNamespaces.html. + +

      + +

      +Needless to say, you might have to experiment a bit to get things working at first. +

      + +

      1.12.4 Testing

      + + +

      +If you want to test SWIG after building it, a check can be performed on Unix operating systems. +Type the following: +

      + +
      +    $ make -k check
      +
      + +

      +This step can be performed either before or after installation. +The check requires at least one of the target languages to be +installed. If it fails, it may mean that you have an uninstalled +language module or that the file 'Examples/Makefile' has been +incorrectly configured. It may also fail due to compiler issues such +as a broken C++ compiler. Even if the check fails, there is a +pretty good chance SWIG still works correctly --- you will just have to +mess around with one of the examples and some makefiles to get it to work. +Some tests may also fail due to missing dependency packages, eg PCRE +or Boost, but this will require careful analysis of the configure output +done during configuration. +

      + +

      +The test suite executed by the check is designed to stress-test +many parts of the implementation including obscure corner cases. If some +of these tests fail or generate warning messages, there is no reason for +alarm --- the test may be related to some new SWIG feature or a difficult bug +that we're trying to resolve. Chances are that SWIG will work just fine +for you. Note that if you have more than one CPU/core, then you can use +parallel make to speed up the check as it does take quite some time to run, +for example: +

      + +
      +    $ make -j2 -k check
      +
      + +

      +Also, SWIG's support for C++ is sufficiently advanced that certain +tests may fail on older C++ compilers (for instance if your compiler +does not support member templates). These errors are harmless if you +don't intend to use these features in your own programs. +

      + +

      +Note: The test-suite currently contains over 500 tests. If you +have many different target languages installed and a slow machine, it +might take more than an hour to run the test-suite. +

      + +

      1.12.5 Examples

      + + +

      +The Examples directory contains a variety of examples of using SWIG +and it has some browsable documentation. Simply point your browser to +the file "Example/index.html". +

      + +

      +The Examples directory also includes Visual C++ project 6 (.dsp) files for +building some of the examples on Windows. Later versions of Visual Studio +will convert these old style project files into a current solution file. +

      + diff --git a/Doc/Manual/Preprocessor.html b/Doc/Manual/Preprocessor.html index 8fcbe9206..d5c41dde7 100644 --- a/Doc/Manual/Preprocessor.html +++ b/Doc/Manual/Preprocessor.html @@ -6,7 +6,7 @@ -

      7 Preprocessing

      +

      8 Preprocessing

        @@ -37,7 +37,7 @@ However, a number of modifications and enhancements have been made. This chapter describes some of these modifications.

        -

        7.1 File inclusion

        +

        8.1 File inclusion

        @@ -63,7 +63,7 @@ By default, the #include is ignored unless you run SWIG with the is that you often don't want SWIG to try and wrap everything included in standard header system headers and auxiliary files. -

        7.2 File imports

        +

        8.2 File imports

        @@ -92,7 +92,7 @@ The -importall directive tells SWIG to follow all #include sta as imports. This might be useful if you want to extract type definitions from system header files without generating any wrappers. -

        7.3 Conditional Compilation

        +

        8.3 Conditional Compilation

        @@ -152,7 +152,7 @@ SWIG (except for the symbol `SWIG' which is only defined within the SWIG compiler).

        -

        7.4 Macro Expansion

        +

        8.4 Macro Expansion

        @@ -207,7 +207,7 @@ like #x. This is a non-standard SWIG extension.

      -

      7.5 SWIG Macros

      +

      8.5 SWIG Macros

      @@ -253,7 +253,7 @@ many of SWIG's advanced features and libraries are built using this mechanism (s support).

      -

      7.6 C99 and GNU Extensions

      +

      8.6 C99 and GNU Extensions

      @@ -309,14 +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

      +

      8.7 Preprocessing and delimiters

      The preprocessor handles { }, " " and %{ %} delimiters differently.

      -

      7.7.1 Preprocessing and %{ ... %} & " ... " delimiters

      +

      8.7.1 Preprocessing and %{ ... %} & " ... " delimiters

      @@ -341,7 +341,7 @@ the contents of the %{ ... %} block are copied without modification to the output (including all preprocessor directives).

      -

      7.7.2 Preprocessing and { ... } delimiters

      +

      8.7.2 Preprocessing and { ... } delimiters

      @@ -383,7 +383,7 @@ to actually go into the wrapper file, prefix the preprocessor directives with % and leave the preprocessor directive in the code.

      -

      7.8 Preprocessor and Typemaps

      +

      8.8 Preprocessor and Typemaps

      @@ -454,7 +454,7 @@ would generate

      -

      7.9 Viewing preprocessor output

      +

      8.9 Viewing preprocessor output

      @@ -464,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.10 The #error and #warning directives

      +

      8.10 The #error and #warning directives

      diff --git a/Doc/Manual/Python.html b/Doc/Manual/Python.html index a9a9bc44e..dcfd7427e 100644 --- a/Doc/Manual/Python.html +++ b/Doc/Manual/Python.html @@ -6,7 +6,7 @@ -

      34 SWIG and Python

      +

      35 SWIG and Python

    • Python Packages +
    • Python 3 Support
      • Function annotation @@ -135,7 +141,7 @@ very least, make sure you read the "SWIG Basics" chapter.

        -

        34.1 Overview

        +

        35.1 Overview

        @@ -162,10 +168,10 @@ described followed by a discussion of low-level implementation details.

        -

        34.2 Preliminaries

        +

        35.2 Preliminaries

        -

        34.2.1 Running SWIG

        +

        35.2.1 Running SWIG

        @@ -263,7 +269,7 @@ The following sections have further practical examples and details on how you might go about compiling and using the generated files.

        -

        34.2.2 Using distutils

        +

        35.2.2 Using distutils

        @@ -355,7 +361,7 @@ This same approach works on all platforms if the appropriate compiler is install can even build extensions to the standard Windows Python using MingGW)

        -

        34.2.3 Hand compiling a dynamic module

        +

        35.2.3 Hand compiling a dynamic module

        @@ -403,7 +409,7 @@ module actually consists of two files; socket.py and

        -

        34.2.4 Static linking

        +

        35.2.4 Static linking

        @@ -482,7 +488,7 @@ If using static linking, you might want to rely on a different approach (perhaps using distutils).

        -

        34.2.5 Using your module

        +

        35.2.5 Using your module

        @@ -639,7 +645,7 @@ system configuration (this requires root access and you will need to read the man pages).

        -

        34.2.6 Compilation of C++ extensions

        +

        35.2.6 Compilation of C++ extensions

        @@ -731,7 +737,7 @@ erratic program behavior. If working with lots of software components, you might want to investigate using a more formal standard such as COM.

        -

        34.2.7 Compiling for 64-bit platforms

        +

        35.2.7 Compiling for 64-bit platforms

        @@ -768,7 +774,7 @@ and -m64 allow you to choose the desired binary format for your python extension.

        -

        34.2.8 Building Python Extensions under Windows

        +

        35.2.8 Building Python Extensions under Windows

        @@ -795,7 +801,9 @@ If you need to build it on your own, the following notes are provided: You will need to create a DLL that can be loaded into the interpreter. This section briefly describes the use of SWIG with Microsoft Visual C++. As a starting point, many of SWIG's examples include project -files. You might want to take a quick look at these in addition to +files (.dsp files) for Visual C++ 6. These can be opened by more +recent versions of Visual Studio. +You might want to take a quick look at these examples in addition to reading this section.

        @@ -868,6 +876,24 @@ set of Win32 debug or thread libraries. You will have to fiddle around with the build options of project to try and track this down.

        +

        +A 'Debug' build of the wrappers requires a debug build of the Python interpreter. +This normally requires building the Python interpreter from source, which is not a +job for the feint-hearted. Alternatively you can use the 'Release' build of the +Python interpreter with a 'Debug' build of your wrappers by defining the SWIG_PYTHON_INTERPRETER_NO_DEBUG +symbol under the preprocessor options. Or you can ensure this macro is defined at the beginning +of the wrapper code using the following in your interface file, where _MSC_VER ensures it is +only used by the Visual Studio compiler: +

        + +
        +%begin %{
        +#ifdef _MSC_VER
        +#define SWIG_PYTHON_INTERPRETER_NO_DEBUG
        +#endif
        +%}
        +
        +

        Some users have reported success in building extension modules using Cygwin and other compilers. However, the problem of building usable DLLs with these @@ -877,7 +903,7 @@ SWIG Wiki.

        -

        34.3 A tour of basic C/C++ wrapping

        +

        35.3 A tour of basic C/C++ wrapping

        @@ -886,7 +912,7 @@ to your C/C++ code. Functions are wrapped as functions, classes are wrapped as This section briefly covers the essential aspects of this wrapping.

        -

        34.3.1 Modules

        +

        35.3.1 Modules

        @@ -899,7 +925,7 @@ module name, make sure you don't use the same name as a built-in Python command or standard module name.

        -

        34.3.2 Functions

        +

        35.3.2 Functions

        @@ -923,7 +949,7 @@ like you think it does: >>>

    • -

      34.3.3 Global variables

      +

      35.3.3 Global variables

      @@ -1061,7 +1087,7 @@ that starts with a leading underscore. SWIG does not create cvar if there are no global variables in a module.

      -

      34.3.4 Constants and enums

      +

      35.3.4 Constants and enums

      @@ -1101,7 +1127,7 @@ other object. Unfortunately, there is no easy way for SWIG to generate code that prevents this. You will just have to be careful.

      -

      34.3.5 Pointers

      +

      35.3.5 Pointers

      @@ -1242,7 +1268,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

      +

      35.3.6 Structures

      @@ -1431,7 +1457,7 @@ everything works just like you would expect. For example: -

      34.3.7 C++ classes

      +

      35.3.7 C++ classes

      @@ -1520,7 +1546,7 @@ they are accessed through cvar like this: -

      34.3.8 C++ inheritance

      +

      35.3.8 C++ inheritance

      @@ -1575,7 +1601,7 @@ then the function spam() accepts Foo * or a pointer to any cla It is safe to use multiple inheritance with SWIG.

      -

      34.3.9 Pointers, references, values, and arrays

      +

      35.3.9 Pointers, references, values, and arrays

      @@ -1636,7 +1662,7 @@ treated as a returning value, and it will follow the same allocation/deallocation process.

      -

      34.3.10 C++ overloaded functions

      +

      35.3.10 C++ overloaded functions

      @@ -1759,7 +1785,7 @@ first declaration takes precedence. Please refer to the "SWIG and C++" chapter for more information about overloading.

      -

      34.3.11 C++ operators

      +

      35.3.11 C++ operators

      @@ -1848,7 +1874,7 @@ Also, be aware that certain operators don't map cleanly to Python. For instance overloaded assignment operators don't map to Python semantics and will be ignored.

      -

      34.3.12 C++ namespaces

      +

      35.3.12 C++ namespaces

      @@ -1915,7 +1941,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

      +

      35.3.13 C++ templates

      @@ -1969,7 +1995,7 @@ Some more complicated examples will appear later.

      -

      34.3.14 C++ Smart Pointers

      +

      35.3.14 C++ Smart Pointers

      @@ -2053,7 +2079,7 @@ simply use the __deref__() method. For example: -

      34.3.15 C++ reference counted objects

      +

      35.3.15 C++ reference counted objects

      @@ -2062,7 +2088,7 @@ Python examples of memory management using referencing counting.

      -

      34.4 Further details on the Python class interface

      +

      35.4 Further details on the Python class interface

      @@ -2085,7 +2111,7 @@ the -builtin option are in the Built-in section.

      -

      34.4.1 Proxy classes

      +

      35.4.1 Proxy classes

      @@ -2174,7 +2200,7 @@ you can attach new Python methods to the class and you can even inherit from it by Python built-in types until Python 2.2).

      -

      34.4.2 Built-in Types

      +

      35.4.2 Built-in Types

      @@ -2218,7 +2244,7 @@ please refer to the python documentation:

      http://docs.python.org/extending/newtypes.html

      -

      34.4.2.1 Limitations

      +

      35.4.2.1 Limitations

      Use of the -builtin option implies a couple of limitations: @@ -2345,7 +2371,7 @@ 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 requiress a bit of extra discipline to ensure that base classes are initialized before derived classes. Specifically:

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

        @@ -2386,7 +2412,7 @@ assert(issubclass(B.Derived, A.Base))
      -

      34.4.2.2 Operator overloads -- use them!

      +

      35.4.2.2 Operator overloads -- use them!

      The entire justification for the -builtin option is improved @@ -2487,7 +2513,7 @@ structs.

      -

      34.4.3 Memory management

      +

      35.4.3 Memory management

      NOTE: Although this section refers to proxy objects, everything here also applies @@ -2682,7 +2708,7 @@ It is also possible to deal with situations like this using typemaps--an advanced topic discussed later.

      -

      34.4.4 Python 2.2 and classic classes

      +

      35.4.4 Python 2.2 and classic classes

      @@ -2719,7 +2745,7 @@ class itself. In Python-2.1 and earlier, they have to be accessed as a global function or through an instance (see the earlier section).

      -

      34.5 Cross language polymorphism

      +

      35.5 Cross language polymorphism

      @@ -2753,7 +2779,7 @@ proxy classes, director classes, and C wrapper functions takes care of all the cross-language method routing transparently.

      -

      34.5.1 Enabling directors

      +

      35.5.1 Enabling directors

      @@ -2782,9 +2808,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; @@ -2846,7 +2869,7 @@ class MyFoo(mymodule.Foo): -

      34.5.2 Director classes

      +

      35.5.2 Director classes

      @@ -2928,7 +2951,7 @@ so there is no need for the extra overhead involved with routing the calls through Python.

      -

      34.5.3 Ownership and object destruction

      +

      35.5.3 Ownership and object destruction

      @@ -2995,7 +3018,7 @@ deleting all the Foo pointers it contains at some point. Note that no hard references to the Foo objects remain in Python.

      -

      34.5.4 Exception unrolling

      +

      35.5.4 Exception unrolling

      @@ -3054,7 +3077,7 @@ Swig::DirectorMethodException is thrown, Python will register the exception as soon as the C wrapper function returns.

      -

      34.5.5 Overhead and code bloat

      +

      35.5.5 Overhead and code bloat

      @@ -3088,7 +3111,7 @@ directive) for only those methods that are likely to be extended in Python.

      -

      34.5.6 Typemaps

      +

      35.5.6 Typemaps

      @@ -3102,7 +3125,7 @@ need to be supported.

      -

      34.5.7 Miscellaneous

      +

      35.5.7 Miscellaneous

      @@ -3149,7 +3172,7 @@ methods that return const references.

      -

      34.6 Common customization features

      +

      35.6 Common customization features

      @@ -3162,7 +3185,7 @@ This section describes some common SWIG features that are used to improve your the interface to an extension module.

      -

      34.6.1 C/C++ helper functions

      +

      35.6.1 C/C++ helper functions

      @@ -3243,7 +3266,7 @@ hard to implement. It is possible to clean this up using Python code, typemaps, customization features as covered in later sections.

      -

      34.6.2 Adding additional Python code

      +

      35.6.2 Adding additional Python code

      @@ -3297,6 +3320,53 @@ what can be done without having to rely on any of the more advanced customization features.

      +

      +There is also %pythonbegin which is another directive very similar to %pythoncode, +but generates the given Python code at the beginning of the .py file. +This directive works in the same way as %pythoncode, except the code is copied +just after the SWIG banner (comment) at the top of the file, before any real code. +This provides an opportunity to add your own description in a comment near the top of the file as well +as Python imports that have to appear at the top of the file, such as "from __future__ import" +statements. +

      + +

      +The following shows example usage for Python 2.6 to use print as it can in Python 3, that is, as a function instead of a statement: +

      + +
      +
      +%pythonbegin %{
      +# This module provides wrappers to the Whizz Bang library
      +%}
      +
      +%pythonbegin %{
      +from __future__ import print_function
      +print("Loading", "Whizz", "Bang", sep=' ... ')
      +%}
      +
      +
      + +

      +which can be seen when viewing the first few lines of the generated .py file: +

      + +
      +
      +# This file was automatically generated by SWIG (http://www.swig.org).
      +# Version 2.0.11
      +#
      +# Do not make changes to this file unless you know what you are doing--modify
      +# the SWIG interface file instead.
      +
      +# This module provides wrappers to the Whizz Bang library
      +
      +from __future__ import print_function
      +print("Loading", "Whizz", "Bang", sep=' ... ')
      +
      +
      +
      +

      Sometimes you may want to replace or modify the wrapper function that SWIG creates in the proxy .py file. The Python module in SWIG provides some features that enable you to do this. First, to @@ -3389,10 +3459,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();
      +}
      +
      +
      -

      34.6.3 Class extension with %extend

      +

      +The same applies for overloaded constructors. +

      + + +

      35.6.3 Class extension with %extend

      @@ -3481,7 +3583,7 @@ Vector(12,14,16) in any way---the extensions only show up in the Python interface.

      -

      34.6.4 Exception handling with %exception

      +

      35.6.4 Exception handling with %exception

      @@ -3607,7 +3709,7 @@ The language-independent exception.i library file can also be used to raise exceptions. See the SWIG Library chapter.

      -

      34.7 Tips and techniques

      +

      35.7 Tips and techniques

      @@ -3617,7 +3719,7 @@ strings, binary data, and arrays. This chapter discusses the common techniques solving these problems.

      -

      34.7.1 Input and output parameters

      +

      35.7.1 Input and output parameters

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

      -

      34.7.2 Simple pointers

      +

      35.7.2 Simple pointers

      @@ -3899,7 +4001,7 @@ If you replace %pointer_functions() by %pointer_class(type,name)SWIG Library chapter for further details.

      -

      34.7.3 Unbounded C Arrays

      +

      35.7.3 Unbounded C Arrays

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

      -

      34.7.4 String handling

      +

      35.7.4 String handling

      @@ -4030,7 +4132,7 @@ If you need to return binary data, you might use the also be used to extra binary data from arbitrary pointers.

      -

      34.8 Typemaps

      +

      35.8 Typemaps

      @@ -4047,7 +4149,7 @@ Typemaps are only used if you want to change some aspect of the primitive C-Python interface or if you want to elevate your guru status.

      -

      34.8.1 What is a typemap?

      +

      35.8.1 What is a typemap?

      @@ -4163,7 +4265,7 @@ parameter is omitted): -

      34.8.2 Python typemaps

      +

      35.8.2 Python typemaps

      @@ -4204,7 +4306,7 @@ a look at the SWIG library version 1.3.20 or so.

      -

      34.8.3 Typemap variables

      +

      35.8.3 Typemap variables

      @@ -4275,7 +4377,7 @@ properly assigned. The Python name of the wrapper function being created. -

      34.8.4 Useful Python Functions

      +

      35.8.4 Useful Python Functions

      @@ -4403,7 +4505,7 @@ write me -

      34.9 Typemap Examples

      +

      35.9 Typemap Examples

      @@ -4412,7 +4514,7 @@ might look at the files "python.swg" and "typemaps.i" in the SWIG library.

      -

      34.9.1 Converting Python list to a char **

      +

      35.9.1 Converting Python list to a char **

      @@ -4492,7 +4594,7 @@ memory allocation is used to allocate memory for the array, the the C function.

      -

      34.9.2 Expanding a Python object into multiple arguments

      +

      35.9.2 Expanding a Python object into multiple arguments

      @@ -4571,7 +4673,7 @@ to supply the argument count. This is automatically set by the typemap code. F -

      34.9.3 Using typemaps to return arguments

      +

      35.9.3 Using typemaps to return arguments

      @@ -4586,8 +4688,7 @@ int spam(double a, double b, double *out1, double *out2) { *out1 = result1; *out2 = result2; return status; -}; - +}

      @@ -4660,7 +4761,7 @@ function can now be used as follows: >>> -

      34.9.4 Mapping Python tuples into small arrays

      +

      35.9.4 Mapping Python tuples into small arrays

      @@ -4709,7 +4810,7 @@ array, such an approach would not be recommended for huge arrays, but for small structures, this approach works fine.

      -

      34.9.5 Mapping sequences to C arrays

      +

      35.9.5 Mapping sequences to C arrays

      @@ -4798,7 +4899,7 @@ static int convert_darray(PyObject *input, double *ptr, int size) { -

      34.9.6 Pointer handling

      +

      35.9.6 Pointer handling

      @@ -4895,7 +4996,7 @@ class object (if applicable). -

      34.10 Docstring Features

      +

      35.10 Docstring Features

      @@ -4923,7 +5024,7 @@ of your users much simpler.

      -

      34.10.1 Module docstring

      +

      35.10.1 Module docstring

      @@ -4957,7 +5058,7 @@ layout of controls on a panel, etc. to be loaded from an XML file." -

      34.10.2 %feature("autodoc")

      +

      35.10.2 %feature("autodoc")

      @@ -4985,7 +5086,7 @@ four levels for autodoc controlled by the value given to the feature, %feature("autodoc", "level"). The four values for level are covered in the following sub-sections. -

      34.10.2.1 %feature("autodoc", "0")

      +

      35.10.2.1 %feature("autodoc", "0")

      @@ -5014,7 +5115,7 @@ def function_name(*args, **kwargs): -

      34.10.2.2 %feature("autodoc", "1")

      +

      35.10.2.2 %feature("autodoc", "1")

      @@ -5039,7 +5140,7 @@ def function_name(*args, **kwargs): -

      34.10.2.3 %feature("autodoc", "2")

      +

      35.10.2.3 %feature("autodoc", "2")

      @@ -5099,7 +5200,7 @@ def function_name(*args, **kwargs): -

      34.10.2.4 %feature("autodoc", "3")

      +

      35.10.2.4 %feature("autodoc", "3")

      @@ -5124,7 +5225,7 @@ def function_name(*args, **kwargs): -

      34.10.2.5 %feature("autodoc", "docstring")

      +

      35.10.2.5 %feature("autodoc", "docstring")

      @@ -5143,7 +5244,7 @@ void GetPosition(int* OUTPUT, int* OUTPUT); -

      34.10.3 %feature("docstring")

      +

      35.10.3 %feature("docstring")

      @@ -5175,13 +5276,70 @@ with more than one line. -

      34.11 Python Packages

      +

      35.11 Python Packages

      + + +

      Python has concepts of modules and packages. Modules are separate units of +code and may be grouped together to form a package. Packages may be nested, +that is they may contain subpackages. This leads to tree-like hierarchy, with +packages as intermediate nodes and modules as leaf nodes.

      + +

      The hierarchy of Python packages/modules follows the hierarchy of +*.py files found in a source tree (or, more generally, in the Python path). +Normally, the developer creates new module by placing a *.py file +somewhere under Python path; the module is then named after that *.py +file. A package is created by placing an __init__.py file within a +directory; the package is then named after that directory. For example, the +following source tree:

      + +
      +
      +mod1.py
      +pkg1/__init__.py
      +pkg1/mod2.py
      +pkg1/pkg2/__init__.py
      +pkg1/pkg2/mod3.py
      +
      +
      + +

      +defines the following Python packages and modules: +

      + +
      +
      +pkg1            # package
      +pkg1.pkg2       # package
      +mod1            # module
      +pkg1.mod2       # module
      +pkg1.pkg2.mod3  # module
      +
      +
      + +

      +The purpose of an __init__.py file is two-fold. First, the existence of +__init__.py in a directory informs the Python interpreter that this +directory contains a Python package. Second, the code in __init__.py is +loaded/executed automatically when the package is initialized (when it or its +submodule/subpackage gets import'ed). By default, SWIG generates +proxy Python code – one *.py file for each *.i +interface. The __init__.py files, however, are not generated by SWIG. +They should be created by other means. Both files (module *.py and +__init__.py) should be installed in appropriate destination +directories in order to obtain a desirable package/module hierarchy. +

      + +

      The way Python defines its modules and packages impacts SWIG users. Some +users may need to use special features such as the package option in the +%module directive or import related command line options. These are +explained in the following sections.

      + +

      35.11.1 Setting the Python package

      -Using the package option of the %module directive -allows you to specify what Python package that the module will be -living in when installed. +Using the package option in the %module directive allows you +to specify a Python package that the module will be in when installed.

      @@ -5194,15 +5352,330 @@ living in when installed. This is useful when the .i file is %imported by another .i file. By default SWIG will assume that the importer is able to find the importee with just the module name, but -if they live in separate Python packages then that won't work. +if they live in separate Python packages then this won't work. However if the importee specifies what its package is with the %module option then the Python code generated for the importer will use that package name when importing the other module -and also in base class declarations, etc. if the package name is -different than its own. +and in base class declarations, etc..

      -

      34.12 Python 3 Support

      +

      SWIG assumes that the package option provided to %module +together with the module name (that is, wx.xrc in the above +example) forms a fully qualified (absolute) name of a module (in Python terms). +This is important especially for Python 3, where absolute imports are used by +default. It's up to you to place the generated module files (.py, +.so) in appropriate subdirectories. For example, if you have an +interface file foo.i with: +

      + +
      +
      +%module(package="pkg1.pkg2") foo
      +
      +
      + +

      +then the resulting directory layout should be +

      + +
      +
      +pkg1/
      +pkg1/__init__.py
      +pkg1/pkg2/__init__.py
      +pkg1/pkg2/foo.py        # (generated by SWIG)
      +pkg1/pkg2/_foo.so       # (shared library built from C/C++ code generated by SWIG)
      +
      +
      + +

      35.11.2 Absolute and relative imports

      + + +

      Suppose, we have the following hierarchy of files:

      + +
      +
      +pkg1/
      +pkg1/__init__.py
      +pkg1/mod2.py
      +pkg1/pkg2/__init__.py
      +pkg1/pkg2/mod3.py
      +
      +
      + +

      Let the contents of pkg1/pkg2/mod3.py be

      +
      +
      +class M3: pass
      +
      +
      + +

      +We edit pkg1/mod2.py and want to import module +pkg1/pkg2/pkg3.py in order to derive from class M3. We can +write appropriate Python code in several ways, for example: +

      + +
        +
      1. Using "import <>" syntax with absolute package name:

        +
        +
        +# pkg1/mod2.py
        +import pkg1.pkg2.mod3
        +class M2(pkg1.pkg2.mod3.M3): pass
        +
        +
        +
      2. + +
      3. Using "import <>" syntax with package name relative to + pkg1 (only in Python 2.7 and earlier):

        +
        +
        +# pkg1/mod2.py
        +import pkg2.mod3
        +class M2(pkg2.mod3.M3): pass
        +
        +
        +
      4. + +
      5. Using "from <> import <>" syntax (relative import + syntax, only in Python 2.5 and later):

        +
        +
        +# pkg1/mod2.py
        +from .pkg2 import mod3
        +class M2(mod3.M3): pass
        +
        +
        +
      6. + +
      7. Other variants, for example the following construction in order to + have the pkg2.mod3.M3 symbol available in mod2 as + in point 2 above (but now under Python 3):

        +
        +
        +# pkg1/mod2.py
        +from . import pkg2
        +from .pkg2 import mod3
        +class M2(pkg2.mod3.M3): pass
        +
        +
        +
      8. + +
      + +

      Now suppose we have mod2.i with

      + +
      +
      +// mod2.i
      +%module (package="pkg1") mod2
      +%import "mod3.i"
      +// ...
      +
      +
      + +

      and mod3.i with

      + +
      +
      +// mod3.i
      +%module (package="pkg1.pkg2") mod3
      +// ...
      +
      +
      + +

      By default, SWIG would generate mod2.py proxy file with +import directive as in point 1. This can be changed with the +-relativeimport command line option. The -relativeimport instructs +SWIG to organize imports as in point 2 (for Python 2.x) or as in point 4 (for +Python 3, that is when the -py3 command line option is enabled). In short, if you have +mod2.i and mod3.i as above, then without +-relativeimport SWIG will write

      + +
      +
      +import pkg1.pkg2.mod3
      +
      +
      + +

      to mod2.py proxy file, and with -relativeimport it will +write

      + +
      +
      +import pkg2.mod3
      +
      +
      + +

      if -py3 is not used, or

      + +
      +
      +from . import pkg2
      +import pkg1.pkg2.mod3
      +
      +
      + +

      when -py3 is used.

      + +

      You should avoid using relative imports and use absolute ones whenever +possible. There are some cases, however, when relative imports may be +necessary. The first example is, when some (legacy) Python code refers entities +imported by proxy files generated by SWIG, and it assumes that the proxy file +uses relative imports. Second case is, when one puts import directives in +__init__.py to import symbols from submodules or subpackages and the +submodule depends on other submodules (discussed later).

      + +

      35.11.3 Enforcing absolute import semantics

      + + +

      As you may know, there is an incompatibility in import semantics (for the +import <> syntax) between Python 2 and 3. In Python 2.4 and +earlier it is not clear whether

      + +
      +
      +import foo
      +
      +
      +

      refers to a top-level module or to another module inside the current +package. In Python 3 it always refers to a top-level module +(see PEP 328). +To instruct Python 2.5 through 2.7 to use new semantics (that is import +foo is interpreted as absolute import), one has to put the following +line +

      + +
      +
      +from __future__ import absolute_import
      +
      +
      + +

      at the very beginning of his proxy *.py file. In SWIG, it may be +accomplished with %pythonbegin directive as follows:

      + +
      +
      +%pythonbegin %{
      +from __future__ import absolute_import
      +%}
      +
      +
      + +

      35.11.4 Importing from __init__.py

      + + +

      Imports in __init__.py are handy when you want to populate a +package's namespace with names imported from other modules. In SWIG based +projects this approach may also be used to split large pieces of code into +smaller modules, compile them in parallel and then re-assemble everything at another +level by importing submodules' contents in __init__.py, for +example.

      + +

      Unfortunately import directives in __init__.py may cause problems, +especially if they refer to a package's submodules. This is caused by the way +Python initializes packages. If you spot problems with imports from +__init__.py try using -relativeimport option. Below we +explain in detail one issue, for which the -relativeimport workaround +may be helpful.

      + +

      Consider the following example (Python 3):

      + +
      +
      +pkg1/__init__.py        # (empty)
      +pkg1/pkg2/__init__.py   # (imports something from bar.py)
      +pkg1/pkg2/foo.py
      +pkg1/pkg2/bar.py        # (imports foo.py)
      +
      +
      + +

      If the file contents are:

      + +
        +
      • pkg1/pkg2/__init__.py:

        +
        +
        +# pkg1/pkg2/__init__.py
        +from .bar import Bar
        +
        +
        +
      • + +
      • pkg1/pkg2/foo.py:

        +
        +
        +# pkg1/pkg2/foo.py
        +class Foo: pass
        +
        +
        +
      • + +
      • pkg1/pkg2/bar.py:

        +
        +
        +# pkg1/pkg2/bar.py
        +import pkg1.pkg2.foo
        +class Bar(pkg1.pkg2.foo.Foo): pass
        +
        +
        +
      • +
      + +

      Now if one simply used import pkg1.pkg2, it will usually fail:

      + +
      +
      +>>> import pkg1.pkg2
      +Traceback (most recent call last):
      +  File "<stdin>", line 1, in <module>
      +  File "./pkg1/pkg2/__init__.py", line 2, in <module>
      +    from .bar import Bar
      +  File "./pkg1/pkg2/bar.py", line 3, in <module>
      +    class Bar(pkg1.pkg2.foo.Foo): pass
      +AttributeError: 'module' object has no attribute 'pkg2'
      +
      +
      + +

      Surprisingly, if we execute the import pkg1.pkg2 directive for the +second time, it succeeds. The reason seems to be following: when Python spots +the from .bar import Bar directive in pkg1/pkg2/__init__.py +it starts loading pkg1/pkg2/bar.py. This module imports +pkg1.pkg2.foo in turn and tries to use pkg1.pkg2.foo.Foo, but +the package pkg1 is not fully initialized yet (the initialization +procedure is actually in progress) and it seems like the effect of the already seen +import pkg1.pkg2.pkg3.foo is "delayed" or ignored. Exactly the +same may happen to a proxy module generated by SWIG.

      + +

      One workaround for this case is to use a relative +import in pkg1/pkg2/bar.py. If we change bar.py to be:

      + +
      +
      +from .pkg3 import foo
      +class Bar(foo.Foo): pass
      +
      +
      + +

      or

      + +
      +
      +from . import pkg3
      +from .pkg3 import foo
      +class Bar(pkg3.foo.Foo): pass
      +
      +
      + +

      then the example works again. With SWIG, you need to enable the +-relativeimport option in order to have the above workaround in +effect (note, that the Python 2 case also needs the -relativeimport +workaround).

      + + +

      35.12 Python 3 Support

      @@ -5229,7 +5702,7 @@ The following are Python 3.0 new features that are currently supported by SWIG.

      -

      34.12.1 Function annotation

      +

      35.12.1 Function annotation

      @@ -5262,7 +5735,7 @@ For detailed usage of function annotation, see PEP 3107.

      -

      34.12.2 Buffer interface

      +

      35.12.2 Buffer interface

      @@ -5414,7 +5887,7 @@ modify the buffer.

      -

      34.12.3 Abstract base classes

      +

      35.12.3 Abstract base classes

      diff --git a/Doc/Manual/R.html b/Doc/Manual/R.html index ceea32146..ce9523ced 100644 --- a/Doc/Manual/R.html +++ b/Doc/Manual/R.html @@ -6,7 +6,7 @@ -

      35 SWIG and R

      +

      36 SWIG and R

        @@ -33,7 +33,7 @@ compile and run an R interface to QuantLib running on Mandriva Linux with gcc. The R bindings also work on Microsoft Windows using Visual C++.

        -

        35.1 Bugs

        +

        36.1 Bugs

        @@ -45,7 +45,7 @@ Currently the following features are not implemented or broken:

      • C Array wrappings
      -

      35.2 Using R and SWIG

      +

      36.2 Using R and SWIG

      @@ -119,7 +119,7 @@ Without it, inheritance of wrapped objects may fail. These two files can be loaded in any order

      -

      35.3 Precompiling large R files

      +

      36.3 Precompiling large R files

      In cases where the R file is large, one make save a lot of loading @@ -137,7 +137,7 @@ will save a large amount of loading time. -

      35.4 General policy

      +

      36.4 General policy

      @@ -146,7 +146,7 @@ wrapping over the underlying functions and rely on the R type system to provide R syntax.

      -

      35.5 Language conventions

      +

      36.5 Language conventions

      @@ -155,7 +155,7 @@ and [ are overloaded to allow for R syntax (one based indices and slices)

      -

      35.6 C++ classes

      +

      36.6 C++ classes

      @@ -167,7 +167,7 @@ keep track of the pointer object which removes the necessity for a lot of the proxy class baggage you see in other languages.

      -

      35.7 Enumerations

      +

      36.7 Enumerations

      diff --git a/Doc/Manual/README b/Doc/Manual/README index f01013d54..66daaec90 100644 --- a/Doc/Manual/README +++ b/Doc/Manual/README @@ -1,9 +1,9 @@ This directory contains the HTML for the SWIG users manual. All of this HTML is hand-written. However, section numbering, indices, -and the table of contents is generated automatically by the 'maketoc.py' +and the table of contents are generated automatically by the 'maketoc.py' script. The Makefile has further information on how the various alternative -forms of the documentation is generated from the hand-written HTML. +forms of the documentation are generated from the hand-written HTML. There are 4 types of boxes that code or whatever can be inside: -

      ...
      diff --git a/Doc/Manual/Ruby.html b/Doc/Manual/Ruby.html index 69005c731..9719239a9 100644 --- a/Doc/Manual/Ruby.html +++ b/Doc/Manual/Ruby.html @@ -7,7 +7,7 @@ -

      36 SWIG and Ruby

      +

      37 SWIG and Ruby

        @@ -71,9 +71,9 @@
      • Placement of typemaps
      • Ruby typemaps
          -
        •  "in" typemap +
        • "in" typemap
        • "typecheck" typemap -
        •  "out" typemap +
        • "out" typemap
        • "arginit" typemap
        • "default" typemap
        • "check" typemap @@ -144,11 +144,7 @@

          This chapter describes SWIG's support of Ruby.

          - - - - -

          36.1 Preliminaries

          +

          37.1 Preliminaries

          SWIG 1.3 is known to work with Ruby versions 1.6 and later. @@ -157,124 +153,60 @@ should also determine if your system supports shared libraries and dynamic loading. SWIG will work with or without dynamic loading, but the compilation process will vary.

          - - - -

          This chapter covers most SWIG features, but in less depth than is found in earlier chapters. At the very least, make sure you also read the "SWIG Basics" chapter. It is also assumed that the reader has a basic understanding of Ruby.

          - - - - -

          36.1.1 Running SWIG

          +

          37.1.1 Running SWIG

          To build a Ruby module, run SWIG using the -ruby option:

          - - - -
          -
          $ swig -ruby example.i
          +
          $ swig -ruby example.i
           
          - - - - -
          - - - -

          If building a C++ extension, add the -c++ option:

          - - - -
          -
          $ swig -c++ -ruby example.i
          +
          $ swig -c++ -ruby example.i
           
          - - - - -
          - - - -

          This creates a file example_wrap.c (example_wrap.cxx if compiling a C++ extension) that contains all of the code needed to build a Ruby extension module. To finish building the module, you need to compile this file and link it with the rest of your program.

          - - - - -

          36.1.2 Getting the right header files

          +

          37.1.2 Getting the right header files

          In order to compile the wrapper code, the compiler needs the ruby.h 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
           
          - - - - -
          - - - -

          The exact location may vary on your machine, but the above location is typical. If you are not entirely sure where Ruby is installed, you can run Ruby to find out. For example:

          - - - -
          -
          $ ruby -e 'puts $:.join("\n")'
          +
          $ 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 .
           
          - - - - -
          - - - - -

          36.1.3 Compiling a dynamic module

          +

          37.1.3 Compiling a dynamic module

          Ruby extension modules are typically compiled into shared @@ -283,100 +215,32 @@ exact commands for doing this vary from platform to platform, your best bet is to follow the steps described in the README.EXT file from the Ruby distribution:

          - - - -
            - - - - -
          1. - - - -

            Create a file called extconf.rb that looks like the following:

            - - - - - - - - -
            -
            require 'mkmf'
            create_makefile('example')
            +
            require 'mkmf'
            +create_makefile('example')
            - - - - -
          2. - - - - -
          3. - - - -

            Type the following to build the extension:

            - - - - - - - - -
            - - - - -
            $ ruby extconf.rb
            $ make
            $ make install +
            +$ ruby extconf.rb
            +$ make
            +$ make install
                 
            - - - - -
            - - - - -
          4. - - - - -
          - - - -

          Of course, there is the problem that mkmf does not work correctly on all platforms, e.g, HPUX. If you need to add your own make rules to the file that extconf.rb produces, you can add this:

          - - - -
          open("Makefile", "a") { |mf|
            puts <<EOM
          @@ -384,51 +248,38 @@ can add this: 

          EOM }
          - - - - -
          - - - -

          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:

          - - - -
          -
          $ 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 -O2 -fPIC -c example.c
          +$ gcc -O2 -fPIC -c example_wrap.c -I/usr/local/lib/ruby/1.6/i686-linux
          +$ gcc -shared example.o example_wrap.o -o example.so
           
          - - - - -
          +

          +The -fPIC option tells GCC to generate position-independent code (PIC) +which is required for most architectures (it's not vital on x86, but +still a good idea as it allows code pages from the library to be shared between +processes). Other compilers may need a different option specified instead of +-fPIC. +

          - - - -

          For other platforms it may be necessary to compile with the -fPIC -option to generate position-independent code. If in doubt, consult the +

          +If in doubt, consult the manual pages for your compiler and linker to determine the correct set of options. You might also check the SWIG Wiki for additional information.

          -

          36.1.4 Using your module

          +

          37.1.4 Using your module

          Ruby module names must be capitalized, @@ -436,10 +287,6 @@ but the convention for Ruby feature names is to use lowercase names. So, for example, the Etc extension module is imported by requiring the etc feature:

          - - - -
          # The feature name begins with a lowercase letter...
           require 'etc'
          @@ -447,48 +294,22 @@ require 'etc'
           # ... but the module name begins with an uppercase letter
           puts "Your login name: #{Etc.getlogin}"
           
          - - - - -
          - - - -

          To stay consistent with this practice, you should always specify a lowercase module name with SWIG's %module directive. SWIG will automatically correct the resulting Ruby module name for your extension. So for example, a SWIG interface file that begins with:

          - - - -
          -
          %module example
          - - - - - +
          %module example
          - - - -

          will result in an extension module using the feature name "example" and Ruby module name "Example".

          - - - - -

          36.1.5 Static linking

          +

          37.1.5 Static linking

          An alternative approach to dynamic linking is to rebuild the @@ -498,41 +319,26 @@ loading support on certain machines. However, the situation has improved greatly over the last few years and you should not consider this approach unless there is really no other option.

          - - - -

          The usual procedure for adding a new module to Ruby involves finding the Ruby source, adding an entry to the ext/Setup file, adding your directory to the list of extensions in the file, and finally rebuilding Ruby.

          - - -

          36.1.6 Compilation of C++ extensions

          +

          37.1.6 Compilation of C++ extensions

          On most machines, C++ extension modules should be linked using the C++ compiler. For example:

          - - - -
          -
          $ swig -c++ -ruby example.i
          $ g++ -c example.cxx
          $ g++ -c example_wrap.cxx -I/usr/local/lib/ruby/1.6/i686-linux
          $ g++ -shared example.o example_wrap.o -o example.so +
          +$ swig -c++ -ruby example.i
          +$ g++ -fPIC -c example.cxx
          +$ g++ -fPIC -c example_wrap.cxx -I/usr/local/lib/ruby/1.6/i686-linux
          +$ g++ -shared example.o example_wrap.o -o example.so
           
          - - - - -
          - - - -

          If you've written an extconf.rb script to automatically generate a Makefile for your C++ extension module, keep in mind that (as of this writing) Ruby still @@ -544,24 +350,13 @@ module's append_library() method to add one of the C++ runtime libraries to the list of libraries linked into your extension, e.g.

          - - - -
          -
          require 'mkmf'
          $libs = append_library($libs, "supc++")
          create_makefile('example')
          - - - - - +
          require 'mkmf'
          +$libs = append_library($libs, "supc++")
          +create_makefile('example')
          - - - - -

          36.2 Building Ruby Extensions under Windows 95/NT

          +

          37.2 Building Ruby Extensions under Windows 95/NT

          Building a SWIG extension to Ruby under Windows 95/NT is @@ -571,24 +366,14 @@ recent versions of Ruby, the procedure described above (i.e. using an extcon script) will work with Windows as well; you should be able to build your code into a DLL by typing:

          - - - -
          -
          C:\swigtest> ruby extconf.rb
          C:\swigtest> nmake
          C:\swigtest> nmake install +
          +C:\swigtest> ruby extconf.rb
          +C:\swigtest> nmake
          +C:\swigtest> nmake install
           
          - - - - -
          - - - -

          The remainder of this section covers the process of compiling SWIG-generated Ruby extensions with Microsoft Visual C++ 6 (i.e. within the Developer Studio IDE, instead of using the command line tools). In @@ -596,84 +381,35 @@ order to build extensions, you may need to download the source distribution to the Ruby package, as you will need the Ruby header files.

          - - - - -

          36.2.1 Running SWIG from Developer Studio

          +

          37.2.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 follows these steps :

          - - - - -
            - - - - -
          • Open up a new workspace and use the AppWizard to select a DLL 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 (i.e. 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.
          • - - - - -
          • Select the SWIG interface file and go to the settings menu. Under settings, select the "Custom Build" option.
          • - - - - -
          • Enter "SWIG" in the description field.
          • - - - - -
          • Enter "swig -ruby -o $(ProjDir)\$(InputName)_wrap.c $(InputPath)" in the "Build command(s) field". You may have to include the path to swig.exe.
          • - - - - -
          • Enter "$(ProjDir)\$(InputName)_wrap.c" in the "Output files(s) field".
          • - - - - -
          • Next, select the settings for the entire project and go to the C/C++ tab and select the Preprocessor category. Add NT=1 to the Preprocessor definitions. This must be set else you will get compilation errors. Also add IMPORT to the preprocessor definitions, else you may get runtime errors. Also add the include directories for your Ruby installation under "Additional include directories".
          • - - - - -
          • Next, select the settings for the entire project and go to the Link tab and select the General category. Set the name of the output file to match the name of your Ruby module (i.e.. example.dll). @@ -681,23 +417,9 @@ Next add the Ruby library file to your link libraries under Object/Library modules. For example "mswin32-ruby16.lib. You also need to add the path to the library under the Input tab - Additional library path.
          • - - - - -
          • Build your project.
          • - - - - -
          - - - -

          Now, assuming all went well, 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 @@ -705,211 +427,95 @@ version of the wrapper file. To run your new Ruby extension, simply run Ruby and use the require command as normal. For example if you have this ruby file run.rb:

          - - - -
          -
          # file: run.rb
          require 'Example'

          # Call a c function
          print "Foo = ", Example.Foo, "\n"
          - - - - +
          # file: run.rb
          +require 'Example'
           
          +# Call a c function
          +print "Foo = ", Example.Foo, "\n"
          - - - -

          Ensure the dll just built is in your path or current directory, then run the Ruby script from the DOS/Command prompt:

          - - - -
          -
          C:\swigtest> ruby run.rb
          Foo = 3.0
          - - - - - +
          +C:\swigtest> ruby run.rb
          +Foo = 3.0
          +
          - - - - -

          36.3 The Ruby-to-C/C++ Mapping

          +

          37.3 The Ruby-to-C/C++ Mapping

          This section describes the basics of how SWIG maps C or C++ declarations in your SWIG interface files to Ruby constructs.

          - - - - -

          36.3.1 Modules

          +

          37.3.1 Modules

          The SWIG %module directive specifies the name of the Ruby module. If you specify:

          - - - -
          %module example
          - - - - -
          - - - -

          then everything is wrapped into a Ruby module named Example that is nested directly under the global module. You can specify a more deeply nested module by specifying the fully-qualified module name in quotes, e.g.

          - - - -
          %module "foo::bar::spam"
          - - - - -
          - - - -

          An alternate method of specifying a nested module name is to -use the -prefix +use the -prefix option on the SWIG command line. The prefix that you specify with this -option will be prepended to the module name specified with the %module +option will be prepended to the module name specified with the %module directive in your SWIG interface file. So for example, this declaration -at the top of your SWIG interface file:
          - - - - - +at the top of your SWIG interface file:

          - - - -
          %module "foo::bar::spam"
          - - - - -
          - - - - -

          will result in a nested module name of Foo::Bar::Spam, +

          will result in a nested module name of Foo::Bar::Spam, but you can achieve the same -effect by specifying:
          - - - - - +effect by specifying:

          - - - -
          %module spam
          - - - - -
          - - - - -

          and then running SWIG with the -prefix command -line option:
          - - - - - +

          and then running SWIG with the -prefix command +line option:

          - - - -
          -
          $ swig -ruby -prefix "foo::bar::" example.i
          - - - - - +
          +$ swig -ruby -prefix "foo::bar::" example.i
          +
          - - - -

          Starting with SWIG 1.3.20, you can also choose to wrap everything into the global module by specifying the -globalmodule option on the SWIG command line, i.e.

          - - - -
          -
          $ swig -ruby -globalmodule example.i
          - - - - - +
          +$ swig -ruby -globalmodule example.i
          +
          - - - -

          Note that this does not relieve you of the requirement of specifying the SWIG module name with the %module directive (or the -module command-line option) as described earlier.

          - - - -

          When choosing a module name, do not use the same name as a built-in Ruby command or standard module name, as the results may be unpredictable. Similarly, if you're using the -globalmodule @@ -917,74 +523,41 @@ option to wrap everything into the global module, take care that the names of your constants, classes and methods don't conflict with any of Ruby's built-in names.

          - - - - -

          36.3.2 Functions

          +

          37.3.2 Functions

          Global functions are wrapped as Ruby module methods. For example, given the SWIG interface file example.i:

          - - - -
          -
          %module example

          int fact(int n);
          - - - - +
          %module example
           
          +int fact(int n);
          - - - -

          and C source file example.c:

          - - - -
          -
          int fact(int n) {
          if (n == 0)
          return 1;
          return (n * fact(n-1));
          }
          - - - - - +
          int fact(int n) {
          +  if (n == 0)
          +  return 1;
          +  return (n * fact(n-1));
          +}
          - - - -

          SWIG will generate a method fact in the Example module that can be used like so:

          - - - -
          -
          $ irb
          irb(main):001:0> require 'example'
          true
          irb(main):002:0> Example.fact(4)
          24
          - - - - - +
          $ irb
          +irb(main):001:0> require 'example'
          +true
          +irb(main):002:0> Example.fact(4)
          +24
          - - - - -

          36.3.3 Variable Linking

          +

          37.3.3 Variable Linking

          C/C++ global variables are wrapped as a pair of singleton @@ -992,143 +565,89 @@ methods for the module: one to get the value of the global variable and one to set it. For example, the following SWIG interface file declares two global variables:

          - - - -
          -
          // SWIG interface file with global variables
          %module example
          ...
          %inline %{
          extern int variable1;
          extern double Variable2;
          %}
          ...
          - - - - - +
          // SWIG interface file with global variables
          +%module example
          +...
          +%inline %{
          +  extern int variable1;
          +  extern double Variable2;
          +%}
          +...
          - - - -

          Now look at the Ruby interface:

          - - - -
          -
          $ irb
          irb(main):001:0> require 'Example'
          true
          irb(main):002:0> Example.variable1 = 2
          2
          irb(main):003:0> Example.Variable2 = 4 * 10.3
          41.2
          irb(main):004:0> Example.Variable2
          41.2
          - - - - - +
          $ irb
          +irb(main):001:0> require 'Example'
          +true
          +irb(main):002:0> Example.variable1 = 2
          +2
          +irb(main):003:0> Example.Variable2 = 4 * 10.3
          +41.2
          +irb(main):004:0> Example.Variable2
          +41.2
          - - - -

          If you make an error in variable assignment, you will receive an error message. For example:

          - - - -
          -
          irb(main):005:0> Example.Variable2 = "hello"
          TypeError: no implicit conversion to float from string
          from (irb):5:in `Variable2='
          from (irb):5
          - - - - - +
          irb(main):005:0> Example.Variable2 = "hello"
          +TypeError: no implicit conversion to float from string
          +from (irb):5:in `Variable2='
          +from (irb):5
          - - - -

          If a variable is declared as const, it is wrapped as a read-only variable. Attempts to modify its value will result in an error.

          - - - -

          To make ordinary variables read-only, you can also use the %immutable directive. For example:

          - - - -
          -
          %immutable;
          %inline %{
          extern char *path;
          %}
          %mutable;
          - - - - - +
          %immutable;
          +%inline %{
          +  extern char *path;
          +%}
          +%mutable;
          - - - -

          The %immutable directive stays in effect until it is explicitly disabled using %mutable.

          - - - - -

          36.3.4 Constants

          +

          37.3.4 Constants

          C/C++ constants are wrapped as module constants initialized to the appropriate value. To create a constant, use #define or the %constant directive. For example:

          - - - -
          -
          #define PI 3.14159
          #define VERSION "1.0"

          %constant int FOO = 42;
          %constant const char *path = "/usr/local";

          const int BAR = 32;
          - - - +
          #define PI 3.14159
          +#define VERSION "1.0"
           
          +%constant int FOO = 42;
          +%constant const char *path = "/usr/local";
           
          +const int BAR = 32;
          - - - -

          Remember to use the :: operator in Ruby to get at these constant values, e.g.

          - - - -
          -
          $ irb
          irb(main):001:0> require 'Example'
          true
          irb(main):002:0> Example::PI
          3.14159
          - - - - - +
          $ irb
          +irb(main):001:0> require 'Example'
          +true
          +irb(main):002:0> Example::PI
          +3.14159
          - - - - -

          36.3.5 Pointers

          +

          37.3.5 Pointers

          "Opaque" pointers to arbitrary C/C++ types (i.e. types that @@ -1136,125 +655,71 @@ aren't explicitly declared in your SWIG interface file) are wrapped as data objects. So, for example, consider a SWIG interface file containing only the declarations:

          - - - -
          -
          Foo *get_foo();
          void set_foo(Foo *foo);
          - - - - - +
          Foo *get_foo();
          +void set_foo(Foo *foo);
          - - - -

          For this case, the get_foo() method returns an instance of an internally generated Ruby class:

          - - - -
          -
          irb(main):001:0> foo = Example::get_foo()
          #<SWIG::TYPE_p_Foo:0x402b1654>
          - - - - - +
          irb(main):001:0> foo = Example::get_foo()
          +#<SWIG::TYPE_p_Foo:0x402b1654>
          - - - -

          A NULL pointer is always represented by the Ruby nil object.

          - - - - -

          36.3.6 Structures

          +

          37.3.6 Structures

          C/C++ structs are wrapped as Ruby classes, with accessor methods (i.e. "getters" and "setters") for all of the struct members. For example, this struct declaration:

          - - - -
          -
          struct Vector {
          double x, y;
          };
          - - - - - +
          struct Vector {
          +  double x, y;
          +};
          - - - -

          gets wrapped as a Vector class, with Ruby instance methods x, x=, y and y=. These methods can be used to access structure data from Ruby as follows:

          - - - -
          -
          $ irb
          irb(main):001:0> require 'Example'
          true
          irb(main):002:0> f = Example::Vector.new
          #<Example::Vector:0x4020b268>
          irb(main):003:0> f.x = 10
          nil
          irb(main):004:0> f.x
          10.0
          - - - - - +
          $ irb
          +irb(main):001:0> require 'Example'
          +true
          +irb(main):002:0> f = Example::Vector.new
          +#<Example::Vector:0x4020b268>
          +irb(main):003:0> f.x = 10
          +nil
          +irb(main):004:0> f.x
          +10.0
          - - - -

          Similar access is provided for unions and the public data members of C++ classes.

          - - - -

          const members of a structure are read-only. Data members can also be forced to be read-only using the %immutable directive (in C++, private may also be used). For example:

          - - - -
          -
          struct Foo {
          ...
          %immutable;
          int x; /* Read-only members */
          char *name;
          %mutable;
          ...
          };
          - - - - - +
          struct Foo {
          +  ...
          +  %immutable;
          +  int x; /* Read-only members */
          +  char *name;
          +  %mutable;
          +  ...
          +};
          - - - -

          When char * members of a structure are wrapped, the contents are assumed to be dynamically allocated using malloc or new (depending on whether or not SWIG is run @@ -1263,99 +728,55 @@ is set, the old contents will be released and a new value created. If this is not the behavior you want, you will have to use a typemap (described shortly).

          - - - -

          Array members are normally wrapped as read-only. For example, this code:

          - - - -
          -
          struct Foo {
          int x[50];
          };
          - - - - - +
          struct Foo {
          +  int x[50];
          +};
          - - - -

          produces a single accessor function like this:

          - - - -
          -
          int *Foo_x_get(Foo *self) {
          return self->x;
          };
          - - - - - +
          int *Foo_x_get(Foo *self) {
          +  return self->x;
          +};
          - - - -

          If you want to set an array member, you will need to supply a "memberin" typemap described in the section on typemaps. As a special case, SWIG does generate code to set array members of type char (allowing you to store a Ruby string in the structure).

          - - - -

          When structure members are wrapped, they are handled as pointers. For example,

          - - - -
          -
          struct Foo {
          ...
          };

          struct Bar {
          Foo f;
          };
          - - - - +
          struct Foo {
          +  ...
          +};
           
          +struct Bar {
          +  Foo f;
          +};
          - - - -

          generates accessor functions such as this:

          - - - -
          -
          Foo *Bar_f_get(Bar *b) {
          return &b->f;
          }

          void Bar_f_set(Bar *b, Foo *val) {
          b->f = *val;
          }
          - - - - +
          Foo *Bar_f_get(Bar *b) {
          +  return &b->f;
          +}
           
          +void Bar_f_set(Bar *b, Foo *val) {
          +  b->f = *val;
          +}
          - - - - -

          36.3.7 C++ classes

          +

          37.3.7 C++ classes

          Like structs, C++ classes are wrapped by creating a new Ruby @@ -1365,152 +786,97 @@ wrapped as Ruby instance methods, and public static member functions are wrapped as Ruby singleton methods. So, given the C++ class declaration:

          - - - -
          -
          class List {
          public:
          List();
          ~List();
          int search(char *item);
          void insert(char *item);
          void remove(char *item);
          char *get(int n);
          int length;
          static void print(List *l);
          };
          - - - - - +
          class List {
          +public:
          +  List();
          +  ~List();
          +  int search(char *item);
          +  void insert(char *item);
          +  void remove(char *item);
          +  char *get(int n);
          +  int length;
          +  static void print(List *l);
          +};
          - - - -

          SWIG would create a List class with:

          - - - -
            - - - - -
          • instance methods search, insert, remove, and get;
          • - - - - -
          • instance methods length and length= (to get and set the value of the length data member); and,
          • - - - - -
          • a print singleton method for the class.
          • - - - - -
          - - - -

          In Ruby, these functions are used as follows:

          - - - -
          -
          require 'Example'

          l = Example::List.new

          l.insert("Ale")
          l.insert("Stout")
          l.insert("Lager")
          Example.print(l)
          l.length()
          ----- produces the following output
          Lager
          Stout
          Ale
          3
          - - - +
          require 'Example'
           
          +l = Example::List.new
           
          +l.insert("Ale")
          +l.insert("Stout")
          +l.insert("Lager")
          +Example.print(l)
          +l.length()
          +----- produces the following output 
          +Lager
          +Stout
          +Ale
          +3
          - - - - -

          36.3.8 C++ Inheritance

          +

          37.3.8 C++ Inheritance

          The SWIG type-checker is fully aware of C++ inheritance. Therefore, if you have classes like this:

          - - - -
          -
          class Parent {
          ...
          };

          class Child : public Parent {
          ...
          };
          - - - - +
          class Parent {
          +  ...
          +};
           
          +class Child : public Parent {
          +  ...
          +};
          - - - -

          those classes are wrapped into a hierarchy of Ruby classes that reflect the same inheritance structure. All of the usual Ruby utility methods work normally:

          - - - -
          -
          irb(main):001:0> c = Child.new
          #<Bar:0x4016efd4>
          irb(main):002:0> c.instance_of? Child
          true
          irb(main):003:0> b.instance_of? Parent
          false
          irb(main):004:0> b.is_a? Child
          true
          irb(main):005:0> b.is_a? Parent
          true
          irb(main):006:0> Child < Parent
          true
          irb(main):007:0> Child > Parent
          false
          - - - - - +
          irb(main):001:0> c = Child.new
          +#<Bar:0x4016efd4>
          +irb(main):002:0> c.instance_of? Child
          +true
          +irb(main):003:0> b.instance_of? Parent
          +false
          +irb(main):004:0> b.is_a? Child
          +true
          +irb(main):005:0> b.is_a? Parent
          +true
          +irb(main):006:0> Child < Parent
          +true
          +irb(main):007:0> Child > Parent
          +false
          - - - -

          Furthermore, if you have a function like this:

          - - - -
          -
          void spam(Parent *f);
          - - - - - +
          void spam(Parent *f);
          - - - -

          then the function spam() accepts Parent* or a pointer to any class derived from Parent.

          - - - -

          Until recently, the Ruby module for SWIG didn't support multiple inheritance, and this is still the default behavior. This doesn't mean that you can't wrap C++ classes which inherit from @@ -1519,23 +885,13 @@ base class listed in the class declaration is considered, and any additional base classes are ignored. As an example, consider a SWIG interface file with a declaration like this:

          - - - -
          -
          class Derived : public Base1, public Base2
          {
          ...
          };
          - - - - - +
          class Derived : public Base1, public Base2
          +{
          +  ...
          +};
          - - - -

          For this case, the resulting Ruby class (Derived) will only consider Base1 as its superclass. It won't inherit any of Base2's member functions or @@ -1544,66 +900,33 @@ data and it won't recognize Base2 as an relationship would fail). When SWIG processes this interface file, you'll see a warning message like:

          - - - -
          -
          example.i:5: Warning 802: Warning for Derived: Base Base2 ignored.
          Multiple inheritance is not supported in Ruby.
          - - - - - +
          example.i:5: Warning 802: Warning for Derived: Base Base2 ignored.
          +Multiple inheritance is not supported in Ruby.
          - - - -

          Starting with SWIG 1.3.20, the Ruby module for SWIG provides limited support for multiple inheritance. Because the approach for dealing with multiple inheritance introduces some limitations, this is an optional feature that you can activate with the -minherit command-line option:

          - - - -
          -
          $ swig -c++ -ruby -minherit example.i
          - - - - - +
          +$ swig -c++ -ruby -minherit example.i
          +
          - - - -

          Using our previous example, if your SWIG interface file contains a declaration like this:

          - - - -
          -
          class Derived : public Base1, public Base2
          {
          ...
          };
          - - - - - +
          class Derived : public Base1, public Base2
          +{
          +  ...
          +};
          - - - -

          and you run SWIG with the -minherit command-line option, then you will end up with a Ruby class Derived that appears to "inherit" the member data and functions from both Base1 @@ -1614,346 +937,186 @@ module named Impl, and it's in these nested Impl modules that the actual instance methods for the classes are defined, i.e.

          - - - -
          -
          class Base1
          module Impl
          # Define Base1 methods here
          end
          include Impl
          end

          class Base2
          module Impl
          # Define Base2 methods here
          end
          include Impl
          end

          class Derived
          module Impl
          include Base1::Impl
          include Base2::Impl
          # Define Derived methods here
          end
          include Impl
          end
          - - - +
          class Base1
          +  module Impl
          +  # Define Base1 methods here
          +  end
          +  include Impl
          +end
           
          +class Base2
          +  module Impl
          +  # Define Base2 methods here
          +  end
          +  include Impl
          +end
           
          +class Derived
          +  module Impl
          +  include Base1::Impl
          +  include Base2::Impl
          +  # Define Derived methods here
          +  end
          +  include Impl
          +end
          - - - -

          Observe that after the nested Impl module for a class is defined, it is mixed-in to the class itself. Also observe that the Derived::Impl module first mixes-in its base classes' Impl modules, thus "inheriting" all of their behavior.

          - - - -

          The primary drawback is that, unlike the default mode of operation, neither Base1 nor Base2 is a true superclass of Derived anymore:

          - - - -
          -
          obj = Derived.new
          obj.is_a? Base1 # this will return false...
          obj.is_a? Base2 # ... and so will this
          - - - - - +
          obj = Derived.new
          +obj.is_a? Base1 # this will return false...
          +obj.is_a? Base2 # ... and so will this
          - - - -

          In most cases, this is not a serious problem since objects of type Derived will otherwise behave as though they inherit from both Base1 and Base2 (i.e. they exhibit "Duck Typing").

          - - - - -

          36.3.9 C++ Overloaded Functions

          +

          37.3.9 C++ Overloaded Functions

          C++ overloaded functions, methods, and constructors are mostly supported by SWIG. For example, if you have two functions like this:

          - - - -
          -
          void foo(int);
          void foo(char *c);
          - - - - - +
          void foo(int);
          +void foo(char *c);
          - - - -

          You can use them in Ruby in a straightforward manner:

          - - - -
          -
          irb(main):001:0> foo(3) # foo(int)
          irb(main):002:0> foo("Hello") # foo(char *c)
          - - - - - +
          irb(main):001:0> foo(3) # foo(int)
          +irb(main):002:0> foo("Hello") # foo(char *c)
          - - - -

          Similarly, if you have a class like this,

          - - - -
          -
          class Foo {
          public:
          Foo();
          Foo(const Foo &);
          ...
          };
          - - - - - +
          class Foo {
          +public:
          +  Foo();
          +  Foo(const Foo &);
          +  ...
          +};
          - - - -

          you can write Ruby code like this:

          - - - -
          -
          irb(main):001:0> f = Foo.new # Create a Foo
          irb(main):002:0> g = Foo.new(f) # Copy f
          - - - - - +
          irb(main):001:0> f = Foo.new # Create a Foo
          +irb(main):002:0> g = Foo.new(f) # Copy f
          - - - -

          Overloading support is not quite as flexible as in C++. Sometimes there are methods that SWIG can't disambiguate. For example:

          - - - -
          -
          void spam(int);
          void spam(short);
          - - - - - +
          void spam(int);
          +void spam(short);
          - - - -

          or

          - - - -
          -
          void foo(Bar *b);
          void foo(Bar &b);
          - - - - - +
          void foo(Bar *b);
          +void foo(Bar &b);
          - - - -

          If declarations such as these appear, you will get a warning message like this:

          - - - -
           example.i:12: Warning 509: Overloaded method spam(short) effectively ignored,
           example.i:11: Warning 509: as it is shadowed by spam(int).
          -
          -
          - - - - - +
          - - - -

          To fix this, you either need to ignore or rename one of the methods. For example:

          - - - -
          -
          %rename(spam_short) spam(short);
          ...
          void spam(int);
          void spam(short); // Accessed as spam_short
          - - - - - +
          %rename(spam_short) spam(short);
          +...
          +void spam(int); 
          +void spam(short); // Accessed as spam_short
          - - - -

          or

          - - - -
          -
          %ignore spam(short);
          ...
          void spam(int);
          void spam(short); // Ignored
          - - - - - +
          %ignore spam(short);
          +...
          +void spam(int); 
          +void spam(short); // Ignored
          - - - -

          SWIG resolves overloaded functions and methods using a disambiguation scheme that ranks and sorts declarations according to a set of type-precedence rules. The order in which declarations appear in the input does not matter except in situations where ambiguity arises--in this case, the first declaration takes precedence.

          - - - -

          Please refer to the "SWIG and C++" chapter for more information about overloading.

          - - - - -

          36.3.10 C++ Operators

          +

          37.3.10 C++ Operators

          For the most part, overloaded operators are handled automatically by SWIG and do not require any special treatment on your part. So if your class declares an overloaded addition operator, e.g.

          - - - -
          -
          class Complex {
          ...
          Complex operator+(Complex &);
          ...
          };
          - - - - - +
          class Complex {
          +  ...
          +  Complex operator+(Complex &);
          +  ...
          +};
          - - - -

          the resulting Ruby class will also support the addition (+) method correctly.

          - - - -

          For cases where SWIG's built-in support is not sufficient, C++ operators can be wrapped using the %rename directive (available on SWIG 1.3.10 and later releases). All you need to do is give the operator the name of a valid Ruby identifier. For example:

          - - - -
          -
          %rename(add_complex) operator+(Complex &, Complex &);
          ...
          Complex operator+(Complex &, Complex &);
          - - - - - +
          %rename(add_complex) operator+(Complex &, Complex &);
          +...
          +Complex operator+(Complex &, Complex &);
          - - - -

          Now, in Ruby, you can do this:

          - - - -
          -
          a = Example::Complex.new(2, 3)
          b = Example::Complex.new(4, -1)
          c = Example.add_complex(a, b)
          - - - - - +
          a = Example::Complex.new(2, 3)
          +b = Example::Complex.new(4, -1)
          +c = Example.add_complex(a, b)
          - - - -

          More details about wrapping C++ operators into Ruby operators is discussed in the section on operator overloading.

          - - - - -

          36.3.11 C++ namespaces

          +

          37.3.11 C++ namespaces

          SWIG is aware of C++ namespaces, but namespace names do not @@ -1961,63 +1124,48 @@ appear in the module nor do namespaces result in a module that is broken up into submodules or packages. For example, if you have a file like this,

          - - - -
          -
          %module example

          namespace foo {
          int fact(int n);
          struct Vector {
          double x,y,z;
          };
          };
          - - - - +
          %module example
           
          +namespace foo {
          +  int fact(int n);
          +  struct Vector {
          +    double x,y,z;
          +  };
          +};
          - - - -

          it works in Ruby as follows:

          - - - -
          -
          irb(main):001:0> require 'example'
          true
          irb(main):002:0> Example.fact(3)
          6
          irb(main):003:0> v = Example::Vector.new
          #<Example::Vector:0x4016f4d4>
          irb(main):004:0> v.x = 3.4
          3.4
          irb(main):004:0> v.y
          0.0
          - - - - - +
          irb(main):001:0> require 'example'
          +true
          +irb(main):002:0> Example.fact(3)
          +6
          +irb(main):003:0> v = Example::Vector.new
          +#<Example::Vector:0x4016f4d4>
          +irb(main):004:0> v.x = 3.4
          +3.4
          +irb(main):004:0> v.y
          +0.0
          - - - -

          If your program has more than one namespace, name conflicts (if any) can be resolved using %rename For example:

          - - - -
          -
          %rename(Bar_spam) Bar::spam;

          namespace Foo {
          int spam();
          }

          namespace Bar {
          int spam();
          }
          - - - +
          %rename(Bar_spam) Bar::spam;
           
          +namespace Foo {
          +  int spam();
          +}
           
          +namespace Bar {
          +  int spam();
          +}
          - - - -

          If you have more than one namespace and your want to keep their symbols separate, consider wrapping them as separate SWIG modules. For example, make the module name the same as the namespace @@ -2025,11 +1173,7 @@ and create extension modules for each namespace separately. If your program utilizes thousands of small deeply nested namespaces each with identical symbol names, well, then you get what you deserve.

          - - - - -

          36.3.12 C++ templates

          +

          37.3.12 C++ templates

          C++ templates don't present a huge problem for SWIG. However, @@ -2037,43 +1181,41 @@ in order to create wrappers, you have to tell SWIG to create wrappers for a particular template instantiation. To do this, you use the %template directive. For example:

          - - - -
          -
          %module example

          %{
          #include "pair.h"
          %}

          template<class T1, class T2>
          struct pair {
          typedef T1 first_type;
          typedef T2 second_type;
          T1 first;
          T2 second;
          pair();
          pair(const T1&, const T2&);
          ~pair();
          };

          %template(Pairii) pair<int,int>;
          - - +
          %module example
           
          +%{
          +#include "pair.h"
          +%}
           
          +template<class T1, class T2>
          +struct pair {
          +  typedef T1 first_type;
          +  typedef T2 second_type;
          +  T1 first;
          +  T2 second;
          +  pair();
          +  pair(const T1&, const T2&);
          +  ~pair();
          +};
           
          +%template(Pairii) pair<int,int>;
          - - - -

          In Ruby:

          - - - -
          -
          irb(main):001:0> require 'example'
          true
          irb(main):002:0> p = Example::Pairii.new(3, 4)
          #<Example:Pairii:0x4016f4df>
          irb(main):003:0> p.first
          3
          irb(main):004:0> p.second
          4
          - - - - - +
          irb(main):001:0> require 'example'
          +true
          +irb(main):002:0> p = Example::Pairii.new(3, 4)
          +#<Example:Pairii:0x4016f4df>
          +irb(main):003:0> p.first
          +3
          +irb(main):004:0> p.second
          +4
          - - - - -

          36.3.13 C++ Standard Template Library (STL)

          +

          37.3.13 C++ Standard Template Library (STL)

          On a related note, the standard SWIG library contains a @@ -2086,658 +1228,231 @@ convenient for users of your extension module to pass Ruby objects of standard C++ templates. For example, suppose the C++ library you're wrapping has a function that expects a vector of floats:

          - - - -
          -
          %module example

          float sum(const std::vector<float>& values);
          - - - - +
          %module example
           
          +float sum(const std::vector<float>& values);
          - - - -

          Rather than go through the hassle of writing an "in" typemap to convert an array of Ruby numbers into a std::vector<float>, you can just use the std_vector.i module from the standard SWIG library:

          - - - -
          -
          %module example

          %include std_vector.i
          float sum(const std::vector<float>& values);
          - - - - +
          %module example
           
          +%include std_vector.i
          +float sum(const std::vector<float>& values);
          - - - -

          Ruby's STL wrappings provide additional methods to make them behave more similarly to Ruby's native classes.

          - - - -

          Thus, you can do, for example:

          - - - -
          -
          v = IntVector.new
          v << 2

          v << 3
          v << 4
          v.each { |x| puts x }

          => 2

          3
          4
          v.delete_if { |x| x == 3 }
          => [2,4]
          - - - - +
          v = IntVector.new
          +v << 2
          +v << 3
          +v << 4
          +v.each { |x| puts x }
           
          +=> 2
          +3
          +4
          +v.delete_if { |x| x == 3 }
          +=> [2,4]
          - - - -

          The SWIG Ruby module provides also the ability for all the STL containers to carry around Ruby native objects (Fixnum, Classes, etc) -making them act almost like Ruby's own Array, Hash, etc.   To +making them act almost like Ruby's own Array, Hash, etc. To do that, you need to define a container that contains a swig::GC_VALUE, like:

          +
          +%module nativevector
           
          +%{
          +std::vector< swig::GC_VALUE > NativeVector;
          +%}
           
          -
          -
          -
          %module -nativevector
          - - - - - -
          - - - - - -%{
          - - - - - -std::vector< swig::GC_VALUE > NativeVector;
          - - - - - -%}
          - - - - - -
          - - - - - -%template(NativeVector) std::vector< swig::GC_VALUE >;
          - - - - - +%template(NativeVector) std::vector< swig::GC_VALUE >; +
          - - - - -
          - - - - -

          This vector can then contain any Ruby object, making them almost identical to Ruby's own Array class.

          +
          +
          require 'nativevector'
          +include NativeVector
           
          +v = NativeVector.new
          +v << 1
          +v << [1,2]
          +v << 'hello'
           
          +class A; end
           
          +v << A.new
           
          -
          require 'nativevector'
          - - - - - -include NativeVector
          - - - - - -
          - - - - - -v = NativeVector.new
          - - - - - -v << 1
          - - - - - -v << -[1,2]
          - - - - - -v << -'hello'
          - - - - - -
          - - - - - -class A; end
          - - - - - -
          - - - - - -v << -A.new
          - - - - - -
          - - - - - -puts v
          - - - - - -=> -[1, [1,2], 'hello', #<A:0x245325>]
          - - - - - -
          - - - - +puts v +=> [1, [1,2], 'hello', #<A:0x245325>] +
          +

          Obviously, there is a lot more to template wrapping than shown in these examples. More details can be found in the SWIG and C++ chapter.

          - - - - -

          36.3.14 C++ STL Functors

          +

          37.3.14 C++ STL Functors

          Some containers in the STL allow you to modify their default behavior by using so called functors or function objects. - Functors are often just a very simple struct with operator() -redefined or an actual C/C++ function.  This allows you, for +Functors are often just a very simple struct with operator() +redefined or an actual C/C++ function. This allows you, for example, to always keep the sort order of a STL container to your liking.

          - - - -

          The Ruby STL mappings allows you to modify those containers that support functors using Ruby procs or methods, instead. - Currently, -this includes std::set, -set::map, -std::multiset -and std::multimap.

          +Currently, +this includes std::set, +set::map, +std::multiset +and std::multimap.

          +

          The functors in swig are called swig::UnaryFunction +and swig::BinaryFunction. - - - -

          The functors in swig are called swig::UnaryFunction -and swig::BinaryFunction.
          - - - - - -For C++ predicates (ie. functors that must return bool as a result) swig::UnaryPredicate -and swig::BinaryPredicate +For C++ predicates (ie. functors that must return bool as a result) swig::UnaryPredicate +and swig::BinaryPredicate are provided.

          - - - -

          As an example, if given this swig file:

          +
          +%module intset;
           
          +%include <std_set.i>
           
          -
          -
          -
          %module -intset;
          - - - - - -
          - - - - - -%include <std_set.i>
          - - - - - -
          - - - - - -%typemap(IntSet)  std::set< int, swig::BinaryPredicate ->;
          - - - - +%typemap(IntSet) std::set< int, swig::BinaryPredicate >; +

          You can then use the set from Ruby with or without a proc object as a predicate:

          +
          +require 'intset'
          +include Intset
           
          -
          -
          -
          -
          require -'intset'
          - - - - - -include Intset
          - - - - - -
          - - - - - -# Default sorting behavior defined in C++
          - - - - - -a = IntSet.new
          - - - - - -a << 1
          - - - - - -a << 2
          - - - - - -a << 3
          - - - - - -a
          - - - - - -=> - [1,2,3]
          - - - - - -
          - - - - +# Default sorting behavior defined in C++ +a = IntSet.new +a << 1 +a << 2 +a << 3 +a +=> [1,2,3] # Custom sorting behavior defined by a Ruby proc -
          b = IntSet.new( proc { -|a,b| a > b } )
          - - - - - -b << 1
          - - - - - -b << 2
          - - - - - -b << 3
          - - - - - -b
          - - - - - -=> - [3,2,1]
          - - - - - +b = IntSet.new( proc { |a,b| a > b } ) +b << 1 +b << 2 +b << 3 +b +=> [3,2,1] +
          +

          37.3.15 C++ STL Iterators

          - - -

          36.3.15 C++ STL Iterators

          - - -

          The STL is well known for the use of iterators.  There +

          The STL is well known for the use of iterators. There are a number of iterators possible with different properties, but in general there are two main categories: const iterators and non-const -iterators.  The const iterators can access and not modify the +iterators. The const iterators can access and not modify the values they point at, while the non-const iterators can both read and modify the values.

          - - - -

          The Ruby STL wrappings support both type of iterators by using -a proxy class in-between.  This proxy class is swig::Iterator or -swig::ConstIterator.  Derived from them are template +a proxy class in-between. This proxy class is swig::Iterator or +swig::ConstIterator. Derived from them are template classes that need to be initialized with the actual iterator for the container you are wrapping and often times with the beginning and -ending points of the iteration range. 

          - - - - +ending points of the iteration range.

          The SWIG STL library already provides typemaps to all the standard containers to do this wrapping automatically for you, but if you have your own STL-like iterator, you will need to write your own -typemap for them.  For out typemaps, the special functions make_const_iterator and make_nonconst_iterator are provided.

          +typemap for them. For out typemaps, the special functions make_const_iterator and make_nonconst_iterator are provided.

          These can be used either like:

          -
          make_const_iterator( iterator, rubyclass );
          +
          +make_const_iterator( iterator, rubyclass );
          +make_const_iterator( iterator, iterator_begin, iterator_end, rubyclass );
          +
          -make_const_iterator( iterator, iterator_begin, iterator_end, rubyclass );
          - - - - - -

          The iterators support a next() and previous() member function to -just change the iterator without returning anything.  previous() -should obviously only be used for bidirectional iterators.  You +

          The iterators support a next() and previous() member function to +just change the iterator without returning anything. previous() +should obviously only be used for bidirectional iterators. You can also advance the iterator multiple steps by using standard math -operations like +=.

          +operations like +=.

          The -value the iterator points at can be accessed with value() -- this is equivalent to dereferencing it with *i. -  For non-const iterators, a value=() function +value the iterator points at can be accessed with value() -- this is equivalent to dereferencing it with *i. + For non-const iterators, a value=() function is also provided which allows you to change the value pointed by the -iterator.  This is equivalent to the C++ construct of dereferencing and assignment, like *i = something

          - - - - +iterator. This is equivalent to the C++ construct of dereferencing and assignment, like *i = something.

          Thus, given say a vector class of doubles defined as:

          +
          +
          +%module doublevector
           
          +%include std_vector.i
           
          -
          -
          -
          %module doublevector
          - - - - - -
          - - - - - -%include std_vector.i

          - - - - - -
          - - - - - -%template(DoubleVector) std::vector<double>;
          - - - - +%template(DoubleVector) std::vector<double>; +
          +

          Its iterator can then be used from Ruby like:

          - - - - -
          require -'doublevector'
          - - - - - -include Doublevector
          - -
          - - - - - -v = DoubleVector.new
          - - - - - -v << 1
          - - - - - -v << 2
          - - - - - -v << 3
          - -
          - -#
          - -# an elaborate and less efficient way of doing v.map! { |x| x+2 }
          - -#
          - - - - - -i = v.begin
          - - - - - -e = v.end
          - - - - - -while i != e
          - - - - - -  val = i.value
          - - - - - -  val += 2
          - - - - - -  i.value = val
          - - - - - -  i.next
          - - - - - -end
          - - - - -i
          - - - - ->> [3, 4, 5 ]
          - - - - - -
          - -

          If you'd rather have STL classes without any iterators, you should define -DSWIG_NO_EXPORT_ITERATOR_METHODS when running swig.

          - - - - - -

          36.3.16 C++ Smart Pointers

          +
          +
          +require 'doublevector'
          +include Doublevector
          +
          +v = DoubleVector.new
          +v << 1
          +v << 2
          +v << 3
          +
          +#
          +# an elaborate and less efficient way of doing v.map! { |x| x+2 }
          +#
          +i = v.begin
          +e = v.end
          +while i != e
          +  val = i.value
          +  val += 2
          +  i.value = val
          +  i.next
          +end
          +i
          +>> [3, 4, 5 ]
          +
          +
          + +

          If you'd rather have STL classes without any iterators, you should define -DSWIG_NO_EXPORT_ITERATOR_METHODS when running swig.

          + +

          37.3.16 C++ Smart Pointers

          In certain C++ programs, it is common to use classes that @@ -2745,124 +1460,64 @@ have been wrapped by so-called "smart pointers." Generally, this involves the use of a template class that implements operator->() like this:

          - - - -
          -
          template<class T> class SmartPtr {
          ...
          T *operator->();
          ...
          }
          - - - - - +
          template<class T> class SmartPtr {
          +  ...
          +  T *operator->();
          +  ...
          +}
          - - - -

          Then, if you have a class like this,

          - - - -
          -
          class Foo {
          public:
          int x;
          int bar();
          };
          - - - - - +
          class Foo {
          +public:
          +  int x;
          +  int bar();
          +};
          - - - -

          A smart pointer would be used in C++ as follows:

          - - - -
          -
          SmartPtr<Foo> p = CreateFoo(); // Created somehow (not shown)
          ...
          p->x = 3; // Foo::x
          int y = p->bar(); // Foo::bar
          - - - - - +
          SmartPtr<Foo> p = CreateFoo(); // Created somehow (not shown)
          +...
          +p->x = 3; // Foo::x
          +int y = p->bar(); // Foo::bar
          - - - -

          To wrap this in Ruby, simply tell SWIG about the SmartPtr class and the low-level Foo object. Make sure you instantiate SmartPtr using %template if necessary. For example:

          - - - -
          -
          %module example
          ...
          %template(SmartPtrFoo) SmartPtr<Foo>;
          ...
          - - - - - +
          %module example
          +...
          +%template(SmartPtrFoo) SmartPtr<Foo>;
          +...
          - - - -

          Now, in Ruby, everything should just "work":

          - - - -
          -
          irb(main):001:0> p = Example::CreateFoo() # Create a smart-pointer somehow
          #<Example::SmartPtrFoo:0x4016f4df>
          irb(main):002:0> p.x = 3 # Foo::x
          3
          irb(main):003:0> p.bar() # Foo::bar
          - - - - - +
          irb(main):001:0> p = Example::CreateFoo() # Create a smart-pointer somehow
          +#<Example::SmartPtrFoo:0x4016f4df>
          +irb(main):002:0> p.x = 3 # Foo::x
          +3
          +irb(main):003:0> p.bar() # Foo::bar
          - - - -

          If you ever need to access the underlying pointer returned by operator->() itself, simply use the __deref__() method. For example:

          - - - -
          -
          irb(main):004:0> f = p.__deref__() # Returns underlying Foo *
          - - - - - +
          irb(main):004:0> f = p.__deref__() # Returns underlying Foo *
          - - - - -

          36.3.17 Cross-Language Polymorphism

          +

          37.3.17 Cross-Language Polymorphism

          SWIG's Ruby module supports cross-language polymorphism @@ -2871,11 +1526,7 @@ module. Rather than duplicate the information presented in the 36.3.17.1 Exception Unrolling +

          37.3.17.1 Exception Unrolling

          Whenever a C++ director class routes one of its virtual @@ -2887,33 +1538,18 @@ change this behavior, you can use the %feature("director:except") directive to indicate what action should be taken when a Ruby exception is raised. The following code should suffice in most cases:

          - - - -
          -
          %feature("director:except") {
          throw Swig::DirectorMethodException($error);
          }
          - - - - - +
          %feature("director:except") {
          +  throw Swig::DirectorMethodException($error);
          +}
          - - - -

          When this feature is activated, the call to the Ruby instance method is "wrapped" using the rb_rescue2() function from Ruby's C API. If any Ruby exception is raised, it will be caught here and a C++ exception is raised in its place.

          - - - - -

          36.4 Naming

          +

          37.4 Naming

          Ruby has several common naming conventions. Constants are @@ -2921,95 +1557,37 @@ generally in upper case, module and class names are in camel case and methods are in lower case with underscores. For example:

          - - - -
            - - - - -
          • MATH::PI is a constant name
          • - - - - -
          • MyClass is a class name
          • - - - - -
          • my_method is a method name
          • - - - - -
          - - - - -
          - - - -

          Prior to version 1.3.28, SWIG did not support these Ruby conventions. The only modifications it made to names was to capitalize the first letter of constants (which includes module and class names).

          - - - -

          SWIG 1.3.28 introduces the new -autorename command line parameter. When this parameter is specified, SWIG will automatically change constant, class and method names to conform with the standard Ruby naming conventions. For example:

          - - - -
          -
          $ swig -ruby -autorename example.i
          +
          $ swig -ruby -autorename example.i
           
          - - - - -
          - - - -

          To disable renaming use the -noautorename command line option.

          - - - -

          Since this change significantly changes the wrapper code generated by SWIG, it is turned off by default in SWIG 1.3.28. However, it is planned to become the default option in future releases.

          - - - - -

          36.4.1 Defining Aliases

          +

          37.4.1 Defining Aliases

          It's a fairly common practice in the Ruby built-ins and @@ -3020,65 +1598,51 @@ approach is to use SWIG's %extend directive to add a new method of the aliased name that calls the original function. For example:

          - - - -
          -
          class MyArray {
          public:
          // Construct an empty array
          MyArray();

          // Return the size of this array
          size_t length() const;
          };

          %extend MyArray {
          // MyArray#size is an alias for MyArray#length
          size_t size() const {
          return $self->length();
          }
          }
          - - - +
          class MyArray {
          +public:
          +  // Construct an empty array
          +  MyArray();
           
          +  // Return the size of this array
          +  size_t length() const;
          +};
           
          +%extend MyArray {
          +  // MyArray#size is an alias for MyArray#length
          +  size_t size() const {
          +    return $self->length();
          +  }
          +}
          + 
          - - - -

          A better solution is to use the %alias directive (unique to SWIG's Ruby module). The previous example could then be rewritten as:

          - - - -
          -
          // MyArray#size is an alias for MyArray#length
          %alias MyArray::length "size";

          class MyArray {
          public:
          // Construct an empty array
          MyArray();

          // Return the size of this array
          size_t length() const;
          };

          - - - - +
          // MyArray#size is an alias for MyArray#length
          +%alias MyArray::length "size";
           
          +class MyArray {
          +public:
          +  // Construct an empty array
          +  MyArray();
          + 
          +  // Return the size of this array
          +  size_t length() const;
          +};
          - - - -

          Multiple aliases can be associated with a method by providing a comma-separated list of aliases to the %alias directive, e.g.

          - - - -
          %alias MyArray::length "amount,quantity,size";
          - - - - -
          - - - -

          From an end-user's standpoint, there's no functional difference between these two approaches; i.e. they should get the same result from calling either MyArray#size or MyArray#length. @@ -3087,21 +1651,13 @@ doesn't need to generate all of the wrapper code that's usually associated with added methods like our MyArray::size() example.

          - - - -

          Note that the %alias directive is implemented using SWIG's "features" mechanism and so the same name matching rules used for other kinds of features apply (see the chapter on "Customization Features") for more details).

          - - - - -

          36.4.2 Predicate Methods

          +

          37.4.2 Predicate Methods

          Ruby methods that return a boolean value and end in a @@ -3114,83 +1670,43 @@ if the object is an instance of the specified class). For consistency with Ruby conventions, methods that return boolean values should be marked as predicate methods.

          - - - -

          One cumbersome solution to this problem is to rename the method (using SWIG's %rename directive) and provide a custom typemap that converts the function's actual return type to Ruby's true or false. For example:

          - - - -
          -
          %rename("is_it_safe?") is_it_safe();

          %typemap(out) int is_it_safe
          "$result = ($1 != 0) ? Qtrue : Qfalse;";

          int is_it_safe();

          - - - +
          %rename("is_it_safe?") is_it_safe();
           
          +%typemap(out) int is_it_safe "$result = ($1 != 0) ? Qtrue : Qfalse;";
           
          +int is_it_safe();
          - - - -

          A better solution is to use the %predicate directive (unique to SWIG's Ruby module) to designate a method as a predicate method. For the previous example, this would look like:

          - - - -
          -
          %predicate is_it_safe();

          int is_it_safe();

          - - - - +
          %predicate is_it_safe();
           
          +int is_it_safe();
          - - - -

          This method would be invoked from Ruby code like this:

          - - - -
          -
          irb(main):001:0> Example::is_it_safe?
          true

          - - - - - +
          irb(main):001:0> Example::is_it_safe?
          +true
          - - - -

          The %predicate directive is implemented using SWIG's "features" mechanism and so the same name matching rules used for other kinds of features apply (see the chapter on "Customization Features") for more details).

          - - - - -

          36.4.3 Bang Methods

          +

          37.4.3 Bang Methods

          Ruby methods that modify an object in-place and end in an @@ -3201,384 +1717,205 @@ which returns a copy of the array with the items sorted instead of modifying the original array. For consistency with Ruby conventions, methods that modify objects in place should be marked as bang methods.

          - - - -

          Bang methods can be marked using the %bang directive which is unique to the Ruby module and was introduced in SWIG 1.3.28. For example:

          - - - -
          -
          %bang sort!(arr);

          int sort(int arr[]);
          - - - - +
          %bang sort(int arr[]);
           
          +int sort(int arr[]); 
          - - - -

          This method would be invoked from Ruby code like this:

          - - - -
          irb(main):001:0> Example::sort!(arr)
          - - - - -
          - - - -

          The %bang directive is implemented using SWIG's "features" mechanism and so the same name matching rules used for other kinds of features apply (see the chapter on "Customization Features") for more details).

          - - - - -

          36.4.4 Getters and Setters

          +

          37.4.4 Getters and Setters

          Often times a C++ library will expose properties through getter and setter methods. For example:

          - - - -
          -
          class Foo {
          Foo() {}

          int getValue() { return value_; }

          void setValue(int value) { value_ = value; }

          private:
          int value_;
          };
          - - - - +
          class Foo {
          +  Foo() {}
          +  int getValue() { return value_; }
          +  void setValue(int value) { value_ = value; }
           
          +private:
          +  int value_;
          +};
          - - - -

          By default, SWIG will expose these methods to Ruby as get_value and set_value. However, it more natural for these methods to be exposed in Ruby as value and value=. That allows the methods to be used like this:

          - - - -
          -
          irb(main):001:0> foo = Foo.new()
          irb(main):002:0> foo.value = 5
          irb(main):003:0> puts foo.value
          - - - - - +
          irb(main):001:0> foo = Foo.new()
          +irb(main):002:0> foo.value = 5
          +irb(main):003:0> puts foo.value
          - - - -

          This can be done by using the %rename directive:

          - - - -
          -
          %rename("value") Foo::getValue();
          %rename("value=") Foo::setValue(int value);
          - - - - - +
          %rename("value") Foo::getValue();
          +%rename("value=") Foo::setValue(int value);
          - - - - -

           

          - - - - - -

          36.5 Input and output parameters

          +

          37.5 Input and output parameters

          A common problem in some C programs is handling parameters passed as simple pointers. For example:

          - - - -
          -
          void add(int x, int y, int *result) {
          *result = x + y;
          }
          or
          int sub(int *x, int *y) {
          return *x-*y;
          }
          - - - - - +
          void add(int x, int y, int *result) {
          +  *result = x + y;
          +}
          +

          +or +

          - - +
          +
          +int sub(int *x, int *y) {
          +  return *x-*y;
          +}
          +

          The easiest way to handle these situations is to use the typemaps.i file. For example:

          - - - -
          -
          %module Example
          %include "typemaps.i"

          void add(int, int, int *OUTPUT);
          int sub(int *INPUT, int *INPUT);
          - - - - +
          %module Example
          +%include "typemaps.i"
           
          +void add(int, int, int *OUTPUT);
          +int sub(int *INPUT, int *INPUT);
          - - - -

          In Ruby, this allows you to pass simple values. For example:

          - - - -
          -
          a = Example.add(3,4)
          puts a
          7
          b = Example.sub(7,4)
          puts b
          3
          - - - - - +
          a = Example.add(3,4)
          +puts a
          +7
          +b = Example.sub(7,4)
          +puts b
          +3
          - - - -

          Notice how the INPUT parameters allow integer values to be passed instead of pointers and how the OUTPUT parameter creates a return result.

          - - - -

          If you don't want to use the names INPUT or OUTPUT, use the %apply directive. For example:

          - - - -
          -
          %module Example
          %include "typemaps.i"

          %apply int *OUTPUT { int *result };
          %apply int *INPUT { int *x, int *y};

          void add(int x, int y, int *result);
          int sub(int *x, int *y);
          - - - +
          %module Example
          +%include "typemaps.i"
           
          +%apply int *OUTPUT { int *result };
          +%apply int *INPUT { int *x, int *y};
           
          +void add(int x, int y, int *result);
          +int sub(int *x, int *y);
          - - - -

          If a function mutates one of its parameters like this,

          - - - -
          -
          void negate(int *x) {
          *x = -(*x);
          }
          - - - - - +
          void negate(int *x) {
          + *x = -(*x);
          +}
          - - - -

          you can use INOUT like this:

          - - - -
          -
          %include "typemaps.i"
          ...
          void negate(int *INOUT);
          - - - - - +
          %include "typemaps.i"
          +...
          +void negate(int *INOUT);
          - - - -

          In Ruby, a mutated parameter shows up as a return value. For example:

          - - - -
          -
          a = Example.negate(3)
          print a
          -3

          - - - - - +
          a = Example.negate(3)
          +print a
          +-3
          - - - -

          The most common use of these special typemap rules is to handle functions that return more than one value. For example, sometimes a function returns a result as well as a special error code:

          - - - -
          -
          /* send message, return number of bytes sent, success code, and error_code */
          int send_message(char *text, int *success, int *error_code);
          - - - - - +
          /* send message, return number of bytes sent, success code, and error_code */
          +int send_message(char *text, int *success, int *error_code);
          - - - -

          To wrap such a function, simply use the OUTPUT rule above. For example:

          - - - -
          -
          %module example
          %include "typemaps.i"
          ...
          int send_message(char *, int *OUTPUT, int *OUTPUT);
          - - - - - +
          %module example
          +%include "typemaps.i"
          +...
          +int send_message(char *, int *OUTPUT, int *OUTPUT);
          - - - -

          When used in Ruby, the function will return an array of multiple values.

          - - - -
          -
          bytes, success, error_code = send_message("Hello World")
          if not success
          print "error #{error_code} : in send_message"
          else
          print "Sent", bytes
          end
          - - - - - +
          bytes, success, error_code = send_message("Hello World")
          +if not success
          +  print "error #{error_code} : in send_message"
          +else
          +  print "Sent", bytes
          +end
          - - - -

          Another way to access multiple return values is to use the %apply rule. In the following example, the parameters rows and columns are related to SWIG as OUTPUT values through the use of %apply

          - - - -
          -
          %module Example
          %include "typemaps.i"
          %apply int *OUTPUT { int *rows, int *columns };
          ...
          void get_dimensions(Matrix *m, int *rows, int*columns);
          - - - - - +
          %module Example
          +%include "typemaps.i"
          +%apply int *OUTPUT { int *rows, int *columns };
          +...
          +void get_dimensions(Matrix *m, int *rows, int*columns);
          - - - -

          In Ruby:

          - - - -
          -
          r, c = Example.get_dimensions(m)
          - - - - - +
          r, c = Example.get_dimensions(m)
          +

          37.6 Exception handling

          - - -

          36.6 Exception handling

          - - -

          36.6.1 Using the %exception directive

          +

          37.6.1 Using the %exception directive

          The SWIG %exception directive can be @@ -3587,1013 +1924,317 @@ C/C++ errors into Ruby exceptions. The chapter on -

          class DoubleArray {
          private:
          int n;
          double *ptr;
          public:
          // Create a new array of fixed size
          DoubleArray(int size) {
          ptr = new double[size];
          n = size;
          }

          // Destroy an array
          ~DoubleArray() {
          delete ptr;
          }

          // Return the length of the array
          int length() {
          return n;
          }

          // Get an array item and perform bounds checking.
          double getitem(int i) {
          if ((i >= 0) && (i < n))
          return ptr[i];
          else
          throw RangeError();
          }

          // Set an array item and perform bounds checking.
          void setitem(int i, double val) {
          if ((i >= 0) && (i < n))
          ptr[i] = val;
          else {
          throw RangeError();
          }
          }
          };
          - - - - - +
          class DoubleArray {
          +private:
          +  int n;
          +  double *ptr;
          +public:
          +  // Create a new array of fixed size
          +  DoubleArray(int size) {
          +    ptr = new double[size];
          +    n = size;
          +  }
          + 
          +  // Destroy an array
          +  ~DoubleArray() {
          +    delete ptr;
          +  } 
          + 
          +  // Return the length of the array
          +  int length() {
          +    return n;
          +  }
          + 
          +  // Get an array item and perform bounds checking.
          +  double getitem(int i) {
          +    if ((i >= 0) && (i < n))
          +      return ptr[i];
          +    else
          +      throw RangeError();
          +  }
          + 
          +  // Set an array item and perform bounds checking.
          +  void setitem(int i, double val) {
          +    if ((i >= 0) && (i < n))
          +      ptr[i] = val;
          +    else {
          +      throw RangeError();
          +    }
          +  }
          +};
      - - - -

      Since several methods in this class can throw an exception for an out-of-bounds access, you might want to catch this in the Ruby extension by writing the following in an interface file:

      - - - -
      -
      %exception {
      try {
      $action
      }
      catch (const RangeError&) {
      static VALUE cpperror = rb_define_class("CPPError", rb_eStandardError);
      rb_raise(cpperror, "Range error.");
      }
      }

      class DoubleArray {
      ...
      };
      - - - - +
      %exception {
      +  try {
      +    $action
      +  }
      +  catch (const RangeError&) {
      +    static VALUE cpperror = rb_define_class("CPPError", rb_eStandardError);
      +    rb_raise(cpperror, "Range error.");
      +  }
      +}
       
      +class DoubleArray {
      +  ...
      +};
      - - - -

      The exception handling code is inserted directly into generated wrapper functions. When an exception handler is defined, errors can be caught and used to gracefully raise a Ruby exception instead of forcing the entire program to terminate with an uncaught error.

      - - - -

      As shown, the exception handling code will be added to every wrapper function. Because this is somewhat inefficient, you might consider refining the exception handler to only apply to specific methods like this:

      - - - -
      -
      %exception getitem {
      try {
      $action
      }
      catch (const RangeError&) {
      static VALUE cpperror = rb_define_class("CPPError", rb_eStandardError);
      rb_raise(cpperror, "Range error in getitem.");
      }
      }

      %exception setitem {
      try {
      $action
      }
      catch (const RangeError&) {
      static VALUE cpperror = rb_define_class("CPPError", rb_eStandardError);
      rb_raise(cpperror, "Range error in setitem.");
      }
      }
      - - - - - +
      %exception getitem {
      +  try {
      +    $action
      +  } catch (const RangeError&) {
      +    static VALUE cpperror = rb_define_class("CPPError", rb_eStandardError);
      +    rb_raise(cpperror, "Range error in getitem.");
      +  }
      +}
      + 
      +%exception setitem {
      +  try {
      +    $action
      +  } catch (const RangeError&) {
      +    static VALUE cpperror = rb_define_class("CPPError", rb_eStandardError);
      +    rb_raise(cpperror, "Range error in setitem.");
      +  }
      +}
      - - - -

      In this case, the exception handler is only attached to methods and functions named getitem and setitem.

      - - - -

      Since SWIG's exception handling is user-definable, you are not limited to C++ exception handling. See the chapter on Customization Features for more examples.

      - - - - -

      36.6.2 Handling Ruby Blocks

      +

      37.6.2 Handling Ruby Blocks

      One of the highlights of Ruby and most of its standard library is the use of blocks, which allow the easy creation of continuations and -other niceties.  Blocks in ruby are also often used to +other niceties. Blocks in ruby are also often used to simplify the passing of many arguments to a class.

      - - - -

      In order to make your class constructor support blocks, you can take advantage of the %exception directive, which will get run -after the C++ class' constructor was called. 

      - - - - +after the C++ class' constructor was called.

      For example, this yields the class over after its construction: -
      - - - - -

      - - - -
      -
      class Window
      {
      public:
      Window(int x, int y, int w, int h);
      // .... other methods here ....
      };

      // Add support for yielding self in the Class' constructor.
      %exception Window::Window {
      $action
      if (rb_block_given_p()) {
      rb_yield(self);
      }
      }
      - - - - +
      class Window
      +{
      +public:
      +  Window(int x, int y, int w, int h);
      +  // .... other methods here ....
      +};
       
      +// Add support for yielding self in the Class' constructor.
      +%exception Window::Window {
      +  $action
      +  if (rb_block_given_p()) {
      +    rb_yield(self);
      +  }
      +}
      - - - -

      Then, in ruby, it can be used like:

      - - - - -
      Window.new(0,0,360,480) -{ |w|
      - - - - - -    w.color = Fltk::RED
      - - - - - -    w.border = false
      - - - - - -}
      - - - - - -
      - - - - +
      +Window.new(0,0,360,480) { |w|
      +  w.color = Fltk::RED
      +  w.border = false
      +}
      +
      +

      For other methods, you can usually use a dummy parameter with a special in typemap, like:

      - - - - -
      //
      - - - - - -// original function was:
      - - - - - -//
      - - - - - -// void func(int x);
      - - - - - -
      - - - - - -%typemap(in,numinputs=0) int RUBY_YIELD_SELF {
      - - - - - -     if ( !rb_block_given_p() )
      - - - - - -            -rb_raise("No block given");
      - - - - - -     return rb_yield(self);
      - - - - - -}
      - - - - - -
      - - - - - -%extend {
      - - - - - -        void func(int x, int -RUBY_YIELD_SELF );
      - - - - - -}
      - - - - +
      +//
      +// original function was:
      +//
      +// void func(int x);
      +
      +%typemap(in,numinputs=0) int RUBY_YIELD_SELF {
      +  if ( !rb_block_given_p() )
      +    rb_raise("No block given");
      +  return rb_yield(self);
      +}
      +
      +%extend {
      +  void func(int x, int RUBY_YIELD_SELF );
      +}
      +
      +

      For more information on typemaps, see Typemaps.

      - -

      36.6.3 Raising exceptions

      +

      37.6.3 Raising exceptions

      There are three ways to raise exceptions from C++ code to Ruby.

      - - - -

      The first way is to use SWIG_exception(int code, const char *msg). The following table shows the mappings from SWIG error codes to Ruby exceptions:

      - - - -
    • - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - -
      - - - - +
      SWIG_MemoryError
      - - - - -
      - - - - +
      rb_eNoMemError
      - - - - -
      - - - - +
      SWIG_IOError
      - - - - -
      - - - - +
      rb_eIOError
      - - - - -
      - - - - +
      SWIG_RuntimeError
      - - - - -
      - - - - +
      rb_eRuntimeError
      - - - - -
      - - - - +
      SWIG_IndexError
      - - - - -
      - - - - +
      rb_eIndexError
      - - - - -
      - - - - +
      SWIG_TypeError
      - - - - -
      - - - - +
      rb_eTypeError
      - - - - -
      - - - - +
      SWIG_DivisionByZero
      - - - - -
      - - - - +
      rb_eZeroDivError
      - - - - -
      - - - - +
      SWIG_OverflowError
      - - - - -
      - - - - +
      rb_eRangeError
      - - - - -
      - - - - +
      SWIG_SyntaxError
      - - - - -
      - - - - +
      rb_eSyntaxError
      - - - - -
      - - - - +
      SWIG_ValueError
      - - - - -
      - - - - +
      rb_eArgError
      - - - - -
      - - - - +
      SWIG_SystemError
      - - - - -
      - - - - +
      rb_eFatal
      - - - - -
      - - - - +
      SWIG_AttributeError
      - - - - -
      - - - - +
      rb_eRuntimeError
      - - - - -
      - - - - +
      SWIG_NullReferenceError
      - - - - -
      - - - - +
      rb_eNullReferenceError*
      - - - - -
      - - - - +
      SWIG_ObjectPreviouslyDeletedError
      - - - - -
      - - - - +
      rb_eObjectPreviouslyDeleted*
      - - - - -
      - - - - +
      SWIG_UnknownError
      - - - - -
      - - - - +
      rb_eRuntimeError
      - - - - -
      - - - -
      * These error classes are created by SWIG and are not built-in Ruby exception classes
      - - - - -
      - - - - - - - - -

      The second way to raise errors is to use SWIG_Raise(obj, type, desc). Obj is a C++ instance of an exception class, type is a string specifying the type of exception (for example, "MyError") and desc is the SWIG description of the exception class. For example:

      - - - - -
      -%raise(SWIG_NewPointerObj(e, -SWIGTYPE_p_AssertionFailedException, -0), ":AssertionFailedException", SWIGTYPE_p_AssertionFailedException);
      - - - - +
      +%raise(SWIG_NewPointerObj(e, SWIGTYPE_p_AssertionFailedException, 0), ":AssertionFailedException", SWIGTYPE_p_AssertionFailedException);
      +

      This is useful when you want to pass the current exception object @@ -4601,21 +2242,13 @@ directly to Ruby, particularly when the object is an instance of class marked as an %exceptionclass (see the next section for more information).

      - - - -

      Last, you can raise an exception by directly calling Ruby's C api. This is done by invoking the rb_raise() function. The first argument passed to rb_raise() is the exception type. You can raise a custom exception type or one of the built-in Ruby exception types.

      - - - - -

      36.6.4 Exception classes

      +

      37.6.4 Exception classes

      Starting with SWIG 1.3.28, the Ruby module supports the %exceptionclass @@ -4625,185 +2258,115 @@ directive are exposed in Ruby as child classes of rb_eRuntimeError. This allows C++ exceptions to be directly mapped to Ruby exceptions, providing for a more natural integration between C++ code and Ruby code.

      - - - -
      -
      	%exceptionclass CustomError;

      %inline %{
      class CustomError { };

      class Foo {
      public:
      void test() { throw CustomError; }
      };
      }
      - - - +
      %exceptionclass CustomError;
       
      +%inline %{
      +  class CustomError { };
       
      +  class Foo { 
      +  public:
      +    void test() { throw CustomError; }
      +  };
      +%}
      - - - -

      From Ruby you can now call this method like this:

      - - - -
      -
      foo = Foo.new
      begin
      foo.test()
      rescue CustomError => e
      puts "Caught custom error"
      end
      - - - - - +
      foo = Foo.new
      +begin
      +  foo.test()
      +rescue CustomError => e
      +  puts "Caught custom error"
      +end 
      - - - - -

      For another example look at swig/Examples/ruby/exception_class.
      - - - - - +

      For another example look at swig/Examples/ruby/exception_class.

      - - - - -

      36.7 Typemaps

      +

      37.7 Typemaps

      This section describes how you can modify SWIG's default wrapping behavior for various C/C++ datatypes using the %typemap directive. This is an advanced topic that assumes familiarity with the Ruby C API as well as the material in the "Typemaps" -chapter.  +chapter.

      - - - -

      Before proceeding, it should be stressed that typemaps are not a required part of using SWIG---the default wrapping behavior is enough in most cases. Typemaps are only used if you want to change some aspect of the primitive C-Ruby interface.

      - - - - -

      36.7.1 What is a typemap?

      +

      37.7.1 What is a typemap?

      A typemap is nothing more than a code generation rule that is attached to a specific C datatype. The general form of this declaration is as follows ( parts enclosed in [...] are optional -):    

      - - - - - -
      %typemap( method [, modifiers...] ) typelist -code;
      - - - +):

      +
      +
      +%typemap( method [, modifiers...] ) typelist code;
      +
      +

      method is a simply a name that specifies what kind of typemap is being defined. It is usually a name like "in", "out", or "argout" (or its director variations). The purpose of these methods is described later.

      - - - -

      modifiers is an optional comma separated list of name="value" values. These are sometimes to attach extra information to a typemap and is often target-language dependent.

      - - - -

      typelist is a list of the C++ type patterns that the typemap will match. The general form of this list is as follows:

      - - - -
      -
      typelist : typepattern [, typepattern, typepattern, ... ] ;

      typepattern : type [ (parms) ]
      | type name [ (parms) ]
      | ( typelist ) [ (parms) ]
      - - - - +
      typelist : typepattern [, typepattern, typepattern, ... ] ;
       
      +typepattern : type [ (parms) ]
      +  | type name [ (parms) ]
      +  | ( typelist ) [ (parms) ]
      - - - -

      Each type pattern is either a simple type, a simple type and argument name, or a list of types in the case of multi-argument typemaps. In addition, each type pattern can be parameterized with a list of temporary variables (parms). The purpose of these variables will be explained shortly.

      - - - -

      code specifies the C code used in the typemap. It can take any one of the following forms:

      - - - -
      -
      code : { ... }
      | " ... "
      | %{ ... %}
      - - - - - +
      code : { ... }
      +  | " ... "
      +  | %{ ... %}
      - - - -

      For example, to convert integers from Ruby to C, you might define a typemap like this:

      - - - -
      -
      %module example

      %typemap(in) int {
      $1 = (int) NUM2INT($input);
      printf("Received an integer : %d\n",$1);
      }

      %inline %{
      extern int fact(int n);
      %}
      - - - +
      %module example
       
      +%typemap(in) int {
      +  $1 = (int) NUM2INT($input);
      +  printf("Received an integer : %d\n",$1);
      +}
       
      +%inline %{
      +  extern int fact(int n);
      +%}
      - - - -

      Typemaps are always associated with some specific aspect of code generation. In this case, the "in" method refers to the conversion of input arguments to C/C++. The datatype int is @@ -4813,77 +2376,44 @@ prefaced by a $ are used. The $1 variable is placeholder for a local variable of type int. The $input variable is the input Ruby object.

      - - - -

      When this example is compiled into a Ruby module, the following sample code:

      - - - -
      -
      require 'example'

      puts Example.fact(6)
      - - - - +
      require 'example'
       
      +puts Example.fact(6)
      - - - -

      prints the result:

      - - - -
      -
      Received an integer : 6
      720
      - - - - - +
      +Received an integer : 6
      +720
      +
      - - - -

      In this example, the typemap is applied to all occurrences of the int datatype. You can refine this by supplying an optional parameter name. For example:

      - - - -
      -
      %module example

      %typemap(in) int n {
      $1 = (int) NUM2INT($input);
      printf("n = %d\n",$1);
      }

      %inline %{
      extern int fact(int n);
      %}
      - - - +
      %module example
       
      +%typemap(in) int n {
      +  $1 = (int) NUM2INT($input);
      +  printf("n = %d\n",$1);
      +}
       
      +%inline %{
      +  extern int fact(int n);
      +%}
      - - - -

      In this case, the typemap code is only attached to arguments that exactly match "int n".

      - - - -

      The application of a typemap to specific datatypes and argument names involves more than simple text-matching--typemaps are fully integrated into the SWIG type-system. When you define a typemap @@ -4892,96 +2422,65 @@ and qualified variations such as const int. In addition, the typemap system follows typedef declarations. For example:

      - - - -
      -
      %typemap(in) int n {
      $1 = (int) NUM2INT($input);
      printf("n = %d\n",$1);
      }

      typedef int Integer;
      extern int fact(Integer n); // Above typemap is applied
      - - - - +
      %typemap(in) int n {
      +  $1 = (int) NUM2INT($input);
      +  printf("n = %d\n",$1);
      +}
       
      +typedef int Integer;
      +extern int fact(Integer n); // Above typemap is applied
      - - - -

      However, the matching of typedef only occurs in one direction. If you defined a typemap for Integer, it is not applied to arguments of type int.

      - - - -

      Typemaps can also be defined for groups of consecutive arguments. For example:

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

      When a multi-argument typemap is defined, the arguments are always handled as a single Ruby object. This allows the function count to be used as follows (notice how the length parameter is omitted):

      - - - -
      -
      puts Example.count('o','Hello World')
      2
      - - - - - +
      puts Example.count('o','Hello World')
      +2
      - - - - -

      36.7.2 Typemap scope

      +

      37.7.2 Typemap scope

      Once defined, a typemap remains in effect for all of the declarations that follow. A typemap may be redefined for different sections of an input file. For example:

      - - - -
      -
      // typemap1
      %typemap(in) int {
      ...
      }

      int fact(int); // typemap1
      int gcd(int x, int y); // typemap1

      // typemap2
      %typemap(in) int {
      ...
      }

      int isprime(int); // typemap2
      - - +
      // typemap1
      +%typemap(in) int {
      +  ...
      +}
       
      +int fact(int); // typemap1
      +int gcd(int x, int y); // typemap1
       
      +// typemap2
      +%typemap(in) int {
      +  ...
      +}
       
      +int isprime(int); // typemap2
      - - - -

      One exception to the typemap scoping rules pertains to the %extend declaration. %extend is used to attach new declarations to a class or structure definition. Because @@ -4989,250 +2488,152 @@ of this, all of the declarations in an %extend block are subject to the typemap rules that are in effect at the point where the class itself is defined. For example:

      - - - -
      -
      class Foo {
      ...
      };

      %typemap(in) int {
      ...
      }

      %extend Foo {
      int blah(int x); // typemap has no effect. Declaration is attached to Foo which
      // appears before the %typemap declaration.
      };
      - - - +
      class Foo {
      +  ...
      +};
       
      +%typemap(in) int {
      +  ...
      +}
       
      +%extend Foo {
      +  int blah(int x); // typemap has no effect. Declaration is attached to Foo which 
      +  // appears before the %typemap declaration.
      +};
      - - - - -

      36.7.3 Copying a typemap

      +

      37.7.3 Copying a typemap

      A typemap is copied by using assignment. For example:

      - - - -
      -
      %typemap(in) Integer = int;
      - - - - - +
      %typemap(in) Integer = int;
      - - - -

      or this:

      - - - -
      -
      %typemap(in) Integer, Number, int32_t = int;
      - - - - - +
      %typemap(in) Integer, Number, int32_t = int;
      - - - -

      Types are often managed by a collection of different typemaps. For example:

      - - - -
      -
      %typemap(in) int { ... }
      %typemap(out) int { ... }
      %typemap(varin) int { ... }
      %typemap(varout) int { ... }
      - - - - - +
      %typemap(in) int { ... }
      +%typemap(out) int { ... }
      +%typemap(varin) int { ... }
      +%typemap(varout) int { ... }
      - - - -

      To copy all of these typemaps to a new type, use %apply. For example:

      - - - -
      -
      %apply int { Integer }; // Copy all int typemaps to Integer
      %apply int { Integer, Number }; // Copy all int typemaps to both Integer and Number
      - - - - - +
      %apply int { Integer }; // Copy all int typemaps to Integer
      +%apply int { Integer, Number }; // Copy all int typemaps to both Integer and Number
      - - - -

      The patterns for %apply follow the same rules as for %typemap. For example:

      - - - -
      -
      %apply int *output { Integer *output }; // Typemap with name
      %apply (char *buf, int len) { (char *buffer, int size) }; // Multiple arguments
      - - - - - +
      %apply int *output { Integer *output }; // Typemap with name
      +%apply (char *buf, int len) { (char *buffer, int size) }; // Multiple arguments
      - - - - -

      36.7.4 Deleting a typemap

      +

      37.7.4 Deleting a typemap

      A typemap can be deleted by simply defining no code. For example:

      - - - -
      -
      %typemap(in) int; // Clears typemap for int
      %typemap(in) int, long, short; // Clears typemap for int, long, short
      %typemap(in) int *output;
      - - - - - +
      %typemap(in) int; // Clears typemap for int
      +%typemap(in) int, long, short; // Clears typemap for int, long, short
      +%typemap(in) int *output; 
      - - - -

      The %clear directive clears all typemaps for a given type. For example:

      - - - -
      -
      %clear int; // Removes all types for int
      %clear int *output, long *output;
      - - - - - +
      %clear int; // Removes all types for int
      +%clear int *output, long *output;
      - - - -

      Note: Since SWIG's default behavior is defined by typemaps, clearing a fundamental type like int will make that type unusable unless you also define a new set of typemaps immediately after the clear operation.

      - - - - -

      36.7.5 Placement of typemaps

      +

      37.7.5 Placement of typemaps

      Typemap declarations can be declared in the global scope, within a C++ namespace, and within a C++ class. For example:

      - - - -
      -
      %typemap(in) int {
      ...
      }

      namespace std {
      class string;
      %typemap(in) string {
      ...
      }
      }

      class Bar {
      public:
      typedef const int & const_reference;
      %typemap(out) const_reference {
      ...
      }
      };
      - - - +
      %typemap(in) int {
      +  ...
      +}
       
      +namespace std {
      +  class string;
      +  %typemap(in) string {
      +    ...
      +  }
      +}
       
      +class Bar {
      +public:
      +  typedef const int & const_reference;
      +  %typemap(out) const_reference {
      +    ...
      +  }
      +};
      - - - -

      When a typemap appears inside a namespace or class, it stays in effect until the end of the SWIG input (just like before). However, the typemap takes the local scope into account. Therefore, this code

      - - - -
      -
      namespace std {
      class string;
      %typemap(in) string {
      ...
      }
      }
      - - - - - +
      namespace std {
      +  class string;
      +  %typemap(in) string {
      +    ...
      +  }
      +}
      - - - -

      is really defining a typemap for the type std::string. You could have code like this:

      - - - -
      -
      namespace std {
      class string;
      %typemap(in) string { /* std::string */
      ...
      }
      }

      namespace Foo {
      class string;
      %typemap(in) string { /* Foo::string */
      ...
      }
      }
      - - - - +
      namespace std {
      +  class string;
      +  %typemap(in) string { /* std::string */
      +  ...
      +  }
      +}
       
      +namespace Foo {
      +  class string;
      +  %typemap(in) string { /* Foo::string */
      +  ...
      +  }
      +}
      - - - -

      In this case, there are two completely distinct typemaps that apply to two completely different types (std::string and Foo::string).

      - - - -

      It should be noted that for scoping to work, SWIG has to know that string is a typename defined within a particular namespace. @@ -5240,537 +2641,153 @@ In this example, this is done using the class declaration class string .

      - - - - -

      36.7.6 Ruby typemaps

      +

      37.7.6 Ruby typemaps

      The following list details all of the typemap methods that can be used by the Ruby module:

      - - - - -

      36.7.6.1  "in" typemap

      +

      37.7.6.1 "in" typemap

      Converts Ruby objects to input function arguments. For example:

      - - - -
      -
      %typemap(in) int {
      $1 = NUM2INT($input);
      }
      - - - - - +
      %typemap(in) int {
      +  $1 = NUM2INT($input);
      +}
      - - - -

      The following special variables are available:

      - - - -
      - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - -
      $input Input object + $input Input object holding value to be converted.
      $symname Name of + $symname Name of function/method being wrapped
      $1...n Argument being + $1...n Argument being sent to the function
      $1_name Name of the + $1_name Name of the argument (if provided)
      $1_type The actual C + $1_type The actual C datatype matched by the typemap.
      $1_ltype The assignable + $1_ltype The assignable version of the C datatype matched by the typemap.
      - - - - -
      - - - -

      This is probably the most commonly redefined typemap because it can be used to implement customized conversions.

      - - - -

      In addition, the "in" typemap allows the number of converted arguments to be specified. For example:

      - - - -
      -
      // Ignored argument.
      %typemap(in, numinputs=0) int *out (int temp) {
      $1 = &temp;
      }
      - - - - - +
      // Ignored argument.
      +%typemap(in, numinputs=0) int *out (int temp) {
      +  $1 = &temp;
      +}
      - - - -

      At this time, only zero or one arguments may be converted.

      - - - - -

      36.7.6.2 "typecheck" typemap

      +

      37.7.6.2 "typecheck" typemap

      The "typecheck" typemap is used to support overloaded functions and methods. It merely checks an argument to see whether or not it matches a specific type. For example:

      - - - -
      -
      %typemap(typecheck,precedence=SWIG_TYPECHECK_INTEGER) int {
      $1 = FIXNUM_P($input) ? 1 : 0;
      }
      - - - - - +
      %typemap(typecheck,precedence=SWIG_TYPECHECK_INTEGER) int {
      +  $1 = FIXNUM_P($input) ? 1 : 0;
      +}
      - - - -

      For typechecking, the $1 variable is always a simple integer that is set to 1 or 0 depending on whether or not the input argument is the correct type.

      - - - -

      If you define new "in" typemaps and your program uses overloaded methods, you should also define a collection of "typecheck" typemaps. More details about this follow in a later section on "Typemaps and Overloading."

      - - - - -

      36.7.6.3  "out" typemap

      +

      37.7.6.3 "out" typemap

      Converts return value of a C function to a Ruby object.

      - - - - -

      - - - - - -%typemap(out) int {
      - - - - - -   $result = INT2NUM( $1 );
      - - - - - -}
      - - - - - -
      - - - - +
      +
      %typemap(out) int {
      +  $result = INT2NUM( $1 );
      +}
      +

      The following special variables are available.

      - - - -
      - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - -
      $result Result object + $result Result object returned to target language.
      $symname Name of + $symname Name of function/method being wrapped
      $1...n Argument being + $1...n Argument being wrapped
      $1_name Name of the + $1_name Name of the argument (if provided)
      $1_type The actual C + $1_type The actual C datatype matched by the typemap.
      $1_ltype The assignable + $1_ltype The assignable version of the C datatype matched by the typemap.
      - - - - -
      - - - - -
      - - - - - -

      36.7.6.4 "arginit" typemap

      +

      37.7.6.4 "arginit" typemap

      The "arginit" typemap is used to set the initial value of a @@ -5778,90 +2795,54 @@ function argument--before any conversion has occurred. This is not normally necessary, but might be useful in highly specialized applications. For example:

      - - - -
      -
      // Set argument to NULL before any conversion occurs
      %typemap(arginit) int *data {
      $1 = NULL;
      }
      - - - - - +
      // Set argument to NULL before any conversion occurs
      +%typemap(arginit) int *data {
      +  $1 = NULL;
      +}
      - - - - -

      36.7.6.5 "default" typemap

      +

      37.7.6.5 "default" typemap

      The "default" typemap is used to turn an argument into a default argument. For example:

      - - - -
      -
      %typemap(default) int flags {
      $1 = DEFAULT_FLAGS;
      }
      ...
      int foo(int x, int y, int flags);
      - - - - - +
      %typemap(default) int flags {
      +  $1 = DEFAULT_FLAGS;
      +}
      +...
      +int foo(int x, int y, int flags);
      - - - -

      The primary use of this typemap is to either change the wrapping of default arguments or specify a default argument in a language where they aren't supported (like C). Target languages that do not support optional arguments, such as Java and C#, effectively ignore the value specified by this typemap as all arguments must be given.

      - - - -

      Once a default typemap has been applied to an argument, all arguments that follow must have default values. See the Default/optional arguments section for further information on default argument wrapping.

      - - - - -

      36.7.6.6 "check" typemap

      +

      37.7.6.6 "check" typemap

      The "check" typemap is used to supply value checking code during argument conversion. The typemap is applied after arguments have been converted. For example:

      - - - -
      -
      %typemap(check) int positive {
      if ($1 <= 0) {
      SWIG_exception(SWIG_ValueError,"Expected positive value.");
      }
      }
      - - - - - +
      %typemap(check) int positive {
      +  if ($1 <= 0) {
      +    SWIG_exception(SWIG_ValueError,"Expected positive value.");
      +  }
      +}
      - - - - -

      36.7.6.7 "argout" typemap

      +

      37.7.6.7 "argout" typemap

      The "argout" typemap is used to return values from arguments. @@ -5870,156 +2851,52 @@ need to return multiple values. The "argout" typemap is almost always combined with an "in" typemap---possibly to ignore the input value. For example:

      - - - -
      -
      /* Set the input argument to point to a temporary variable */
      %typemap(in, numinputs=0) int *out (int temp) {
      $1 = &temp;
      }

      %typemap(argout, fragment="output_helper") int *out {
      // Append output value $1 to $result (assuming a single integer in this case)
      $result = output_helper( $result, INT2NUM(*$1) );
      }
      - - - - +
      /* Set the input argument to point to a temporary variable */
      +%typemap(in, numinputs=0) int *out (int temp) {
      +  $1 = &temp;
      +}
       
      +%typemap(argout, fragment="output_helper") int *out {
      +  // Append output value $1 to $result (assuming a single integer in this case)
      +  $result = output_helper( $result, INT2NUM(*$1) );
      +}
      - - - -

      The following special variables are available.

      - - - -
      - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - -
      $result Result object + $result Result object returned to target language.
      $input The original + $input The original input object passed.
      $symname Name of + $symname Name of function/method being wrapped.
      - - - - -
      - - - -

      The code supplied to the "argout" typemap is always placed after the "out" typemap. If multiple return values are used, the extra return values are often appended to return value of the function.

      - - - -

      Output helper is a fragment that usually defines a macro to some function like SWIG_Ruby_AppendOutput.

      - - - -

      See the typemaps.i library for examples.

      - - - - -

      36.7.6.8 "freearg" typemap

      +

      37.7.6.8 "freearg" typemap

      The "freearg" typemap is used to cleanup argument data. It is @@ -6028,65 +2905,49 @@ be cleaned up when the wrapper function exits. The "freearg" typemap usually cleans up argument resources allocated by the "in" typemap. For example:

      - - - -
      -
      // Get a list of integers
      %typemap(in) int *items {
      int nitems = Length($input);
      $1 = (int *) malloc(sizeof(int)*nitems);
      }
      // Free the list
      %typemap(freearg) int *items {
      free($1);
      }
      - - - - - +
      // Get a list of integers
      +%typemap(in) int *items {
      +  int nitems = Length($input); 
      +  $1 = (int *) malloc(sizeof(int)*nitems);
      +}
      +// Free the list 
      +%typemap(freearg) int *items {
      +  free($1);
      +}
      - - - -

      The "freearg" typemap inserted at the end of the wrapper function, just before control is returned back to the target language. This code is also placed into a special variable $cleanup that may be used in other typemaps whenever a wrapper function needs to abort prematurely.

      - - - - -

      36.7.6.9 "newfree" typemap

      +

      37.7.6.9 "newfree" typemap

      The "newfree" typemap is used in conjunction with the %newobject directive and is used to deallocate memory used by the return result of a function. For example:

      - - - -
      -
      %typemap(newfree) string * {
      delete $1;
      }
      %typemap(out) string * {
      $result = PyString_FromString($1->c_str());
      }
      ...

      %newobject foo;
      ...
      string *foo();
      - - - - +
      %typemap(newfree) string * {
      +  delete $1;
      +}
      +%typemap(out) string * {
      +  $result = PyString_FromString($1->c_str());
      +}
      +...
       
      +%newobject foo;
      +...
      +string *foo();
      - - - -

      See Object ownership and %newobject for further details.

      - - - - -

      36.7.6.10 "memberin" typemap

      +

      37.7.6.10 "memberin" typemap

      The "memberin" typemap is used to copy data from an @@ -6094,54 +2955,31 @@ already converted input value into a structure member. It is typically used to handle array members and other special cases. For example:

      - - - -
      -
      %typemap(memberin) int [4] {
      memmove($1, $input, 4*sizeof(int));
      }
      - - - - - +
      %typemap(memberin) int [4] {
      +  memmove($1, $input, 4*sizeof(int));
      +}
      - - - -

      It is rarely necessary to write "memberin" typemaps---SWIG already provides a default implementation for arrays, strings, and other objects.

      - - - - -

      36.7.6.11 "varin" typemap

      +

      37.7.6.11 "varin" typemap

      The "varin" typemap is used to convert objects in the target language to C for the purposes of assigning to a C/C++ global variable. This is implementation specific.

      - - - - -

      36.7.6.12 "varout" typemap

      +

      37.7.6.12 "varout" typemap

      The "varout" typemap is used to convert a C/C++ object to an object in the target language when reading a C/C++ global variable. This is implementation specific.

      - - - - -

      36.7.6.13 "throws" typemap

      +

      37.7.6.13 "throws" typemap

      The "throws" typemap is only used when SWIG parses a C++ @@ -6153,736 +2991,238 @@ or exception in the target language. It is slightly different to the other typemaps as it is based around the exception type rather than the type of a parameter or variable. For example:

      - - - -
      -
      %typemap(throws) const char * %{
      rb_raise(rb_eRuntimeError, $1);
      SWIG_fail;
      %}
      void bar() throw (const char *);
      - - - - - +
      %typemap(throws) const char * %{
      +  rb_raise(rb_eRuntimeError, $1);
      +  SWIG_fail;
      +%}
      +void bar() throw (const char *);
      - - - -

      As can be seen from the generated code below, SWIG generates an exception handler with the catch block comprising the "throws" typemap content.

      - - - -
      -
      ...
      try {
      bar();
      }
      catch(char const *_e) {
      rb_raise(rb_eRuntimeError, _e);
      SWIG_fail;
      }
      ...
      - - - - - +
      ...
      +try {
      +  bar();
      +}
      +catch(char const *_e) {
      +  rb_raise(rb_eRuntimeError, _e);
      +  SWIG_fail;
      +}
      +...
      - - - -

      Note that if your methods do not have an exception specification yet they do throw exceptions, SWIG cannot know how to deal with them. For a neat way to handle these, see the Exception handling with %exception section.

      - - - - -

      36.7.6.14 directorin typemap

      +

      37.7.6.14 directorin typemap

      Converts C++ objects in director -member functions to ruby objects. It is roughly the opposite +member functions to ruby objects. It is roughly the opposite of the "in" typemap, making its typemap rule often similar to the "out" typemap.

      - - - - -

      - - - - - -%typemap(directorin) int {
      - - - - - -     $result = INT2NUM($1);
      - - - - - -}
      - - - - - -
      - - - - +
      +%typemap(directorin) int {
      +  $result = INT2NUM($1);
      +}
      +

      The following special variables are available.

      - - - -
      - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - -
      $result Result object + $result Result object returned to target language.
      $symname Name of + $symname Name of function/method being wrapped
      $1...n Argument being + $1...n Argument being wrapped
      $1_name Name of the + $1_name Name of the argument (if provided)
      $1_type The actual C + $1_type The actual C datatype matched by the typemap.
      $1_ltype The assignable + $1_ltype The assignable version of the C datatype matched by the typemap.
      this C++ this, + this C++ this, referring to the class itself.
      - - - - -
      - - - - -

      36.7.6.15 directorout typemap

      +

      37.7.6.15 directorout typemap

      Converts Ruby objects in director -member functions to C++ objects.  It is roughly the opposite +member functions to C++ objects. It is roughly the opposite of the "out" typemap, making its rule often similar to the "in" typemap.

      - - - - -

      - - - - - -%typemap(directorout) int {

      - - - - - -   $result = NUM2INT($1);

      - - - - - -}
      - - - - - -
      - - - - +
      +%typemap(directorout) int {
      +  $result = NUM2INT($1);
      +}
      +
      +

      The following special variables are available:

      - - - -
      - - - - - - - - - - - - + + - - + + - - + + - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - -
      $inputRuby object being sent to the function$inputRuby object being sent to the function
      $symname Name of function/method being wrapped$symname Name of function/method being wrapped
      $1...n Argument being sent to the function$1...n Argument being sent to the function
      $1_name Name of the + $1_name Name of the argument (if provided)
      $1_type The actual C + $1_type The actual C datatype matched by the typemap.
      $1_ltype The assignable + $1_ltype The assignable version of the C datatype matched by the typemap.
      this C++ this, + this C++ this, referring to the class itself.
      - - - - -
      - - - -

      Currently, the directorout nor the out typemap support the -option numoutputs, +option numoutputs, but the Ruby module provides that functionality through a %feature -directive.  Thus, a function can be made to return "nothing" +directive. Thus, a function can be made to return "nothing" if you do:

      - - - - -
      %feature("numoutputs","0") -MyClass::function;
      - - - - +
      +%feature("numoutputs","0") MyClass::function;
      +

      This feature can be useful if a function returns a status code, which you want to discard but still use the typemap to raise an -exception.
      - - - - +exception.

      - - - - -

      36.7.6.16 directorargout typemap

      +

      37.7.6.16 directorargout typemap

      Output argument processing in director member functions.

      - - - - -
      %typemap(directorargout, -fragment="output_helper") int {
      - - - - - -$result = output_helper( $result, NUM2INT($1) );

      - - - - - -}
      - - - - +
      +%typemap(directorargout,
      +fragment="output_helper") int {
      +  $result = output_helper( $result, NUM2INT($1) );
      +}
      +

      The following special variables are available:

      - - - -
      - - - - - - - - - - - - + + - - + + - - + + - - + + - - - - - - - - - - - - + - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - -
      $resultResult that the director function returns$resultResult that the director function returns
      $inputRuby object being sent to the function$inputRuby object being sent to the function
      $symnamename of the function/method being wrapped$symnamename of the function/method being wrapped
      $1...nArgument being sent to the function$1...nArgument being sent to the function
      $1_nameName of the + $1_nameName of the argument (if provided)
      $1_typeThe actual C + $1_typeThe actual C datatype matched by the typemap
      $1_ltypeThe assignable + $1_ltypeThe assignable version of the C datatype matched by the typemap
      thisC++ this, + thisC++ this, referring to the instance of the class itself
      - - - - -
      - - - - -

      36.7.6.17 ret typemap

      +

      37.7.6.17 ret typemap

      Cleanup of function return values

      - - - - -

      36.7.6.18 globalin typemap

      +

      37.7.6.18 globalin typemap

      Setting of C global variables

      - - - - -

      36.7.7 Typemap variables

      +

      37.7.7 Typemap variables

      @@ -6891,83 +3231,35 @@ may appear. A full list of variables can be found in the "A C local variable corresponding to the actual type specified in the %typemap directive. For input values, this is a C local variable that is supposed to hold an argument value. For output values, this is the raw result that is supposed to be returned to Ruby. - - - -

      $input

      - - - -
      A VALUE holding a raw Ruby object with an argument or variable value.
      - - - -

      $result

      - - - -
      A VALUE that holds the result to be returned to Ruby.
      - - - -

      $1_name

      - - - -
      The parameter name that was matched.
      - - - -

      $1_type

      - - - -
      The actual C datatype matched by the typemap.
      - - - -

      $1_ltype

      - - - -
      An assignable version of the datatype matched by the typemap (a type that can appear on the left-hand-side of a C assignment operation). This type is stripped of qualifiers and may @@ -6975,48 +3267,27 @@ be an altered version of $1_type. All arguments and local variables in wrapper functions are declared using this type so that their values can be properly assigned.
      - - - -

      $symname

      - - - -
      The Ruby name of the wrapper function being created.
      - - - - -

      36.7.8 Useful Functions

      +

      37.7.8 Useful Functions

      When you write a typemap, you usually have to work directly with Ruby objects. The following functions may prove to be useful. (These functions plus many more can be found in Programming -Ruby book, by David Thomas and Andrew Hunt.) 

      +Ruby book, by David Thomas and Andrew Hunt.)

      In addition, we list equivalent functions that SWIG defines, which provide a language neutral conversion (these functions are defined for -each swig language supported).  If you are trying to create a swig +each swig language supported). If you are trying to create a swig file that will work under multiple languages, it is recommended you stick to the swig functions instead of the native Ruby functions. - That should help you avoid having to rewrite a lot of typemaps +That should help you avoid having to rewrite a lot of typemaps across multiple languages.

      - - - - - - - - - -

      36.7.8.1 C Datatypes to Ruby Objects

      +

      37.7.8.1 C Datatypes to Ruby Objects

      @@ -7024,487 +3295,264 @@ across multiple languages.

      - RUBY - SWIG + RUBY + SWIG - INT2NUM(long or int) - SWIG_From_int(int x) + INT2NUM(long or int) + SWIG_From_int(int x) int to Fixnum or Bignum - - INT2FIX(long or int) - + INT2FIX(long or int) + int to Fixnum (faster than INT2NUM) - - CHR2FIX(char) - SWIG_From_char(char x) + CHR2FIX(char) + SWIG_From_char(char x) char to Fixnum - - rb_str_new2(char*) - SWIG_FromCharPtrAndSize(char*, size_t) + rb_str_new2(char*) + SWIG_FromCharPtrAndSize(char*, size_t) char* to String - - rb_float_new(double) - SWIG_From_double(double),
      + rb_float_new(double) + SWIG_From_double(double),
      SWIG_From_float(float) float/double to Float - - - - - -
      - - - - -

      36.7.8.2 Ruby Objects to C Datatypes

      +

      37.7.8.2 Ruby Objects to C Datatypes

      Here, while the Ruby versions return the value directly, the SWIG -versions do not, but return a status value to indicate success (SWIG_OK). While more akward to use, this allows you to write typemaps that report more helpful error messages, like:

      -

      -%typemap(in) size_t (int ok)

      -  ok = SWIG_AsVal_size_t($input, &$1);
      -  if (!SWIG_IsOK(ok)) {
      -    SWIG_exception_fail(SWIG_ArgError(ok), -Ruby_Format_TypeError( "$1_name", "$1_type","$symname", $argnum, $input -));
      -   }
      -
      -}
      -
        
      -
      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
      int NUM2INT(Numeric)SWIG_AsVal_int(VALUE, int*)
      int FIX2INT(Numeric)SWIG_AsVal_int(VALUE, int*)
      unsigned int NUM2UINT(Numeric)SWIG_AsVal_unsigned_SS_int(VALUE, int*)
      unsigned int FIX2UINT(Numeric)SWIG_AsVal_unsigned_SS_int(VALUE, int*)
      long NUM2LONG(Numeric)SWIG_AsVal_long(VALUE, long*)
      long FIX2LONG(Numeric)SWIG_AsVal_long(VALUE, long*)
      unsigned long FIX2ULONG(Numeric)SWIG_AsVal_unsigned_SS_long(VALUE, unsigned long*)
      char NUM2CHR(Numeric or String)SWIG_AsVal_char(VALUE, int*)
      char * STR2CSTR(String)SWIG_AsCharPtrAndSize(VALUE, char*, size_t, int* alloc)
      char * rb_str2cstr(String, int*length)
      double NUM2DBL(Numeric)(double) SWIG_AsVal_int(VALUE) or similar
      - - - - +versions do not, but return a status value to indicate success (SWIG_OK). While more akward to use, this allows you to write typemaps that report more helpful error messages, like:

      +
      +
      +%typemap(in) size_t (int ok)
      +  ok = SWIG_AsVal_size_t($input, &$1);
      +  if (!SWIG_IsOK(ok)) {
      +    SWIG_exception_fail(SWIG_ArgError(ok), Ruby_Format_TypeError( "$1_name", "$1_type","$symname", $argnum, $input));
      +  }
      +}
      +
      +
      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      int NUM2INT(Numeric)SWIG_AsVal_int(VALUE, int*)
      int FIX2INT(Numeric)SWIG_AsVal_int(VALUE, int*)
      unsigned int NUM2UINT(Numeric)SWIG_AsVal_unsigned_SS_int(VALUE, int*)
      unsigned int FIX2UINT(Numeric)SWIG_AsVal_unsigned_SS_int(VALUE, int*)
      long NUM2LONG(Numeric)SWIG_AsVal_long(VALUE, long*)
      long FIX2LONG(Numeric)SWIG_AsVal_long(VALUE, long*)
      unsigned long FIX2ULONG(Numeric)SWIG_AsVal_unsigned_SS_long(VALUE, unsigned long*)
      char NUM2CHR(Numeric or String)SWIG_AsVal_char(VALUE, int*)
      char * StringValuePtr(String)SWIG_AsCharPtrAndSize(VALUE, char*, size_t, int* alloc)
      char * rb_str2cstr(String, int*length)
      double NUM2DBL(Numeric)(double) SWIG_AsVal_int(VALUE) or similar
      +
      - - - -

      36.7.8.3 Macros for VALUE

      +

      37.7.8.3 Macros for VALUE

      RSTRING_LEN(str)

      - - - -
      length of the Ruby string
      - - - -

      RSTRING_PTR(str)

      - - - -
      pointer to string storage
      - - - -

      RARRAY_LEN(arr)

      - - - -
      length of the Ruby array
      - - - -

      RARRAY(arr)->capa

      - - - -
      capacity of the Ruby array
      - - - -

      RARRAY_PTR(arr)

      - - - -
      pointer to array storage
      - - - - -

      36.7.8.4 Exceptions

      +

      37.7.8.4 Exceptions

      void rb_raise(VALUE exception, const char *fmt, ...)

      - - - -
      Raises an exception. The given format string fmt and remaining arguments are interpreted as with printf().
      - - - -

      void rb_fatal(const char *fmt, ...)

      - - - -
      Raises a fatal exception, terminating the process. No rescue blocks are called, but ensure blocks will be called. The given format string fmt and remaining arguments are interpreted as with printf().
      - - - -

      void rb_bug(const char *fmt, ...)

      - - - -
      Terminates the process immediately -- no handlers of any sort will be called. The given format string fmt and remaining arguments are interpreted as with printf(). You should call this function only if a fatal bug has been exposed.
      - - - -

      void rb_sys_fail(const char *msg)

      - - - -
      Raises a platform-specific exception corresponding to the last known system error, with the given string msg.
      - - - -

      VALUE rb_rescue(VALUE (*body)(VALUE), VALUE args, VALUE(*rescue)(VALUE, VALUE), VALUE rargs)

      - - - -
      Executes body with the given args. If a StandardError exception is raised, then execute rescue with the given rargs.
      - - - -

      VALUE rb_ensure(VALUE(*body)(VALUE), VALUE args, VALUE(*ensure)(VALUE), VALUE eargs)

      - - - -
      Executes body with the given args. Whether or not an exception is raised, execute ensure with the given rargs after body has completed.
      - - - -

      VALUE rb_protect(VALUE (*body)(VALUE), VALUE args, int *result)

      - - - -
      Executes body with the given args and returns nonzero in result if any exception was raised.
      - - - -

      void rb_notimplement()

      - - - -
      Raises a NotImpError exception to indicate that the enclosed function is not implemented yet, or not available on this platform.
      - - - -

      void rb_exit(int status)

      - - - -
      Exits Ruby with the given status. Raises a SystemExit exception and calls registered exit functions and finalizers.
      - - - -

      void rb_warn(const char *fmt, ...)

      - - - -
      Unconditionally issues a warning message to standard error. The given format string fmt and remaining arguments are interpreted as with printf().
      - - - -

      void rb_warning(const char *fmt, ...)

      - - - -
      Conditionally issues a warning message to standard error if Ruby was invoked with the -w flag. The given format string fmt and remaining arguments are interpreted as with printf().
      - - - - -

      36.7.8.5 Iterators

      +

      37.7.8.5 Iterators

      void rb_iter_break()

      - - - -
      Breaks out of the enclosing iterator block.
      - - - -

      VALUE rb_each(VALUE obj)

      - - - -
      Invokes the each method of the given obj.
      - - - -

      VALUE rb_yield(VALUE arg)

      - - - -
      Transfers execution to the iterator block in the current context, passing arg as an argument. Multiple values may be passed in an array.
      - - - -

      int rb_block_given_p()

      - - - -
      Returns true if yield would execute a block in the current context; that is, if a code block was passed to the current method and is available to be called.
      - - - -

      VALUE rb_iterate(VALUE (*method)(VALUE), VALUE args, VALUE (*block)(VALUE, VALUE), VALUE arg2)

      - - - -
      Invokes method with argument args and block block. A yield from that method will invoke block with the argument given to yield, and a second argument arg2.
      - - - -

      VALUE rb_catch(const char *tag, VALUE (*proc)(VALUE, VALUE), VALUE value)

      - - - -
      Equivalent to Ruby's catch.
      - - - -

      void rb_throw(const char *tag, VALUE value)

      - - - -
      Equivalent to Ruby's throw.
      - - - - -

      36.7.9 Typemap Examples

      +

      37.7.9 Typemap Examples

      This section includes a few examples of typemaps. For more examples, you might look at the examples in the Example/ruby directory.

      - - - - -

      36.7.10 Converting a Ruby array to a char **

      +

      37.7.10 Converting a Ruby array to a char **

      A common problem in many C programs is the processing of @@ -7512,54 +3560,64 @@ command line arguments, which are usually passed in an array of NULL terminated strings. The following SWIG interface file allows a Ruby 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;
      +}
      +%}
      - - - -

      When this module is compiled, the wrapped C function now operates as follows :

      - - - -
      -
      require 'Argv'
      Argv.print_args(["Dave","Mike","Mary","Jane","John"])
      argv[0] = Dave
      argv[1] = Mike
      argv[2] = Mary
      argv[3] = Jane
      argv[4] = John
      - - - - - +
      require 'Argv'
      +Argv.print_args(["Dave","Mike","Mary","Jane","John"])
      +argv[0] = Dave
      +argv[1] = Mike
      +argv[2] = Mary
      +argv[3] = Jane
      +argv[4] = John
      - - - -

      In the example, two different typemaps are used. The "in" typemap is used to receive an input argument and convert it to a C array. Since dynamic memory allocation is used to allocate memory for the array, the "freearg" typemap is used to later release this memory after the execution of the C function.

      - - - - -

      36.7.11 Collecting arguments in a hash

      +

      37.7.11 Collecting arguments in a hash

      Ruby's solution to the "keyword arguments" capability of some @@ -7571,66 +3629,33 @@ provide similar functionality for your Ruby interface. For example, suppose you'd like to wrap this C function that collects information about people's vital statistics:

      - - - -
      -
      void setVitalStats(const char *person, int nattributes, const char **names, int *values);
      - - - - - +
      void setVitalStats(const char *person, int nattributes, const char **names, int *values);
      - - - -

      and you'd like to be able to call it from Ruby by passing in an arbitrary number of key-value pairs as inputs, e.g.

      - - - -
      -
      setVitalStats("Fred",
      'weight' => 270,
      'age' => 42
      )
      - - - - - +
      setVitalStats("Fred", 
      +  'weight' => 270, 
      +  'age' => 42 
      +)
      - - - -

      To make this work, you need to write a typemap that expects a Ruby Hash as its input and somehow extracts the last three arguments (nattributes, names and values) needed by your C function. Let's start with the basics:

      - - - -
      -
      %typemap(in) (int nattributes, const char **names, const int *values)
      (VALUE keys_arr, int i, VALUE key, VALUE val) {
      }
      - - - - - +
      %typemap(in) (int nattributes, const char **names, const int *values)
      +  (VALUE keys_arr, int i, VALUE key, VALUE val) {
      +}
      + 
      - - - -

      This %typemap directive tells SWIG that we want to match any function declaration that has the specified types and names of arguments somewhere in the argument list. The fact that we @@ -7643,38 +3668,20 @@ of parentheses (keys_arr, i, key and val) define local variables that our typemap will need.

      - - - -

      Since we expect the input argument to be a Hash, let's next add a check for that:

      - - - -
      -
      %typemap(in) (int nattributes, const char **names, const int *values)
      (VALUE keys_arr, int i, VALUE key, VALUE val) {
      Check_Type($input, T_HASH);
      }
      - - - - - +
      %typemap(in) (int nattributes, const char **names, const int *values)
      +  (VALUE keys_arr, int i, VALUE key, VALUE val) {
      +    Check_Type($input, T_HASH);
      +}
      - - - -

      Check_Type() is just a macro (defined in the Ruby header files) that confirms that the input argument is of the correct type; if it isn't, an exception will be raised.

      - - - -

      The next task is to determine how many key-value pairs are present in the hash; we'll assign this number to the first typemap argument ($1). This is a little tricky since the @@ -7683,162 +3690,148 @@ hash, but we can get around that by calling the hash's size method directly and converting its result to a C int value:

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

      So now we know the number of attributes. Next we need to initialize the second and third typemap arguments (i.e. the two C arrays) to NULL and set the stage for extracting the keys and values from the hash:

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

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

      There are a number of ways we could extract the keys and values from the input hash, but the simplest approach is to first call the hash's keys method (which returns a Ruby array of the keys) and then start looping over the elements in that array:

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

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

      Recall that keys_arr and i are local variables for this typemap. For each element in the keys_arr array, we want to get the key itself, as well as the value corresponding to that key in the hash:

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

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

      To be safe, we should again use the Check_Type() macro to confirm that the key is a String and the value is a Fixnum:

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

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

      Finally, we can convert these Ruby objects into their C 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);
      +    }
      +  }
      +}
      - - - -

      We're not done yet. Since we used malloc() to dynamically allocate the memory used for the names and values arguments, we need to provide a corresponding "freearg" typemap to free that memory so that there is no memory leak. Fortunately, this typemap is a lot easier to write:

      - - - -
      -
      %typemap(freearg) (int nattributes, const char **names, const int *values) {
      free((void *) $2);
      free((void *) $3);
      }
      - - - - - +
      %typemap(freearg) (int nattributes, const char **names, const int *values) {
      +  free((void *) $2);
      +  free((void *) $3);
      +}
      - - - -

      All of the code for this example, as well as a sample Ruby program that uses the extension, can be found in the Examples/ruby/hashargs directory of the SWIG distribution.

      - - - - -

      36.7.12 Pointer handling

      +

      37.7.12 Pointer handling

      Occasionally, it might be necessary to convert pointer values @@ -7846,17 +3839,9 @@ that have been stored using the SWIG typed-pointer representation. Since there are several ways in which pointers can be represented, the following two functions are used to safely perform this conversion:

      - - - -

      int SWIG_ConvertPtr(VALUE obj, void **ptr, swig_type_info *ty, int flags)

      - - - -
      Converts a Ruby object obj to a C pointer whose address is ptr (i.e. ptr is a pointer to a pointer). The third argument, ty, @@ -7870,17 +3855,9 @@ errors will cause SWIG_ConvertPtr() to return -1 but not raise an exception. If ty is NULL, no type-checking is performed.
      - - - -

      VALUE SWIG_NewPointerObj(void *ptr, swig_type_info *ty, int own)

      - - - -
      Creates a new Ruby pointer object. Here, ptr is the pointer to convert, ty is the SWIG type descriptor structure that describes the type, and own @@ -7888,10 +3865,6 @@ is a flag that indicates whether or not Ruby should take ownership of the pointer (i.e. whether Ruby should free this data when the corresponding Ruby instance is garbage-collected).
      - - - -

      Both of these functions require the use of a special SWIG type-descriptor structure. This structure contains information about the mangled name of the datatype, type-equivalence information, as well @@ -7899,96 +3872,52 @@ as information about converting pointer values under C++ inheritance. For a type of Foo *, the type descriptor structure is usually accessed as follows:

      - - - -
      -
      Foo *foo;
      SWIG_ConvertPtr($input, (void **) &foo, SWIGTYPE_p_Foo, 1);

      VALUE obj;
      obj = SWIG_NewPointerObj(f, SWIGTYPE_p_Foo, 0);
      - - - - +
      Foo *foo;
      +SWIG_ConvertPtr($input, (void **) &foo, SWIGTYPE_p_Foo, 1);
       
      +VALUE obj;
      +obj = SWIG_NewPointerObj(f, SWIGTYPE_p_Foo, 0);
      - - - -

      In a typemap, the type descriptor should always be accessed using the special typemap variable $1_descriptor. For example:

      - - - -
      -
      %typemap(in) Foo * {
      SWIG_ConvertPtr($input, (void **) &$1, $1_descriptor, 1);
      }
      - - - - - +
      %typemap(in) Foo * {
      +  SWIG_ConvertPtr($input, (void **) &$1, $1_descriptor, 1);
      +}
      - - - - -

      36.7.12.1 Ruby Datatype Wrapping

      +

      37.7.12.1 Ruby Datatype Wrapping

      VALUE Data_Wrap_Struct(VALUE class, void (*mark)(void *), void (*free)(void *), void *ptr)

      - - - -
      Given a pointer ptr to some C data, and the two garbage collection routines for this data (mark and free), return a VALUE for the Ruby object.
      - - - -

      VALUE Data_Make_Struct(VALUE class, c-type, void (*mark)(void *), void (*free)(void *), c-type *ptr)

      - - - -
      Allocates a new instance of a C data type c-type, assigns it to the pointer ptr, then wraps that pointer with Data_Wrap_Struct() as above.
      - - - -

      Data_Get_Struct(VALUE obj, c-type, c-type *ptr)

      - - - -
      Retrieves the original C pointer of type c-type from the data object obj and assigns that pointer to ptr.
      - - - - -

      36.7.13 Example: STL Vector to Ruby Array

      +

      37.7.13 Example: STL Vector to Ruby Array

      Another use for macros and type maps is to create a Ruby array @@ -7999,105 +3928,88 @@ The following is an example of how to construct this type of macro/typemap and should give insight into constructing similar typemaps for other STL structures:

      - - - -
      -
      %define PTR_VECTOR_TO_RUBY_ARRAY(vectorclassname, classname)
      %typemap(out) vectorclassname &, const vectorclassname & {
      VALUE arr = rb_ary_new2($1->size());
      vectorclassname::iterator i = $1->begin(), iend = $1->end();
      for ( ; i!=iend; i++ )
      rb_ary_push(arr, Data_Wrap_Struct(c ## classname.klass, 0, 0, *i));
      $result = arr;
      }
      %typemap(out) vectorclassname, const vectorclassname {
      VALUE arr = rb_ary_new2($1.size());
      vectorclassname::iterator i = $1.begin(), iend = $1.end();
      for ( ; i!=iend; i++ )
      rb_ary_push(arr, Data_Wrap_Struct(c ## classname.klass, 0, 0, *i));
      $result = arr;
      }
      %enddef
      - - - - - +
      %define PTR_VECTOR_TO_RUBY_ARRAY(vectorclassname, classname)
      +%typemap(out) vectorclassname &, const vectorclassname & {
      +  VALUE arr = rb_ary_new2($1->size());
      +  vectorclassname::iterator i = $1->begin(), iend = $1->end();
      +  for ( ; i!=iend; i++ )
      +    rb_ary_push(arr, Data_Wrap_Struct(c ## classname.klass, 0, 0, *i));
      +  $result = arr;
      +}
      +%typemap(out) vectorclassname, const vectorclassname {
      +  VALUE arr = rb_ary_new2($1.size());
      +  vectorclassname::iterator i = $1.begin(), iend = $1.end();
      +  for ( ; i!=iend; i++ )
      +    rb_ary_push(arr, Data_Wrap_Struct(c ## classname.klass, 0, 0, *i));
      +  $result = arr;
      +}
      +%enddef
      - - - -

      Note, that the "c ## classname.klass" is used in the preprocessor step to determine the actual object from the class name.

      - - - -

      To use the macro with a class Foo, the following is used:

      - - - -
      -
      PTR_VECTOR_TO_RUBY_ARRAY(vector<foo *="">, Foo)
      - - - - - +
      PTR_VECTOR_TO_RUBY_ARRAY(vector<foo *="">, Foo)
      - - - -

      It is also possible to create a STL vector of Ruby objects:

      - - - -
      -
      %define RUBY_ARRAY_TO_PTR_VECTOR(vectorclassname, classname)
      %typemap(in) vectorclassname &, const vectorclassname & {
      Check_Type($input, T_ARRAY);
      vectorclassname *vec = new vectorclassname;
      int len = RARRAY($input)->len;
      for (int i=0; i!=len; i++) {
      VALUE inst = rb_ary_entry($input, i);
      //The following _should_ work but doesn't on HPUX
      // Check_Type(inst, T_DATA);
      classname *element = NULL;
      Data_Get_Struct(inst, classname, element);
      vec->push_back(element);
      }
      $1 = vec;
      }

      %typemap(freearg) vectorclassname &, const vectorclassname & {
      delete $1;
      }
      %enddef
      - - - - +
      %define RUBY_ARRAY_TO_PTR_VECTOR(vectorclassname, classname)
      +%typemap(in) vectorclassname &, const vectorclassname & {
      +  Check_Type($input, T_ARRAY);
      +  vectorclassname *vec = new vectorclassname;
      +  int len = RARRAY($input)->len;
      +  for (int i=0; i!=len; i++) {
      +    VALUE inst = rb_ary_entry($input, i);
      +    //The following _should_ work but doesn't on HPUX
      +    // Check_Type(inst, T_DATA);
      +    classname *element = NULL;
      +    Data_Get_Struct(inst, classname, element);
      +    vec->push_back(element);
      +  }
      +  $1 = vec;
      +}
       
      +%typemap(freearg) vectorclassname &, const vectorclassname & {
      +  delete $1;
      +}
      +%enddef
      - - - -

      It is also possible to create a Ruby array from a vector of static data types:

      - - - -
      -
      %define VECTOR_TO_RUBY_ARRAY(vectorclassname, classname)
      %typemap(out) vectorclassname &, const vectorclassname & {
      VALUE arr = rb_ary_new2($1->size());
      vectorclassname::iterator i = $1->begin(), iend = $1->end();
      for ( ; i!=iend; i++ )
      rb_ary_push(arr, Data_Wrap_Struct(c ## classname.klass, 0, 0, &(*i)));
      $result = arr;
      }
      %typemap(out) vectorclassname, const vectorclassname {
      VALUE arr = rb_ary_new2($1.size());
      vectorclassname::iterator i = $1.begin(), iend = $1.end();
      for ( ; i!=iend; i++ )
      rb_ary_push(arr, Data_Wrap_Struct(c ## classname.klass, 0, 0, &(*i)));
      $result = arr;
      }
      %enddef
      - - - - - +
      %define VECTOR_TO_RUBY_ARRAY(vectorclassname, classname)
      +%typemap(out) vectorclassname &, const vectorclassname & {
      +  VALUE arr = rb_ary_new2($1->size()); 
      +  vectorclassname::iterator i = $1->begin(), iend = $1->end();
      +  for ( ; i!=iend; i++ )
      +    rb_ary_push(arr, Data_Wrap_Struct(c ## classname.klass, 0, 0, &(*i)));
      +  $result = arr;
      +}
      +%typemap(out) vectorclassname, const vectorclassname {
      +  VALUE arr = rb_ary_new2($1.size()); 
      +  vectorclassname::iterator i = $1.begin(), iend = $1.end();
      +  for ( ; i!=iend; i++ )
      +    rb_ary_push(arr, Data_Wrap_Struct(c ## classname.klass, 0, 0, &(*i)));
      +  $result = arr;
      +}
      +%enddef
      - - - - -
      - - - - - Note that this is mostly an example of typemaps. If you want to use the STL with ruby, you are advised to use the standard swig STL library, -which does much more than this.  Refer to the section called -the C++ Standard Template Library.
      +which does much more than this. Refer to the section called +the C++ Standard Template Library. - - - - -

      36.8 Docstring Features

      +

      37.8 Docstring Features

      @@ -8107,109 +4019,61 @@ will normally not get any documentation for it, even if they run 'rdoc' on the resulting .c or .cxx file.

      - - - -

      The features described in this section make it easy for you to add rdoc strings to your modules, functions and methods that can then be read by Ruby's rdoc tool to generate html web pages, ri documentation, Windows chm file and an .xml description.

      - - - -

      rdoc can then be run from a console or shell window on a swig -generated file. 

      - - - - +generated file.

      For example, to generate html web pages from a C++ file, you'd -do: 

      - - - - - -
      -$ -rdoc -E cxx=c -f html file_wrap.cxx
      - - - +do:

      +
      +
      +$ rdoc -E cxx=c -f html file_wrap.cxx
      +

      To generate ri documentation from a c wrap file, you could do:

      +
      +$ rdoc -r file_wrap.c
      +
      - - - -
      $ rdoc --r file_wrap.c -
      - - - - - -

      36.8.1 Module docstring

      +

      37.8.1 Module docstring

      -Ruby allows a docstring at the beginning of the file +Ruby allows a docstring at the beginning of the file before any other statements, and it is typically used to give a general description of the entire module. SWIG supports this by setting an option of the %module directive. For example:

      - - - -
      -
      %module(docstring="This is the example module's docstring") example
      - - - - - +
      %module(docstring="This is the example module's docstring") example
      - - - -

      When you have more than just a line or so then you can retain the easy readability of the %module directive by using a macro. For example:

      - - - -
      -
      %define DOCSTRING
      "The `XmlResource` class allows program resources defining menus,
      layout of controls on a panel, etc. to be loaded from an XML file."
      %enddef

      %module(docstring=DOCSTRING) xrc
      - - - - +
      %define DOCSTRING
      +"The `XmlResource` class allows program resources defining menus, 
      +layout of controls on a panel, etc. to be loaded from an XML file."
      +%enddef
       
      +%module(docstring=DOCSTRING) xrc
      - - - - -

      36.8.2 %feature("autodoc")

      +

      37.8.2 %feature("autodoc")

      Since SWIG does know everything about the function it wraps, @@ -8219,10 +4083,6 @@ and default values. Since Ruby ships with one of the best documentation systems of any language, it makes sense to take advantage of it.

      - - - -

      SWIG's Ruby module provides support for the "autodoc" feature, which when attached to a node in the parse tree will cause an rdoc @@ -8234,11 +4094,7 @@ several options for autodoc controlled by the value given to the feature, described below.

      - - - - -

      36.8.2.1 %feature("autodoc", "0")

      +

      37.8.2.1 %feature("autodoc", "0")

      @@ -8248,45 +4104,21 @@ example, given this function prototype:

      - - - -
      -
      %feature("autodoc", "0");
      bool function_name(int x, int y, Foo* foo=NULL, Bar* bar=NULL);
      - - - - - +
      %feature("autodoc", "0");
      +bool function_name(int x, int y, Foo* foo=NULL, Bar* bar=NULL);
      - - - -

      Then Ruby code like this will be generated:

      - - - -
      -
      function_name(x, y, foo=nil, bar=nil) -> bool
      ...
      - - - - - +
      function_name(x, y, foo=nil, bar=nil) -> bool
      +  ...
      - - - - -

      36.8.2.2 %feature("autodoc", "1")

      +

      37.8.2.2 %feature("autodoc", "1")

      @@ -8301,68 +4133,45 @@ parameter types with the "1" option will result in rdoc code like this:

      - - - -
      -
      function_name(int x, int y, Foo foo=nil, Bar bar=nil) -> bool
      ...
      - - - - - +
      function_name(int x, int y, Foo foo=nil, Bar bar=nil) -> bool
      +  ...
      - - - - -

      36.8.2.3 %feature("autodoc", "2")

      +

      37.8.2.3 %feature("autodoc", "2")

      When the "2" option is used then the parameter types will not be used in the rdoc string. However, they will be listed in full after the -function.  Given the example above, then turning on the +function. Given the example above, then turning on the parameter types with the "2" option will result in Ruby code like this:

      - - - - -

      36.8.2.4 %feature("autodoc", "3")

      +

      37.8.2.4 %feature("autodoc", "3")

      When the "3" option is used then the function will be documented using -a combination of "1" and "2" above.  Given the example above, +a combination of "1" and "2" above. Given the example above, then turning on the parameter types with the "2" option will result in Ruby code like this:

      - - - -
      -
      function_name(int x, int y, Foo foo=nil, Bar bar=nil) -> bool

      Parameters:
      x - int
      y - int
      foo - Foo
      bar - Bar
      - - - - +
      function_name(int x, int y, Foo foo=nil, Bar bar=nil) -> bool
       
      +Parameters:
      +	x - int
      +	y - int
      +	foo - Foo
      +	bar - Bar
      - - - - -

      36.8.2.5 %feature("autodoc", "docstring")

      +

      37.8.2.5 %feature("autodoc", "docstring")

      @@ -8373,24 +4182,12 @@ feature then that string will be used in place of the automatically generated string. For example:

      - - - -
      -
      %feature("autodoc", "GetPosition() -> (x, y)") GetPosition;
      void GetPosition(int* OUTPUT, int* OUTPUT);
      - - - - - +
      %feature("autodoc", "GetPosition() -> (x, y)") GetPosition;
      +void GetPosition(int* OUTPUT, int* OUTPUT);
      - - - - -

      36.8.3 %feature("docstring")

      +

      37.8.3 %feature("docstring")

      @@ -8401,1031 +4198,191 @@ docstring associated with classes, function or methods are output. If an item already has an autodoc string then it is combined with the docstring and they are output together.

      +

      37.9 Advanced Topics

      - - -

      36.9 Advanced Topics

      - - -

      36.9.1 Operator overloading

      +

      37.9.1 Operator overloading

      SWIG allows operator overloading with, by using the %extend or %rename commands in SWIG and the following operator names (derived from Python):

      - - - -
      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
      General
      __repr__ inspect
      __str__ to_s
      __cmp__ <=>
      __hash__ hash
      __nonzero__ nonzero?
      Callable
      __call__ call
      Collection
      __len__ length
      __getitem__ []
      __setitem__ []=
      Numeric
      __add__ +
      __sub__ -
      __mul__ *
      __div__ /
      __mod__ %
      __divmod__ divmod
      __pow__ **
      __lshift__ <<
      __rshift__ >>
      __and__ &
      __xor__ ^
      __or__ |
      __neg__ -@
      __pos__ +@
      __abs__ abs
      __invert__ ~
      __int__ to_i
      __float__ to_f
      __coerce__ coerce
      Additions in 1.3.13
      __lt__ <
      __le__ <=
      __eq__ ==
      __gt__ >
      __ge__ >=
      - - - - -
      - - - -

      Note that although SWIG supports the __eq__ magic method name for defining an equivalence operator, there is no separate method for handling inequality since Ruby parses the expression a != b as !(a == b).

      - - - - -

      36.9.2 Creating Multi-Module Packages

      +

      37.9.2 Creating Multi-Module Packages

      The chapter on Working @@ -9433,112 +4390,88 @@ with Modules discusses the basics of creating multi-module extensions with SWIG, and in particular the considerations for sharing runtime type information among the different modules.

      - - - -

      As an example, consider one module's interface file (shape.i) that defines our base class:

      - - - -
      -
      %module shape

      %{
      #include "Shape.h"
      %}

      class Shape {
      protected:
      double xpos;
      double ypos;
      protected:
      Shape(double x, double y);
      public:
      double getX() const;
      double getY() const;
      };
      - - - +
      %module shape
       
      +%{
      +#include "Shape.h"
      +%}
       
      +class Shape {
      +protected:
      +  double xpos;
      +  double ypos;
      +protected:
      +  Shape(double x, double y);
      +public:
      +  double getX() const;
      +  double getY() const;
      +};
      - - - -

      We also have a separate interface file (circle.i) that defines a derived class:

      - - - -
      -
      %module circle

      %{
      #include "Shape.h"
      #include "Circle.h"
      %}

      // Import the base class definition from Shape module
      %import shape.i

      class Circle : public Shape {
      protected:
      double radius;
      public:
      Circle(double x, double y, double r);
      double getRadius() const;
      };
      - - +
      %module circle
       
      +%{
      +#include "Shape.h"
      +#include "Circle.h"
      +%}
       
      +// Import the base class definition from Shape module
      +%import shape.i
       
      +class Circle : public Shape {
      +protected:
      +  double radius;
      +public:
      +  Circle(double x, double y, double r);
      +  double getRadius() const;
      +};
      - - - -

      We'll start by building the Shape extension module:

      - - - -
      -
      $ swig -c++ -ruby shape.i
      +
      $ swig -c++ -ruby shape.i
       
      - - - - -
      - - - -

      SWIG generates a wrapper file named shape_wrap.cxx. To compile this into a dynamically loadable extension for Ruby, prepare an extconf.rb script using this template:

      - - - -
      -
      require 'mkmf'

      # Since the SWIG runtime support library for Ruby
      # depends on the Ruby library, make sure it's in the list
      # of libraries.
      $libs = append_library($libs, Config::CONFIG['RUBY_INSTALL_NAME'])

      # Create the makefile
      create_makefile('shape')
      - - - +
      require 'mkmf'
       
      +# Since the SWIG runtime support library for Ruby
      +# depends on the Ruby library, make sure it's in the list
      +# of libraries.
      +$libs = append_library($libs, Config::CONFIG['RUBY_INSTALL_NAME'])
       
      +# Create the makefile
      +create_makefile('shape')
      - - - -

      Run this script to create a Makefile and then type make to build the shared library:

      - - - -
      -
      $ ruby extconf.rb
      creating Makefile
      $ make
      g++ -fPIC -g -O2 -I. -I/usr/local/lib/ruby/1.7/i686-linux \
      -I. -c shape_wrap.cxx
      gcc -shared -L/usr/local/lib -o shape.so shape_wrap.o -L. \
      -lruby -lruby -lc
      - - - - - +
      $ ruby extconf.rb
      +creating Makefile
      +$ make
      +g++ -fPIC -g -O2 -I. -I/usr/local/lib/ruby/1.7/i686-linux \
      +-I. -c shape_wrap.cxx
      +gcc -shared -L/usr/local/lib -o shape.so shape_wrap.o -L. \
      +-lruby -lruby -lc
      - - - -

      Note that depending on your installation, the outputs may be slightly different; these outputs are those for a Linux-based development environment. The end result should be a shared library @@ -9546,67 +4479,36 @@ development environment. The end result should be a shared library code. Now repeat this process in a separate directory for the Circle module:

      - - - -
        - - - - -
      1. Run SWIG to generate the wrapper code (circle_wrap.cxx);
      2. - - - - -
      3. Write an extconf.rb script that your end-users can use to create a platform-specific Makefile for the extension;
      4. - - - - -
      5. Build the shared library for this extension by typing make.
      6. - - - - -
      - - - -

      Once you've built both of these extension modules, you can test them interactively in IRB to confirm that the Shape and Circle modules are properly loaded and initialized:

      - - - -
      -
      $ irb
      irb(main):001:0> require 'shape'
      true
      irb(main):002:0> require 'circle'
      true
      irb(main):003:0> c = Circle::Circle.new(5, 5, 20)
      #<Circle::Circle:0xa097208>
      irb(main):004:0> c.kind_of? Shape::Shape
      true
      irb(main):005:0> c.getX()
      5.0
      - - - - - +
      $ irb
      +irb(main):001:0> require 'shape'
      +true
      +irb(main):002:0> require 'circle'
      +true
      +irb(main):003:0> c = Circle::Circle.new(5, 5, 20)
      +#<Circle::Circle:0xa097208>
      +irb(main):004:0> c.kind_of? Shape::Shape
      +true
      +irb(main):005:0> c.getX()
      +5.0
      - - - - -

      36.9.3 Specifying Mixin Modules

      +

      37.9.3 Specifying Mixin Modules

      The Ruby language doesn't support multiple inheritance, but @@ -9614,97 +4516,66 @@ it does allow you to mix one or more modules into a class using Ruby's inclu method. For example, if you have a Ruby class that defines an each instance method, e.g.

      - - - -
      -
      class Set
      def initialize
      @members = []
      end

      def each
      @members.each { |m| yield m }
      end
      end
      - - - - - +
      class Set
      +  def initialize
      +  @members = []
      +  end
      + 
      +  def each
      +  @members.each { |m| yield m }
      +  end
      +end
      - - - -

      then you can mix-in Ruby's Enumerable module to easily add a lot of functionality to your class:

      - - - -
      -
      class Set
      include Enumerable
      def initialize
      @members = []
      end
      def each
      @members.each { |m| yield m }
      end
      end
      - - - - - +
      class Set
      +  include Enumerable
      +  def initialize
      +    @members = []
      +  end
      +  def each
      +    @members.each { |m| yield m }
      +  end
      +end
      - - - -

      To get the same benefit for your SWIG-wrapped classes, you can use the %mixin directive to specify the names of one or more modules that should be mixed-in to a class. For the above example, the SWIG interface specification might look like this:

      - - - -
      -
      %mixin Set "Enumerable";

      class Set {
      public:
      // Constructor
      Set();

      // Iterates through set members
      void each();
      };
      - - - - +
      %mixin Set "Enumerable";
       
      +class Set {
      +public:
      +  // Constructor
      +  Set();
      + 
      +  // Iterates through set members
      +  void each();
      +};
      - - - -

      Multiple modules can be mixed into a class by providing a comma-separated list of module names to the %mixin directive, e.g.

      - - - -
      %mixin Set "Fee,Fi,Fo,Fum";
      - - - - -
      - - - -

      Note that the %mixin directive is implemented using SWIG's "features" mechanism and so the same name matching rules used for other kinds of features apply (see the chapter on "Customization Features") for more details).

      - - - - -

      36.10 Memory Management

      +

      37.10 Memory Management

      One of the most common issues in generating SWIG bindings for @@ -9712,46 +4583,22 @@ Ruby is proper memory management. The key to proper memory management is clearly defining whether a wrapper Ruby object owns the underlying C struct or C++ class. There are two possibilities:

      - - - -
        - - - -
      • The Ruby object is responsible for freeing the C struct or C++ object
      • - - - -
      • The Ruby object should not free the C struct or C++ object because it will be freed by the underlying C or C++ code
      • - - - -
      - - - -

      To complicate matters, object ownership may transfer from Ruby to C++ (or vice versa) depending on what function or methods are invoked. Clearly, developing a SWIG wrapper requires a thorough understanding of how the underlying library manages memory.

      - - - - -

      36.10.1 Mark and Sweep Garbage Collector

      +

      37.10.1 Mark and Sweep Garbage Collector

      Ruby uses a mark and sweep garbage collector. When the garbage @@ -9768,38 +4615,22 @@ In the sweep phase, all objects that have not been marked will be garbage collected. For more information about the Ruby garbage collector please refer to http://rubygarden.org/ruby/ruby?GCAndExtensions.

      - - - -

      The Ruby C/API provides extension developers two hooks into the garbage collector - a "mark" function and a "sweep" function. By default these functions are set to NULL.

      - - - -

      If a C struct or C++ class references any other Ruby objects, then it must provide a "mark" function. The "mark" function should identify any referenced Ruby objects by calling the rb_gc_mark function for each one. Unsurprisingly, this function will be called by the Ruby garbage during the "mark" phase.

      - - - -

      During the sweep phase, Ruby destroys any unused objects. If any memory has been allocated in creating the underlying C struct or C++ struct, then a "free" function must be defined that deallocates this memory.

      - - - - -

      36.10.2 Object Ownership

      +

      37.10.2 Object Ownership

      As described above, memory management depends on clearly @@ -9809,171 +4640,92 @@ then a "free" function must be registered for the object. If the Ruby object is not responsible for freeing the underlying memory, then a "free" function must not be registered for the object.

      - - - -

      For the most part, SWIG takes care of memory management issues. The rules it uses are:

      - - - -
        - - - -
      • When calling a C++ object's constructor from Ruby, SWIG will assign a "free" function thereby making the Ruby object responsible for freeing the C++ object
      • - - - -
      • When calling a C++ member function that returns a pointer, SWIG will not assign a "free" function thereby making the underlying library responsible for freeing the object.
      • - - - -
      - - - -

      To make this clearer, let's look at an example. Assume we have a Foo and a Bar class.

      - - - -
      -
      /* File "RubyOwernshipExample.h" */

      class Foo
      {
      public:
      Foo() {}
      ~Foo() {}
      };

      class Bar
      {
      Foo *foo_;
      public:
      Bar(): foo_(new Foo) {}
      ~Bar() { delete foo_; }
      Foo* get_foo() { return foo_; }
      Foo* get_new_foo() { return new Foo; }
      void set_foo(Foo *foo) { delete foo_; foo_ = foo; }
      };

      - - - +
      /* File "RubyOwernshipExample.h" */
       
      +class Foo
      +{
      +public:
      +  Foo() {}
      +  ~Foo() {}
      +};
       
      +class Bar
      +{
      +  Foo *foo_;
      +public:
      +  Bar(): foo_(new Foo) {}
      +  ~Bar() { delete foo_; }
      +  Foo* get_foo() { return foo_; }
      +  Foo* get_new_foo() { return new Foo; }
      +  void set_foo(Foo *foo) { delete foo_; foo_ = foo; }
      +};
      - - - -

      First, consider this Ruby code:

      - - - -
      foo = Foo.new
      - - - - -
      - - - -

      In this case, the Ruby code calls the underlying Foo C++ constructor, thus creating a new foo object. By default, SWIG will assign the new Ruby object a "free" function. When the Ruby object is garbage collected, the "free" function will be -called. It in turn will call Foo's destructor.

      - - - - +called. It in turn will call Foo's destructor.

      Next, consider this code:

      - - - -
      -
      bar = Bar.new
      foo = bar.get_foo()
      - - - - - +
      bar = Bar.new
      +foo = bar.get_foo()
      - - - -

      In this case, the Ruby code calls a C++ member function, get_foo. By default, SWIG will not assign the Ruby object a "free" function. Thus, when the Ruby object is garbage collected the underlying C++ foo object is not affected.

      - - - -

      Unfortunately, the real world is not as simple as the examples above. For example:

      - - - -
      -
      bar = Bar.new
      foo = bar.get_new_foo()
      - - - - - +
      bar = Bar.new
      +foo = bar.get_new_foo()
      - - - -

      In this case, the default SWIG behavior for calling member functions is incorrect. The Ruby object should assume ownership of the returned object. This can be done by using the %newobject directive. See Object ownership and %newobject for more information.

      - - - -

      The SWIG default mappings are also incorrect in this case:

      - - - -
      -
      foo = Foo.new
      bar = Bar.new
      bar.set_foo(foo)
      - - - - - +
      foo = Foo.new
      +bar = Bar.new
      +bar.set_foo(foo)
      - - - -

      Without modification, this code will cause a segmentation fault. When the Ruby foo object goes out of scope, it will free the underlying C++ foo @@ -9984,17 +4736,9 @@ Ruby object to the C++ object when the set_foo method is called. This can be done by using the special DISOWN type map, which was added to the Ruby bindings in SWIG-1.3.26.

      - - - -

      Thus, a correct SWIG interface file correct mapping for these classes is:

      - - - -
      /* File RubyOwnershipExample.i */
       
      @@ -10007,92 +4751,108 @@ classes is:

      class Foo { public: - Foo(); - ~Foo(); + Foo(); + ~Foo(); }; class Bar { - Foo *foo_; + Foo *foo_; public: - Bar(); - ~Bar(); - Foo* get_foo(); + Bar(); + ~Bar(); + Foo* get_foo(); - %newobject get_new_foo; - Foo* get_new_foo(); + %newobject get_new_foo; + Foo* get_new_foo(); - %apply SWIGTYPE *DISOWN {Foo *foo}; - void set_foo(Foo *foo); - %clear Foo *foo; + %apply SWIGTYPE *DISOWN {Foo *foo}; + void set_foo(Foo *foo); + %clear Foo *foo; }; -
      - - - - -
      - - - - -
      - - - - -

      This code can be seen in swig/examples/ruby/tracking.

      - - - - -
      - - - - - -

      36.10.3 Object Tracking

      +

      37.10.3 Object Tracking

      The remaining parts of this section will use the class library shown below to illustrate different memory management techniques. The class library models a zoo and the animals it contains.

      - - - -
      -
      %module zoo

      %{
      #include <string>
      #include <vector>

      #include "zoo.h"
      %}

      class Animal
      {
      private:
      typedef std::vector<Animal*> AnimalsType;
      typedef AnimalsType::iterator IterType;
      protected:
      AnimalsType animals;
      protected:
      std::string name_;
      public:
      // Construct an animal with this name
      Animal(const char* name) : name_(name) {}

      // Return the animal's name
      const char* get_name() const { return name.c_str(); }
      };

      class Zoo
      {
      protected:
      std::vector<animal *=""> animals;

      public:
      // Construct an empty zoo
      Zoo() {}

      /* Create a new animal. */
      static Animal* Zoo::create_animal(const char* name)
      {
      return new Animal(name);
      }

      // Add a new animal to the zoo
      void add_animal(Animal* animal) {
      animals.push_back(animal);
      }

      Animal* remove_animal(size_t i) {
      Animal* result = this->animals[i];
      IterType iter = this->animals.begin();
      std::advance(iter, i);
      this->animals.erase(iter);

      return result;
      }

      // Return the number of animals in the zoo
      size_t get_num_animals() const {
      return animals.size();
      }

      // Return a pointer to the ith animal
      Animal* get_animal(size_t i) const {
      return animals[i];
      }
      };

      - +
      %module zoo
       
      +%{
      +#include <string>
      +#include <vector>
       
      +#include "zoo.h"
      +%}
       
      +class Animal
      +{
      +private:
      +  typedef std::vector<Animal*> AnimalsType;
      +  typedef AnimalsType::iterator IterType;
      +protected:
      +  AnimalsType animals;
      +protected:
      +  std::string name_;
      +public:
      +  // Construct an animal with this name
      +  Animal(const char* name) : name_(name) {}
      + 
      +  // Return the animal's name
      +  const char* get_name() const { return name.c_str(); }
      +};
       
      +class Zoo
      +{
      +protected:
      + std::vector<animal *=""> animals;
      + 
      +public:
      +  // Construct an empty zoo
      +  Zoo() {}
      +  
      +  /* Create a new animal. */
      +  static Animal* Zoo::create_animal(const char* name) {
      +    return new Animal(name);
      +  }
      + 
      +  // Add a new animal to the zoo
      +  void add_animal(Animal* animal) {
      +    animals.push_back(animal); 
      +  }
      + 
      +  Animal* remove_animal(size_t i) {
      +    Animal* result = this->animals[i];
      +    IterType iter = this->animals.begin();
      +    std::advance(iter, i);
      +    this->animals.erase(iter);
      +   
      +    return result;
      +  }
      +  
      +  // Return the number of animals in the zoo
      +  size_t get_num_animals() const {
      +    return animals.size(); 
      +  }
      +  
      +  // Return a pointer to the ith animal
      +  Animal* get_animal(size_t i) const {
      +    return animals[i]; 
      +  }
      +};
      - - - - -

      Let's say you SWIG this code and then run IRB:
      - - - - +

      Let's say you SWIG this code and then run IRB:

      - - - -
      $ irb
       irb(main):001:0> require 'example'
      @@ -10121,33 +4881,14 @@ irb(main):008:0> tiger2.get_name()
       
       irb(main):009:0> tiger1.equal?(tiger2)
       => false
      -
       
      - - - - -
      - - - -

      Pay particular attention to the code tiger1.equal?(tiger2). Note that the two Ruby objects are not the same - but they reference -the same underlying C++ object. This can cause problems. For example:
      - - - - - +the same underlying C++ object. This can cause problems. For example:

      - - - -
      irb(main):010:0> tiger1 = nil
       => nil
      @@ -10157,19 +4898,9 @@ irb(main):011:0> GC.start
       
       irb(main):012:0> tiger2.get_name()
       (irb):12: [BUG] Segmentation fault
      -
       
      - - - - -
      - - - -

      After the garbage collector runs, as a result of our call to GC.start, callingtiger2.get_name() causes a segmentation fault. The problem is that when tiger1 @@ -10177,116 +4908,85 @@ is garbage collected, it frees the underlying C++ object. Thus, when tiger2< calls the get_name() method it invokes it on a destroyed object.

      - - - -

      This problem can be avoided if SWIG enforces a one-to-one mapping between Ruby objects and C++ classes. This can be done via the use of the %trackobjects functionality available in SWIG-1.3.26. and later.

      - - - -

      When the %trackobjects is turned on, SWIG automatically keeps track of mappings between C++ objects and Ruby objects. Note that enabling object tracking causes a slight performance degradation. Test results show this degradation to be about 3% to 5% when creating and destroying 100,000 animals in a row.

      - - - -

      Since %trackobjects is implemented as a %feature, it uses the same name matching rules as other kinds of features (see the chapter on "Customization Features") . Thus it can be applied on a 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"
      - - - - -

      When this code runs we see:
      - - - - - -
      - - - - - +

      When this code runs we see:

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

      For those who are interested, object tracking is implemented by storing Ruby objects in a hash table and keying them on C++ -pointers. The underlying API is:
      - - - - +pointers. The underlying API is:

      - - - -
      -
      static void SWIG_RubyAddTracking(void* ptr, VALUE object);
      static VALUE SWIG_RubyInstanceFor(void* ptr) ;
      static void SWIG_RubyRemoveTracking(void* ptr);
      static void SWIG_RubyUnlinkObjects(void* ptr);
      - - - - - +
      static void SWIG_RubyAddTracking(void* ptr, VALUE object);
      +static VALUE SWIG_RubyInstanceFor(void* ptr) ;
      +static void SWIG_RubyRemoveTracking(void* ptr);
      +static void SWIG_RubyUnlinkObjects(void* ptr);
      - - - -

      When an object is created, SWIG will automatically call the SWIG_RubyAddTracking method. Similarly, when an object is deleted, SWIG will call the SWIG_RubyRemoveTracking. When an object is returned to Ruby from C++, SWIG will use the SWIG_RubyInstanceFor @@ -10294,58 +4994,49 @@ method to ensure a one-to-one mapping from Ruby to C++ objects. Last, the RubyUnlinkObjects method unlinks a Ruby object from its underlying C++ object.

      - - - -

      In general, you will only need to use the SWIG_RubyInstanceFor, which is required for implementing mark functions as shown below. However, if you implement your own free functions (see below) you may also have to call the SWIG_RubyRemoveTracking and RubyUnlinkObjects methods.

      - - - - -

      36.10.4 Mark Functions

      +

      37.10.4 Mark Functions

      With a bit more testing, we see that our class library still -has problems. For example:
      - - - - +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
      - - - -

      The problem is that Ruby does not know that the zoo object contains a reference to a Ruby object. Thus, when Ruby garbage -collects tiger1 +collects tiger1 it frees the underlying C++ object.

      - - - -

      This can be fixed by implementing a mark function as described above in the Mark and Sweep Garbage Collector section. You can specify a mark @@ -10355,10 +5046,6 @@ SWIG's' "features" mechanism it uses the same name matching rules as other kinds of features (see the chapter on "Customization Features" for more details).

      - - - -

      A mark function takes a single argument, which is a pointer to the C++ object being marked; it should, in turn, call rb_gc_mark() for any instances that are @@ -10368,75 +5055,87 @@ objects in the zoo object, look up their Ruby object equivalent, and then call rb_gc_mark(). One possible 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);
      +    }
      +  }
      +}
      +%}
      - - - -

      Note the mark function is dependent on the SWIG_RUBY_InstanceFor method, and thus requires that %trackobjects is enabled. For more information, please refer to the track_object.i test case in the SWIG test suite.

      - - - -

      When this code is compiled we now see:

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

      This code can be seen in swig/examples/ruby/mark_function.

      - - - - -

      36.10.5 Free Functions

      +

      37.10.5 Free Functions

      By default, SWIG creates a "free" function that is called when a Ruby object is garbage collected. The free function simply calls the C++ object's destructor.

      - - - -

      However, sometimes an appropriate destructor does not exist or special processing needs to be performed before the destructor is called. Therefore, SWIG allows you to manually specify a "free" @@ -10446,10 +5145,6 @@ SWIG's' "features" mechanism and so the same name matching rules used for other kinds of features apply (see the chapter on "Customization Features") for more details).

      - - - -

      IMPORTANT ! - If you define your own free function, then you must ensure that you call the underlying C++ object's destructor. In addition, if object tracking is activated for the object's class, you @@ -10458,10 +5153,6 @@ function (of course call this before you destroy the C++ object). Note that it is harmless to call this method if object tracking if off so it is advised to always call it.

      - - - -

      Note there is a subtle interaction between object ownership and free functions. A custom defined free function will only be called if the Ruby object owns the underlying C++ object. This also to Ruby @@ -10469,21 +5160,13 @@ objects which are created, but then transfer ownership to C++ objects via the use of the disown typemap described above.

      - - - -

      To show how to use the %freefunc directive, let's slightly change our example. Assume that the zoo object is responsible for freeing animal that it contains. This means -that the Zoo::add_animal -function should be marked with a DISOWN typemap +that the Zoo::add_animal +function should be marked with a DISOWN typemap and the destructor should be updated as below:

      - - - -
      Zoo::~Zoo() {
        IterType iter = this->animals.begin();
      @@ -10494,23 +5177,10 @@ and the destructor should be updated as below:

      delete animal; } }
      - - - - -
      - - - -

      When we use these objects in IRB we see:

      - - - -
      $irb
       irb(main):002:0> require 'example'
      @@ -10533,19 +5203,9 @@ irb(main):008:0> GC.start
       
       irb(main):009:0> tiger1.get_name()
       (irb):12: [BUG] Segmentation fault
      -
       
      - - - - -
      - - - -

      The error happens because the C++ animal object is freed when the zoo object is freed. Although this error is unavoidable, we can at least prevent the @@ -10554,18 +5214,9 @@ implementing a custom free function that calls the SWIG_RubyUnlinkObjectsSWIG_RubyUnlinkObjects function notifies SWIG that a Ruby object's underlying C++ object is no longer valid. Once notified, SWIG will intercept any calls from the -existing Ruby object to the destroyed C++ object and raise an exception.
      - - - - - +existing Ruby object to the destroyed C++ object and raise an exception.

      - - - -
      %module example
       
      @@ -10586,47 +5237,33 @@ existing Ruby object to the destroyed C++ object and raise an exception.
      %include "example.h" %header %{ - static void free_Zoo(void* ptr) { - Zoo* zoo = (Zoo*) ptr; + static void free_Zoo(void* ptr) { + Zoo* zoo = (Zoo*) ptr; - /* Loop over each animal */ - int count = zoo->get_num_animals(); + /* 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); + 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); + /* Unlink the Ruby object from the C++ object */ + SWIG_RubyUnlinkObjects(animal); - /* Now remove the tracking for this animal */ - SWIG_RubyRemoveTracking(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; - } + /* Now call SWIG_RubyRemoveTracking for the zoo */ + SWIG_RubyRemoveTracking(ptr); + /* Now free the zoo which will free the animals it contains */ + delete zoo; + } %}
      - - - - -
      - - - -

      Now when we use these objects in IRB we see:

      - - - -
      $irb
       irb(main):002:0> require 'example'
      @@ -10652,159 +5289,82 @@ RuntimeError: This Animal * already released
        from (irb):10:in `get_name'
        from (irb):10
       irb(main):011:0>
      - - - - -
      - - - -

      Notice that SWIG can now detect the underlying C++ object has been freed, and thus raises a runtime exception.

      - - - -

      This code can be seen in swig/examples/ruby/free_function.

      - - - - -

      36.10.6 Embedded Ruby and the C++ Stack

      +

      37.10.6 Embedded Ruby and the C++ Stack

      As has been said, the Ruby GC runs and marks objects before its -sweep phase.  When the garbage collector is called, it will +sweep phase. When the garbage collector is called, it will also try to mark any Ruby objects (VALUE) it finds in the machine registers and in the C++ stack.

      - - - -

      The stack is basically the history of the functions that have been called and also contains local variables, such as the ones you define whenever you do inside a function:

      - - - -
      VALUE obj;
      - - - -

      For ruby to determine where its stack space begins, during initialization a normal Ruby interpreter will call the ruby_init() function which in turn will call a function called Init_stack or -similar.  This function will store a pointer to the location +similar. This function will store a pointer to the location where the stack points at that point in time.

      - - - -

      ruby_init() is presumed to always be called within the main() function of your program and whenever the GC is called, ruby will assume that the memory between the current location in memory and the pointer that was stored previously represents the stack, which may -contain local (and temporary) VALUE ruby objects.   Ruby will +contain local (and temporary) VALUE ruby objects. Ruby will then be careful not to remove any of those objects in that location.

      - - - - -

      So far so good.  For a normal Ruby session, all the +

      So far so good. For a normal Ruby session, all the above is completely transparent and magic to the extensions developer. -  

      - - - - +

      However, with an embedded Ruby, it may not always be possible to -modify main() to make sure ruby_init() is called there.   As +modify main() to make sure ruby_init() is called there. As such, ruby_init() will likely end up being called from within some other -function.  This can lead Ruby to measure incorrectly where the -stack begins and can result in Ruby incorrectly collecting +function. This can lead Ruby to measure incorrectly where the +stack begins and can result in Ruby incorrectly collecting those -temporary VALUE objects that are created once another function +temporary VALUE objects that are created once another function is -called.  The end result: random crashes and segmentation +called. The end result: random crashes and segmentation faults.

      - - - -

      This problem will often be seen in director functions that are -used for callbacks, for example.  

      - - - - +used for callbacks, for example.

      To solve the problem, SWIG can now generate code with director -functions containing the optional macros SWIG_INIT_STACK and -SWIG_RELEASE_STACK.   These macros will try to force Ruby to -reinitiliaze the beginning of the stack the first time a +functions containing the optional macros SWIG_INIT_STACK and +SWIG_RELEASE_STACK. These macros will try to force Ruby to +reinitiliaze the beginning of the stack the first time a director -function is called.  This will lead Ruby to measure and not -collect any VALUE objects defined from that point on.  

      - - - - +function is called. This will lead Ruby to measure and not +collect any VALUE objects defined from that point on.

      To mark functions to either reset the ruby stack or not, you can use:

      - - - - -
      %initstack -  Class::memberfunction;  // only re-init the stack -in this director method
      - - - - - -%ignorestack Class::memberfunction;  // do not re-init the -stack in this director method
      - - - - - -%initstack   Class;       -        // init the stack on all -the methods of this class
      - - - - - -%initstack;   // all director functions will -re-init the stack
      - +
      +%initstack Class::memberfunction;   // only re-init the stack in this director method
      +%ignorestack Class::memberfunction; // do not re-init the stack in this director method
      +%initstack Class;                   // init the stack on all the methods of this class
      +%initstack;                         // all director functions will re-init the stack
      +
      diff --git a/Doc/Manual/SWIG.html b/Doc/Manual/SWIG.html index 58a3c8e55..bd929f7d4 100644 --- a/Doc/Manual/SWIG.html +++ b/Doc/Manual/SWIG.html @@ -224,7 +224,7 @@ $ swig -c++ -python -o example_wrap.cpp example.i

      The C/C++ output file created by SWIG often -contains everything that is needed to construct a extension module +contains everything that is needed to construct an extension module for the target scripting language. SWIG is not a stub compiler nor is it usually necessary to edit the output file (and if you look at the output, you probably won't want to). To build the final extension module, the @@ -233,7 +233,7 @@ program to create a shared library.

      -Many target languages will also generate proxy class files in the +For many target languages SWIG will also generate proxy class files in the target language. The default output directory for these language specific files is the same directory as the generated C/C++ file. This can be modified using the -outdir option. For example: @@ -258,7 +258,7 @@ this option the default output directory is the path to the input file. If -o and -outcurrentdir are used together, -outcurrentdir is effectively ignored as the output directory for the language files is the same directory as the -generated C/C++ file if not overidden with -outdir. +generated C/C++ file if not overridden with -outdir.

      5.1.3 Comments

      @@ -484,7 +484,7 @@ Or in Python: Whenever possible, SWIG creates an interface that closely matches the underlying C/C++ code. However, due to subtle differences between languages, run-time environments, and semantics, it is not always possible to do so. The -next few sections describes various aspects of this mapping. +next few sections describe various aspects of this mapping.

      5.2.1 Basic Type Handling

      @@ -728,7 +728,7 @@ However, for the same conservative reasons even a constant with a simple cast wi
      -#define F_CONST (double) 5            // A floating pointer constant with cast
      +#define F_CONST (double) 5            // A floating point constant with cast
       
      @@ -750,7 +750,7 @@ enum values as assigned by the C compiler.

      The %constant directive is used to more precisely create constants corresponding to different C datatypes. Although it is not -usually not needed for simple values, it is more useful when working +usually needed for simple values, it is more useful when working with pointers and other more complex datatypes. Typically, %constant is only used when you want to add constants to the scripting language interface that are not defined in the original header file. @@ -868,7 +868,7 @@ from a scripting language to a C char *, the pointer usually points to string data stored inside the interpreter. It is almost always a really bad idea to modify this data. Furthermore, some languages may explicitly disallow it. For instance, in Python, -strings are supposed be immutable. If you violate this, you will probably +strings are supposed to be immutable. If you violate this, you will probably receive a vast amount of wrath when you unleash your module on the world.

      @@ -1483,7 +1483,7 @@ void transpose(double (*a)[20]);

      Like C, SWIG does not perform array bounds checking. It is up to the -user to make sure the pointer points a suitably allocated region of memory. +user to make sure the pointer points to a suitably allocated region of memory.

      @@ -1888,11 +1888,22 @@ and a more descriptive one, but the two functions are otherwise equivalent: 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 + can contain back-references of the form \N where N is a digit + from 0 to 9, or one of the following escape sequences: \l, \L, + \u, \U or \E. The back-references are replaced with the + contents of the corresponding capture group while the escape sequences perform the + case conversion in the substitution string: \l and \L convert to + the lower case, while \u and \U convert to the upper case. The + difference between the elements of each pair is that \l and \u + change the case of the next character only, while \L and \U do + it for all the remaining characters or until \E is encountered. + + Finally please notice that backslashes need to be escaped in C strings, so in + practice "\\" must be used in all these escape sequences. For example, + to remove any alphabetic prefix before an underscore and capitalize the remaining + part you could use the following directive: + %rename("regex:/(\\w+)_(.*)/\\u\\2/") + prefix_printPrint command:cmd @@ -2254,7 +2265,7 @@ disabled using %nocallback. When you do this, the interface now works

      Notice that when the function is used as a callback, special names -such as add_cb is used instead. To call the function +such as add_cb are used instead. To call the function normally, just use the original function name such as add().

      @@ -2300,7 +2311,7 @@ handle C++ are described in the next section. If SWIG encounters the definition of a structure or union, it creates a set of accessor functions. Although SWIG does not need structure definitions to build an interface, providing definitions -make it possible to access structure members. The accessor functions +makes it possible to access structure members. The accessor functions generated by SWIG simply take a pointer to an object and allow access to an individual member. For example, the declaration :

      @@ -2423,7 +2434,7 @@ vector_struct
      , SWIG knows that this is the same as Structures involving character strings require some care. SWIG assumes that all members of type char * have been dynamically allocated using malloc() and that they are NULL-terminated -ASCII strings. When such a member is modified, the previously contents +ASCII strings. When such a member is modified, the previous contents will be released, and the new contents allocated. For example :

      @@ -2508,7 +2519,7 @@ typedef struct Bar {
       

      When a structure member is wrapped, it is handled as a pointer, unless the %naturalvar directive is used where it is handled more like a C++ reference (see C++ Member data). -The accessors to the member variable as a pointer is effectively wrapped as follows: +The accessors to the member variable as a pointer are effectively wrapped as follows:

      @@ -2645,8 +2656,8 @@ struct Bar { // Default constructor generated.

      -Since ignoring the implicit or default destructors most of the times -produce memory leaks, SWIG will always try to generate them. If +Since ignoring the implicit or default destructors most of the time +produces memory leaks, SWIG will always try to generate them. If needed, however, you can selectively disable the generation of the default/implicit destructor by using %nodefaultdtor

      @@ -2676,7 +2687,7 @@ has now been enabled as the default behavior. Note: There are also the -nodefault option and %nodefault directive, which disable both the default or implicit destructor generation. This could lead to memory leaks across -the target languages, and is highly recommended you don't use them. +the target languages, and it is highly recommended you don't use them.

      @@ -2699,7 +2710,7 @@ the following declaration :

       /* file : vector.h */
       ...
      -typedef struct {
      +typedef struct Vector {
       	double x,y,z;
       } Vector;
       
      @@ -2772,7 +2783,7 @@ of the Vector structure. For example:

      #include "vector.h" %} -typedef struct { +typedef struct Vector { double x,y,z; %extend { Vector(double x, double y, double z) { ... } @@ -2783,7 +2794,7 @@ typedef struct {

      -Finally, %extend can be used to access externally written +Note that %extend can be used to access externally written functions provided they follow the naming convention used in this example :

      @@ -2814,7 +2825,7 @@ double Vector_magnitude(Vector *v) { #include "vector.h" %} -typedef struct { +typedef struct Vector { double x,y,z; %extend { Vector(int,int,int); // This calls new_Vector() @@ -2826,6 +2837,37 @@ typedef struct {
      +

      +The name used for %extend should be the name of the struct and not the name of any typedef to the struct. +For example: +

      + +
      +typedef struct Integer {
      +	int value;
      +} Int;
      +%extend Integer { ...  } /* Correct name */
      +%extend Int { ...  } /* Incorrect name */
      +
      +struct Float {
      +	float value;
      +};
      +typedef struct Float FloatValue;
      +%extend Float { ...  } /* Correct name */
      +%extend FloatValue { ...  } /* Incorrect name */
      +
      + +

      +There is one exception to this rule and that is when the struct is anonymously named such as: +

      + +
      +typedef struct {
      +	double value;
      +} Double;
      +%extend Double { ...  } /* Okay */
      +
      +

      A little known feature of the %extend directive is that it can also be used to add synthesized attributes or to modify the @@ -2862,7 +2904,7 @@ For example, consider this interface:

      -typedef struct {
      +typedef struct Person {
         char name[50];
         ...
       } Person;
      @@ -2876,7 +2918,7 @@ the interface as follows to ensure this occurs whenever a name is read or writte
       
       
      -typedef struct {
      +typedef struct Person {
         %extend {
           char name[50];
         }
      @@ -3238,7 +3280,7 @@ initialization on module loading, you could write this:
       
       
       

      -This section describes the general approach for building interface +This section describes the general approach for building interfaces with SWIG. The specifics related to a particular scripting language are found in later chapters.

      @@ -3253,9 +3295,9 @@ of steps you can follow to make an interface for a C program :

      • Identify the functions that you want to wrap. It's probably not -necessary to access every single function in a C program--thus, a +necessary to access every single function of a C program--thus, a little forethought can dramatically simplify the resulting scripting -language interface. C header files are particularly good source for +language interface. C header files are a particularly good source for finding things to wrap.
      • Create a new interface file to describe the scripting language @@ -3300,7 +3342,7 @@ to the swig-devel mailing list or to

        -The preferred method of using SWIG is to generate separate interface +The preferred method of using SWIG is to generate a separate interface file. Suppose you have the following C header file :

        @@ -3394,7 +3436,7 @@ include certain header files by using a %{,%} block like this:
         #include <GL/glu.h>
         %}
         
        -// Put rest of declarations here
        +// Put the rest of the declarations here
         ...
         
        @@ -3436,7 +3478,7 @@ program that is more interactive. In many cases, the old or Tcl script.

        -Note: If some cases, you might be inclined to create a +Note: In some cases, you might be inclined to create a scripting language wrapper for main(). If you do this, the compilation will probably work and your module might even load correctly. The only trouble is that when you call your diff --git a/Doc/Manual/SWIGPlus.html b/Doc/Manual/SWIGPlus.html index b4baca6ae..f9558994b 100644 --- a/Doc/Manual/SWIGPlus.html +++ b/Doc/Manual/SWIGPlus.html @@ -185,7 +185,6 @@ The following C++ features are not currently supported:

        • Overloaded versions of certain operators (new, delete, etc.) -
        • Nested classes, see Nested classes for workarounds.

        @@ -217,7 +216,7 @@ to use the C++ compiler. For example:

         $ swig -c++ -tcl example.i
        -$ c++ -c example_wrap.cxx 
        +$ c++ -fPIC -c example_wrap.cxx 
         $ c++ example_wrap.o $(OBJS) -o example.so
         
        @@ -960,8 +959,9 @@ Similarly, all data attributes declared as const are wrapped as read-on

        +By default, SWIG uses the const reference typemaps for members that are primitive types. There are some subtle issues when wrapping data members that are -themselves classes. For instance, if you had another class like this, +not primitive types, such as classes. For instance, if you had another class like this,

        @@ -974,7 +974,8 @@ public:

        -then the low-level accessor to the items member actually uses pointers. For example: +then the low-level accessor to the items member actually uses pointers. +For example:

        @@ -999,31 +1000,7 @@ This can be somewhat unnatural for some types. For example, a user would expect the STL std::string class member variables to be wrapped as a string in the target language, rather than a pointer to this class. The const reference typemaps offer this type of marshalling, so there is a feature to tell SWIG to use the const reference typemaps rather than the pointer typemaps. -It is the %naturalvar directive and is used as follows: -

        - -
        -
        -// All List variables will use const List& typemaps
        -%naturalvar List;
        -
        -// Only Foo::myList will use const List& typemaps
        -%naturalvar Foo::myList;
        -struct Foo {
        -  List myList;
        -};
        -
        -// All variables will use const reference typemaps
        -%naturalvar;
        -
        -
        - -

        -The observant reader will notice that %naturalvar works like any other -feature flag directive, -except it can also be attached to class types. -The first of the example usages above show %naturalvar attaching to the List class. -Effectively this feature changes the way accessors are generated to the following: +It is the naturalvar feature and can be used to effectively change the way accessors are generated to the following:

        @@ -1038,15 +1015,45 @@ void Foo_items_set(Foo *self, const List &value) {

        -In fact it is generally a good idea to use this feature globally as the reference typemaps have extra NULL checking compared to the pointer typemaps. +The %naturalvar directive is a macro for, and hence equivalent to, %feature("naturalvar"). It can be used as follows: +

        + +
        +
        +// All List variables will use const List& typemaps
        +%naturalvar List;
        +
        +// Only Foo::myList will use const List& typemaps
        +%naturalvar Foo::myList;
        +struct Foo {
        +  List myList;
        +};
        +
        +// All non-primitive types will use const reference typemaps
        +%naturalvar;
        +
        +
        + +

        +The observant reader will notice that %naturalvar works like any other +feature flag directive but with some extra flexibility. +The first of the example usages above shows %naturalvar attaching to the myList's variable type, that is the List class. +The second usage shows %naturalvar attaching to the variable name. +Hence the naturalvar feature can be used on either the variable's name or type. +Note that using the naturalvar feature on a variable's name overrides any naturalvar feature attached to the variable's type. +

        + +

        +It is generally a good idea to use this feature globally as the reference typemaps have extra NULL checking compared to the pointer typemaps. A pointer can be NULL, whereas a reference cannot, so the extra checking ensures that the target language user does not pass in a value that translates to a NULL pointer and thereby preventing any potential NULL pointer dereferences. The %naturalvar feature will apply to global variables in addition to member variables in some language modules, eg C# and Java.

        -Other alternatives for turning this feature on globally are to use the swig -naturalvar commandline option -or the module mode option, %module(naturalvar=1) +The naturalvar behavior can also be turned on as a global setting via the -naturalvar commandline option +or the module mode option, %module(naturalvar=1). +However, any use of %feature("naturalvar") will override the global setting.

        @@ -1522,7 +1529,7 @@ multiple inheritance. spirit, and target language capabilities, as possible. In most cases, this means that SWIG will parse the non-public inheritance declarations, but that will have no effect in the generated code, -besides the implicit policies derived for constructor and +besides the implicit policies derived for constructors and destructors.

        @@ -2838,6 +2845,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 @@ -3121,8 +3134,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. 
       
      @@ -3163,7 +3176,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:

      @@ -4427,7 +4440,7 @@ around some other class. For example: template<class T> class SmartPtr { T *pointee; public: - ... + SmartPtr(T *p) : pointee(p) { ... } T *operator->() { return pointee; } @@ -4447,7 +4460,7 @@ typedef SmartPtr<Foo_Impl> Foo; // Create smart pointer Foo Foo make_Foo() { - return SmartPtr(new Foo_Impl()); + return SmartPtr<Foo_Impl>(new Foo_Impl()); } // Do something with smart pointer Foo @@ -4455,6 +4468,9 @@ void do_something(Foo f) { printf("x = %d\n", f->x); f->bar(); } + +// Call the wrapped smart pointer proxy class in the target language 'Foo' +%template(Foo) SmartPtr<Foo_Impl>;
      @@ -4958,141 +4974,55 @@ public:

      -There is some support for nested structs and unions when wrapping C code, -see Nested structures for further details. -The added complexity of C++ compared to C means this approach does not work well for -C++ code (when using the -c++ command line option). -For C++, a nested class is treated much like an opaque pointer, so anything useful within the nested class, such as its -methods and variables, are not accessible from the target language. -True nested class support may be added to SWIG in the future, however, -until then some of the following workarounds can be applied to improve the situation. +If the target language supports the nested classes concept (like Java), the nested C++ classes +are wrapped as nested target language proxy classes. (In case of Java - "static" nested classes.) +Only public nested classes are wrapped. Otherwise there is little difference between nested and +normal classes.

      -

      -It might be possible to use partial class information as often you can accept that the nested class is not needed, -especially if it is not actually used in any methods you need from the target language. -Imagine you are wrapping the following Outer class which contains a nested class Inner. -The easiest thing to do is turn a blind eye to the warning that SWIG generates, or simply suppress it: +If the target language doesn't support nested classes directly, or the support is not implemented in the +language module (like for python currently), then the visible nested classes are moved to the same name +space as the containing class (nesting hierarchy is "flattened"). The same behaviour may be turned on for +C# and Java by the %feature ("flatnested"); If there is a class with the same name in the outer namespace +the inner class (or the global one) may be renamed or ignored:

      -%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Outer::Inner;
      -
      -class Outer {
      -public:
      -  class Inner {
      -    public:
      -      ...
      -  };
      -  Inner getInner();
      -  void useInner(const Inner& inner);
      -  ...
      -};
      -
      -
      - -

      -Note that if Inner can be used as an opaque type, the default wrapping approach suffices. -For example, if the nested class does not need to be created from the target language, but can be obtained via a method -call, such as the getInner() method above, the returned value can then be passed around, such as passed into the -useInner() method. -

      - -

      -With some more effort the above situation can be improved somewhat and a nested class can be constructed and used -from the target language much like any other non-nested class. Assuming we have the Outer class in a header file: -

      - -
      -
      -// File outer.h
      -class Outer {
      -public:
      -  class Inner {
      -    public:
      -      int var;
      -      Inner(int v = 0) : var(v) {}
      -  };
      -  Inner getInner();
      -  void useInner(const Inner& inner);
      -};
      -
      -
      - -

      -The following interface file works around the nested class limitations by redefining the nested class as a global class. -A typedef for the compiler and the nestedworkaround -feature flag is also required in -order for the generated wrappers to compile. This flag simply removes all the type information from SWIG, so SWIG treats -the nested class as if it had not been parsed at all. -

      - -
      -
      -// File : example.i
      -%module example
      -
      -// Redefine nested class in global scope in order for SWIG to generate
      -// a proxy class. Only SWIG parses this definition.
      -class Inner {
      +%rename (Bar_Foo) Bar::Foo;
      +class Foo {};
      +class Bar {
         public:
      -    int var;
      -    Inner(int v = 0) : var(v) {}
      +  class Foo {};
       };
      -
      -%nestedworkaround Outer::Inner;
      -
      -%{
      -#include "outer.h"
      -%}
      -%include "outer.h"
      -
      -// We've fooled SWIG into thinking that Inner is a global class, so now we need
      -// to trick the C++ compiler into understanding this apparent global type.
      -%{
      -typedef Outer::Inner Inner;
      -%}
       
      -

      -The downside to this approach is a more complex interface file and having to maintain two definitions of Inner, -the real one and the one in the interface file that SWIG parses. -However, the upside is that all the methods/variables in the nested class are available from the target language -as a proxy class is generated instead of treating the nested class as an opaque type. -The proxy class can be constructed from the target language and passed into any methods accepting the nested class. -Also note that the original header file is parsed unmodified. -

      -Finally, conditional compilation can be used as a workaround to comment out nested class definitions in the actual headers, -assuming you are able to modify them. +Compatibility Note: +Prior to SWIG-3.0.0, there was limited nested class support. Nested classes were treated as opaque pointers. +However, there was a workaround for nested class support in these older versions requiring the user to replicate +the nested class in the global scope, adding in a typedef for the nested class in the global scope and +using the "nestedworkaround" feature on the nested class. This resulted in approximately the +same behaviour as the "flatnested" feature. With proper nested class support now available in SWIG-3.0.0, this +feature has been deprecated and no longer works requiring code changes. If you see the following warning:

      -
      +
      -// File outer.h
      -class Outer {
      -public:
      -#ifndef SWIG
      -  class Inner {
      -    public:
      -      ...
      -  };
      -#endif
      -  ...
      -};
      +example.i:8: Warning 126: The nestedworkaround feature is deprecated
       

      -This workaround used to be common when SWIG could not deal with nested classes particulary well. -This should just be a last resort for unusual corner cases now as SWIG can parse nested classes and even handle nested template classes fairly well. +consider using the "flatnested" feature discussed above which generates a non-nested proxy class, like the +"nestedworkaround" feature did. Alternatively, use the default nested class code generation, which may generate an +equivalent to a nested proxy class in the target language, depending on the target language support.

      -Compatibility Note: SWIG-1.3.40 and earlier versions did not have the nestedworkaround feature +SWIG-1.3.40 and earlier versions did not have the nestedworkaround feature and the generated code resulting from parsing nested classes did not always compile. Nested class warnings could also not be suppressed using %warnfilter.

      diff --git a/Doc/Manual/Scripting.html b/Doc/Manual/Scripting.html index e6a2eee24..c714fa0d7 100644 --- a/Doc/Manual/Scripting.html +++ b/Doc/Manual/Scripting.html @@ -293,7 +293,7 @@ A proxy class is a special kind of object that gets created in a scripting language to access a C/C++ class (or struct) in a way that looks like the original structure (that is, it proxies the real C++ class). For example, if you -have the following C definition :

      +have the following C++ definition :

       class Vector {
      @@ -334,12 +334,12 @@ Finally, in Tcl :
       
       
       Vector v
      -v configure -x 3 -y 4 -z 13
      +v configure -x 3 -y 4 -z -13
       
       

      -When proxy classes are used, two objects are at really work--one in +When proxy classes are used, two objects are really at work--one in the scripting language, and an underlying C/C++ object. Operations affect both objects equally and for all practical purposes, it appears as if you are simply manipulating a C/C++ object. @@ -353,7 +353,7 @@ The final step in using a scripting language with your C/C++ application is adding your extensions to the scripting language itself. There are two primary approaches for doing this. The preferred technique is to build a dynamically loadable -extension in the form a shared library. Alternatively, you can +extension in the form of a shared library. Alternatively, you can recompile the scripting language interpreter with your extensions added to it.

      @@ -364,21 +364,16 @@ added to it.

      To create a shared library or DLL, you often need to look at the manual pages for your compiler and linker. However, the procedure -for a few common machines is shown below:

      +for a few common platforms is shown below:

       # Build a shared library for Solaris
      -gcc -c example.c example_wrap.c -I/usr/local/include
      +gcc -fpic -c example.c example_wrap.c -I/usr/local/include
       ld -G example.o example_wrap.o -o example.so
       
       # Build a shared library for Linux
       gcc -fpic -c example.c example_wrap.c -I/usr/local/include
       gcc -shared example.o example_wrap.o -o example.so
      -
      -# Build a shared library for Irix
      -gcc -c example.c example_wrap.c -I/usr/local/include
      -ld -shared example.o example_wrap.o -o example.so
      -
       

      diff --git a/Doc/Manual/Sections.html b/Doc/Manual/Sections.html index 1151de1d5..877ca2fae 100644 --- a/Doc/Manual/Sections.html +++ b/Doc/Manual/Sections.html @@ -1,12 +1,12 @@ -SWIG-2.0 Documentation +SWIG-3.0 Documentation -

      SWIG-2.0 Documentation

      +

      SWIG-3.0 Documentation

      -Last update : SWIG-2.0.6 (30 April 2012) +Last update : SWIG-3.0.1 (in progress)

      Sections

      @@ -18,6 +18,7 @@ Last update : SWIG-2.0.6 (30 April 2012)
    • Scripting
    • SWIG Basics (Read this!)
    • SWIG and C++
    • +
    • SWIG and C++11
    • The SWIG preprocessor
    • The SWIG library
    • Argument handling
    • diff --git a/Doc/Manual/Tcl.html b/Doc/Manual/Tcl.html index f55a7f139..45eebbf5e 100644 --- a/Doc/Manual/Tcl.html +++ b/Doc/Manual/Tcl.html @@ -6,7 +6,7 @@ -

      37 SWIG and Tcl

      +

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

        -

        37.1 Preliminaries

        +

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

        -

        37.1.1 Getting the right header files

        +

        38.1.1 Getting the right header files

        @@ -127,19 +127,20 @@ this is the case, you should probably make a symbolic link so that tcl.h -

        37.1.2 Compiling a dynamic module

        +

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

         $ swig -tcl example.i
        -$ gcc -c example.c
        -$ gcc -c example_wrap.c -I/usr/local/include
        +$ gcc -fPIC -c example.c
        +$ gcc -fPIC -c example_wrap.c -I/usr/local/include
         $ gcc -shared example.o example_wrap.o -o example.so
         
        @@ -162,7 +163,7 @@ The name of the module is specified using the %module directive or the -module command line option.

        -

        37.1.3 Static linking

        +

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

        -

        37.1.4 Using your module

        +

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

        -

        37.1.5 Compilation of C++ extensions

        +

        38.1.5 Compilation of C++ extensions

        @@ -373,8 +374,8 @@ compiler. For example:

         % swig -c++ -tcl example.i
        -% g++ -c example.cxx
        -% g++ -c example_wrap.cxx -I/usr/local/include
        +% g++ -fPIC -c example.cxx
        +% g++ -fPIC -c example_wrap.cxx -I/usr/local/include
         % g++ -shared example.o example_wrap.o -o example.so
         
        @@ -386,8 +387,8 @@ Solaris, you often need to add an extra library -lCrun like this:
         % swig -c++ -tcl example.i
        -% CC -c example.cxx
        -% CC -c example_wrap.cxx -I/usr/local/include
        +% CC -KPIC -c example.cxx
        +% CC -KPIC -c example_wrap.cxx -I/usr/local/include
         % CC -G example.o example_wrap.o -L/opt/SUNWspro/lib -o example.so -lCrun
         
        @@ -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.

        -

        37.1.6 Compiling for 64-bit platforms

        +

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

        -

        37.1.7 Setting a package prefix

        +

        38.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".

        -

        37.1.8 Using namespaces

        +

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

        -

        37.2 Building Tcl/Tk Extensions under Windows 95/NT

        +

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

        -

        37.2.1 Running SWIG from Developer Studio

        +

        38.2.1 Running SWIG from Developer Studio

        @@ -576,7 +577,7 @@ MSDOS > tclsh80 %

      -

      37.2.2 Using NMAKE

      +

      38.2.2 Using NMAKE

      @@ -639,7 +640,7 @@ to get you started. With a little practice, you'll be making lots of Tcl extensions.

      -

      37.3 A tour of basic C/C++ wrapping

      +

      38.3 A tour of basic C/C++ wrapping

      @@ -650,7 +651,7 @@ classes. This section briefly covers the essential aspects of this wrapping.

      -

      37.3.1 Modules

      +

      38.3.1 Modules

      @@ -684,7 +685,7 @@ To fix this, supply an extra argument to load like this:

      -

      37.3.2 Functions

      +

      38.3.2 Functions

      @@ -709,7 +710,7 @@ like you think it does: %

      -

      37.3.3 Global variables

      +

      38.3.3 Global variables

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

      37.3.4 Constants and enums

      +

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

      -

      37.3.5 Pointers

      +

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

      -

      37.3.6 Structures

      +

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

      -

      37.3.7 C++ classes

      +

      38.3.7 C++ classes

      @@ -1318,7 +1319,7 @@ In Tcl, the static member is accessed as follows: -

      37.3.8 C++ inheritance

      +

      38.3.8 C++ inheritance

      @@ -1367,7 +1368,7 @@ For instance: It is safe to use multiple inheritance with SWIG.

      -

      37.3.9 Pointers, references, values, and arrays

      +

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

      -

      37.3.10 C++ overloaded functions

      +

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

      -

      37.3.11 C++ operators

      +

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

      -

      37.3.12 C++ namespaces

      +

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

      -

      37.3.13 C++ templates

      +

      38.3.13 C++ templates

      @@ -1762,7 +1763,7 @@ More details can be found in the SWIG and C++ -

      37.3.14 C++ Smart Pointers

      +

      38.3.14 C++ Smart Pointers

      @@ -1846,7 +1847,7 @@ simply use the __deref__() method. For example: -

      37.4 Further details on the Tcl class interface

      +

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

      -

      37.4.1 Proxy classes

      +

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

      -

      37.4.2 Memory management

      +

      38.4.2 Memory management

      @@ -2112,7 +2113,7 @@ typemaps--an advanced topic discussed later.

      -

      37.5 Input and output parameters

      +

      38.5 Input and output parameters

      @@ -2300,7 +2301,7 @@ set c [lindex $dim 1] -

      37.6 Exception handling

      +

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

      -

      37.7 Typemaps

      +

      38.7 Typemaps

      @@ -2451,7 +2452,7 @@ Typemaps are only used if you want to change some aspect of the primitive C-Tcl interface.

      -

      37.7.1 What is a typemap?

      +

      38.7.1 What is a typemap?

      @@ -2568,7 +2569,7 @@ parameter is omitted): -

      37.7.2 Tcl typemaps

      +

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

      -

      37.7.3 Typemap variables

      +

      38.7.3 Typemap variables

      @@ -2777,7 +2778,7 @@ properly assigned. The Tcl name of the wrapper function being created. -

      37.7.4 Converting a Tcl list to a char **

      +

      38.7.4 Converting a Tcl list to a char **

      @@ -2839,7 +2840,7 @@ argv[2] = Larry 3 -

      37.7.5 Returning values in arguments

      +

      38.7.5 Returning values in arguments

      @@ -2881,7 +2882,7 @@ result, a Tcl function using these typemaps will work like this : % -

      37.7.6 Useful functions

      +

      38.7.6 Useful functions

      @@ -2958,7 +2959,7 @@ int Tcl_IsShared(Tcl_Obj *obj); -

      37.7.7 Standard typemaps

      +

      38.7.7 Standard typemaps

      @@ -3042,7 +3043,7 @@ work) -

      37.7.8 Pointer handling

      +

      38.7.8 Pointer handling

      @@ -3118,7 +3119,7 @@ For example: -

      37.8 Turning a SWIG module into a Tcl Package.

      +

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

      -

      37.9 Building new kinds of Tcl interfaces (in Tcl)

      +

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

      -

      37.9.1 Proxy classes

      +

      38.9.1 Proxy classes

      @@ -3410,7 +3411,7 @@ short, but clever Tcl script can be combined with SWIG to do many interesting things.

      -

      37.10 Tcl/Tk Stubs

      +

      38.10 Tcl/Tk Stubs

      diff --git a/Doc/Manual/Typemaps.html b/Doc/Manual/Typemaps.html index b3b0bc7a9..cba524149 100644 --- a/Doc/Manual/Typemaps.html +++ b/Doc/Manual/Typemaps.html @@ -6,7 +6,7 @@ -

      10 Typemaps

      +

      11 Typemaps

        @@ -95,7 +95,7 @@ -

        10.1 Introduction

        +

        11.1 Introduction

        @@ -112,7 +112,7 @@ to re-read the earlier chapters if you have found your way to this chapter with only a vague idea of what SWIG already does by default.

        -

        10.1.1 Type conversion

        +

        11.1.1 Type conversion

        @@ -205,7 +205,7 @@ to read the extension documentation for your favorite language to know how it works (an exercise left to the reader).

        -

        10.1.2 Typemaps

        +

        11.1.2 Typemaps

        @@ -306,7 +306,7 @@ parts of the generated wrapper functions. Because arbitrary code can be insert possible to completely change the way in which values are converted.

        -

        10.1.3 Pattern matching

        +

        11.1.3 Pattern matching

        @@ -408,7 +408,7 @@ In this case, a single input object is expanded into a pair of C arguments. Thi provides a hint to the unusual variable naming scheme involving $1, $2, and so forth.

        -

        10.1.4 Reusing typemaps

        +

        11.1.4 Reusing typemaps

        @@ -464,7 +464,7 @@ typedef int size_t; then SWIG already knows that the int typemaps apply. You don't have to do anything.

        -

        10.1.5 What can be done with typemaps?

        +

        11.1.5 What can be done with typemaps?

        @@ -576,7 +576,7 @@ typemaps that expand upon this list. For example, the Java module defines a var aspects of the Java bindings. Consult language specific documentation for further details.

        -

        10.1.6 What can't be done with typemaps?

        +

        11.1.6 What can't be done with typemaps?

        @@ -639,7 +639,7 @@ void wrap_foo(char *s, int x) {

      -

      10.1.7 Similarities to Aspect Oriented Programming

      +

      11.1.7 Similarities to Aspect Oriented Programming

      @@ -657,7 +657,7 @@ SWIG can also be viewed as has having a second set of aspects based around %exception are also cross-cutting concerns as they encapsulate code that can be used to add logging or exception handling to any function.

      -

      10.1.8 The rest of this chapter

      +

      11.1.8 The rest of this chapter

      @@ -677,14 +677,14 @@ of "The C Programming Language" by Kernighan and Ritchie or "The C++ Programming Language" by Stroustrup before going any further.

      -

      10.2 Typemap specifications

      +

      11.2 Typemap specifications

      This section describes the behavior of the %typemap directive itself.

      -

      10.2.1 Defining a typemap

      +

      11.2.1 Defining a typemap

      @@ -773,7 +773,7 @@ Here are some examples of valid typemap specifications: } /* Typemap with modifiers */ -%typemap(in,doc="integer") int "$1 = gh_scm2int($input);"; +%typemap(in,doc="integer") int "$1 = scm_to_int($input);"; /* Typemap applied to patterns of multiple arguments */ %typemap(in) (char *str, int len), @@ -797,7 +797,7 @@ Admittedly, it's not the most readable syntax at first glance. However, the pur individual pieces will become clear.

      -

      10.2.2 Typemap scope

      +

      11.2.2 Typemap scope

      @@ -847,7 +847,7 @@ class Foo { -

      10.2.3 Copying a typemap

      +

      11.2.3 Copying a typemap

      @@ -905,7 +905,7 @@ The patterns for %apply follow the same rules as for %typemap. -

      10.2.4 Deleting a typemap

      +

      11.2.4 Deleting a typemap

      @@ -938,7 +938,7 @@ For example: after the clear operation.

      -

      10.2.5 Placement of typemaps

      +

      11.2.5 Placement of typemaps

      @@ -1018,7 +1018,7 @@ It should be noted that for scoping to work, SWIG has to know that stringclass string.

      -

      10.3 Pattern matching rules

      +

      11.3 Pattern matching rules

      @@ -1026,7 +1026,7 @@ The section describes the pattern matching rules by which C/C++ datatypes are as The matching rules can be observed in practice by using the debugging options also described.

      -

      10.3.1 Basic matching rules

      +

      11.3.1 Basic matching rules

      @@ -1125,7 +1125,7 @@ void F(int x[1000]); // int [ANY] rule (typemap 5) stripped all qualifiers in one step.

      -

      10.3.2 Typedef reductions matching

      +

      11.3.2 Typedef reductions matching

      @@ -1300,7 +1300,7 @@ void go(Struct aStruct); -

      10.3.3 Default typemap matching rules

      +

      11.3.3 Default typemap matching rules

      @@ -1438,7 +1438,7 @@ Finally the best way to view the typemap matching rules in action is via the -

      10.3.4 Multi-arguments typemaps

      +

      11.3.4 Multi-arguments typemaps

      @@ -1468,7 +1468,7 @@ but all subsequent arguments must match exactly.

      -

      10.3.5 Matching rules compared to C++ templates

      +

      11.3.5 Matching rules compared to C++ templates

      @@ -1627,7 +1627,7 @@ are similar to those for specialized template handling.

      -

      10.3.6 Debugging typemap pattern matching

      +

      11.3.6 Debugging typemap pattern matching

      @@ -1840,7 +1840,7 @@ Also the types may be displayed slightly differently - char const * and

    -

    10.4 Code generation rules

    +

    11.4 Code generation rules

    @@ -1848,7 +1848,7 @@ This section describes rules by which typemap code is inserted into the generated wrapper code.

    -

    10.4.1 Scope

    +

    11.4.1 Scope

    @@ -1926,7 +1926,7 @@ a block scope when it is emitted. This sometimes results in a less complicated Note that only the third of the three typemaps have the typemap code passed through the SWIG preprocessor.

    -

    10.4.2 Declaring new local variables

    +

    11.4.2 Declaring new local variables

    @@ -2077,7 +2077,7 @@ each type must have its own local variable declaration. -

    10.4.3 Special variables

    +

    11.4.3 Special variables

    @@ -2329,7 +2329,7 @@ Another approach, which only works for arrays is to use the $1_basetype -

    10.4.4 Special variable macros

    +

    11.4.4 Special variable macros

    @@ -2341,7 +2341,7 @@ it is done during the SWIG parsing/compilation stages. The following special variable macros are available across all language modules.

    -

    10.4.4.1 $descriptor(type)

    +

    11.4.4.1 $descriptor(type)

    @@ -2352,7 +2352,7 @@ For example, $descriptor(std::vector<int> *) will expand into Run-time type checker usage section.

    -

    10.4.4.2 $typemap(method, typepattern)

    +

    11.4.4.2 $typemap(method, typepattern)

    @@ -2409,7 +2409,7 @@ The result is the following expansion -

    10.5 Common typemap methods

    +

    11.5 Common typemap methods

    @@ -2417,7 +2417,7 @@ The set of typemaps recognized by a language module may vary. However, the following typemap methods are nearly universal:

    -

    10.5.1 "in" typemap

    +

    11.5.1 "in" typemap

    @@ -2477,7 +2477,7 @@ Usually numinputs is not specified, whereupon the default value is 1, t is the same as the old "ignore" typemap.

    -

    10.5.2 "typecheck" typemap

    +

    11.5.2 "typecheck" typemap

    @@ -2503,7 +2503,7 @@ If you define new "in" typemaps and your program uses overloaded method "typecheck" typemaps. More details about this follow in the Typemaps and overloading section.

    -

    10.5.3 "out" typemap

    +

    11.5.3 "out" typemap

    @@ -2534,7 +2534,7 @@ $symname - Name of function/method being wrapped The "out" typemap supports an optional attribute flag called "optimal". This is for code optimisation and is detailed in the Optimal code generation when returning by value section.

    -

    10.5.4 "arginit" typemap

    +

    11.5.4 "arginit" typemap

    @@ -2553,7 +2553,7 @@ For example: -

    10.5.5 "default" typemap

    +

    11.5.5 "default" typemap

    @@ -2586,7 +2586,7 @@ See the Default/optional arguments sec for further information on default argument wrapping.

    -

    10.5.6 "check" typemap

    +

    11.5.6 "check" typemap

    @@ -2605,7 +2605,7 @@ converted. For example: -

    10.5.7 "argout" typemap

    +

    11.5.7 "argout" typemap

    @@ -2651,7 +2651,7 @@ return values are often appended to return value of the function. See the typemaps.i library file for examples.

    -

    10.5.8 "freearg" typemap

    +

    11.5.8 "freearg" typemap

    @@ -2684,7 +2684,7 @@ be used in other typemaps whenever a wrapper function needs to abort prematurely.

    -

    10.5.9 "newfree" typemap

    +

    11.5.9 "newfree" typemap

    @@ -2713,7 +2713,7 @@ string *foo(); See Object ownership and %newobject for further details.

    -

    10.5.10 "memberin" typemap

    +

    11.5.10 "memberin" typemap

    @@ -2735,7 +2735,7 @@ It is rarely necessary to write "memberin" typemaps---SWIG already provides a default implementation for arrays, strings, and other objects.

    -

    10.5.11 "varin" typemap

    +

    11.5.11 "varin" typemap

    @@ -2743,7 +2743,7 @@ The "varin" typemap is used to convert objects in the target language to C for t purposes of assigning to a C/C++ global variable. This is implementation specific.

    -

    10.5.12 "varout" typemap

    +

    11.5.12 "varout" typemap

    @@ -2751,7 +2751,7 @@ The "varout" typemap is used to convert a C/C++ object to an object in the targe language when reading a C/C++ global variable. This is implementation specific.

    -

    10.5.13 "throws" typemap

    +

    11.5.13 "throws" typemap

    @@ -2797,7 +2797,7 @@ Note that if your methods do not have an exception specification yet they do thr For a neat way to handle these, see the Exception handling with %exception section.

    -

    10.6 Some typemap examples

    +

    11.6 Some typemap examples

    @@ -2805,7 +2805,7 @@ This section contains a few examples. Consult language module documentation for more examples.

    -

    10.6.1 Typemaps for arrays

    +

    11.6.1 Typemaps for arrays

    @@ -3064,7 +3064,7 @@ Now, you will find that member access is quite nice: useless and has since been eliminated. To return structure members, simply use the "out" typemap.

    -

    10.6.2 Implementing constraints with typemaps

    +

    11.6.2 Implementing constraints with typemaps

    @@ -3112,7 +3112,7 @@ a NULL pointer. As a result, SWIG can often prevent a potential segmentation faults or other run-time problems by raising an exception rather than blindly passing values to the underlying C/C++ program.

    -

    10.7 Typemaps for multiple target languages

    +

    11.7 Typemaps for multiple target languages

    @@ -3142,7 +3142,7 @@ The example above also shows a common approach of issuing a warning for an as ye %typemap(ruby,in) int "$1 = NUM2INT($input);".

    -

    10.8 Optimal code generation when returning by value

    +

    11.8 Optimal code generation when returning by value

    @@ -3331,7 +3331,7 @@ example.i:7: Warning 475: optimal attribute usage in the out typemap. However, it doesn't always get it right, for example when $1 is within some commented out code.

    -

    10.9 Multi-argument typemaps

    +

    11.9 Multi-argument typemaps

    @@ -3598,7 +3598,7 @@ 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 warnings

    +

    11.10 Typemap warnings

    @@ -3607,7 +3607,7 @@ See the information in the issuing warnings

    -

    10.11 Typemap fragments

    +

    11.11 Typemap fragments

    @@ -3860,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.11.1 Fragment type specialization

    +

    11.11.1 Fragment type specialization

    @@ -3893,7 +3893,7 @@ struct A { -

    10.11.2 Fragments and automatic typemap specialization

    +

    11.11.2 Fragments and automatic typemap specialization

    @@ -3939,7 +3939,7 @@ The interested (or very brave) reader can take a look at the fragments.swg file

    -

    10.12 The run-time type checker

    +

    11.12 The run-time type checker

    @@ -3956,7 +3956,7 @@ Requirements for the type system:

  • Store inheritance and type equivalence information and be able to correctly re-create the type pointer.
  • Share type information between modules.
  • -
  • Modules can be loaded in any order, irregardless of actual type +
  • Modules can be loaded in any order, regardless of actual type dependency.
  • Avoid the use of dynamically allocated memory, and library/system calls in general.
  • Provide a reasonably fast implementation, minimizing the lookup time for all @@ -3965,7 +3965,7 @@ language modules.
  • Modules can be unloaded from the type system.
  • -

    10.12.1 Implementation

    +

    11.12.1 Implementation

    @@ -4151,7 +4151,7 @@ structures rather than creating new ones. These swig_module_info structures are chained together in a circularly linked list.

    -

    10.12.2 Usage

    +

    11.12.2 Usage

    This section covers how to use these functions from typemaps. To learn how to @@ -4245,7 +4245,7 @@ probably just look at the output of SWIG to get a better sense for how types are managed.

    -

    10.13 Typemaps and overloading

    +

    11.13 Typemaps and overloading

    @@ -4556,7 +4556,7 @@ Subsequent "in" typemaps would then perform more extensive type-checking. -

    10.14 More about %apply and %clear

    +

    11.14 More about %apply and %clear

    @@ -4642,7 +4642,7 @@ example: -

    10.15 Passing data between typemaps

    +

    11.15 Passing data between typemaps

    @@ -4679,7 +4679,7 @@ sure that the typemaps sharing information have exactly the same types and names

    -

    10.16 C++ "this" pointer

    +

    11.16 C++ "this" pointer

    @@ -4739,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.17 Where to go for more information?

    +

    11.17 Where to go for more information?

    diff --git a/Doc/Manual/Varargs.html b/Doc/Manual/Varargs.html index c27db603d..dac1ad7bc 100644 --- a/Doc/Manual/Varargs.html +++ b/Doc/Manual/Varargs.html @@ -6,7 +6,7 @@ -

    13 Variable Length Arguments

    +

    14 Variable Length Arguments

      @@ -42,7 +42,7 @@ added in SWIG-1.3.12. Most other wrapper generation tools have wisely chosen to avoid this issue.

      -

      13.1 Introduction

      +

      14.1 Introduction

      @@ -139,7 +139,7 @@ List make_list(const char *s, ...) {

    -

    13.2 The Problem

    +

    14.2 The Problem

    @@ -232,7 +232,7 @@ can also support real varargs wrapping (with stack-frame manipulation) if you are willing to get hands dirty. Keep reading.

    -

    13.3 Default varargs support

    +

    14.3 Default varargs support

    @@ -301,7 +301,7 @@ Read on for further solutions.

    -

    13.4 Argument replacement using %varargs

    +

    14.4 Argument replacement using %varargs

    @@ -398,7 +398,7 @@ 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. +Note that str3 is the name of the last argument, as we have used %varargs with 3. Now execlp("a", "b", "c", "d", "e") will result in an error as one too many arguments has been passed, as now only 2 additional 'str' arguments can be passed with the 3rd one always using the specified default NULL.

    @@ -412,7 +412,7 @@ mixed argument types such as printf(). Providing general purpose wrappers to such functions presents special problems (covered shortly).

    -

    13.5 Varargs and typemaps

    +

    14.5 Varargs and typemaps

    @@ -509,10 +509,10 @@ like this:

    -%typemap(in) (...)(char *args[10]) {
    +%typemap(in) (...)(char *vargs[10]) {
       int i;
       int argc;
    -  for (i = 0; i < 10; i++) args[i] = 0;
    +  for (i = 0; i < 10; i++) vargs[i] = 0;
       argc = PyTuple_Size(varargs);
       if (argc > 10) {
         PyErr_SetString(PyExc_ValueError, "Too many arguments");
    @@ -528,7 +528,7 @@ like this:
            return NULL;
         }
         pystr = PyUnicode_AsUTF8String(pyobj);
    -    str = PyBytes_AsString(pystr);
    +    str = strdup(PyBytes_AsString(pystr));
         Py_XDECREF(pystr);
     %#else  
         if (!PyString_Check(pyobj)) {
    @@ -537,22 +537,34 @@ like this:
         }
         str = PyString_AsString(pyobj);
     %#endif
    -    args[i] = str;
    +    vargs[i] = str;
       }
    -  $1 = (void *) args;
    +  $1 = (void *)vargs;
    +}
    +
    +%typemap(freearg) (...) {
    +%#if PY_VERSION_HEX>=0x03000000
    +  int i;
    +  for (i = 0; i < 10; i++) {
    +    free(vargs$argnum[i]);
    +  }
    +%#endif
     }
     

    -In this typemap, the special variable varargs is a tuple +In the 'in' typemap, the special variable varargs is a tuple holding all of the extra arguments passed (this is specific to the Python module). The typemap then pulls this apart and sticks the values into the array of strings args. Then, the array is assigned to $1 (recall that this is the void * variable corresponding to (...)). However, this assignment is only half of the picture----clearly this alone is not enough to -make the function work. To patch everything up, you have to rewrite the +make the function work. The 'freearg' typemap cleans up memory +allocated in the 'in' typemap; this code is generated to be called +after the execlp function is called. To patch everything +up, you have to rewrite the underlying action code using the %feature directive like this:

    @@ -560,9 +572,9 @@ this:
     %feature("action") execlp {
    -   char *args = (char **) arg3;
    -   result = execlp(arg1, arg2, args[0], args[1], args[2], args[3], args[4],
    -                   args[5],args[6],args[7],args[8],args[9], NULL);
    +  char **vargs = (char **) arg3;
    +  result = execlp(arg1, arg2, vargs[0], vargs[1], vargs[2], vargs[3], vargs[4],
    +                  vargs[5], vargs[6], vargs[7], vargs[8], vargs[9], NULL);
     }
     
     int execlp(const char *path, const char *arg, ...);
    @@ -577,7 +589,7 @@ really want to elevate your guru status and increase your job
     security, continue to the next section.
     

    -

    13.6 Varargs wrapping with libffi

    +

    14.6 Varargs wrapping with libffi

    @@ -829,7 +841,7 @@ provide an argument number for the first extra argument. This can be used to in values. Please consult the chapter on each language module for more details.

    -

    13.7 Wrapping of va_list

    +

    14.7 Wrapping of va_list

    @@ -839,13 +851,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 @@ -853,7 +865,37 @@ call-stack. It's not clear that exporting a va_list would have any use or that it would work at all.

    -

    13.8 C++ Issues

    +

    +A workaround can be implemented by writing a simple varargs C wrapper and then using the techniques +discussed earlier in this chapter for varargs. Below is a simple wrapper for vprintf renamed so that +it can still be called as vprintf from your target language. The %varargs +used in the example restricts the function to taking one string argument. +

    + +
    +
    +%{
    +int vprintf(const char *fmt, va_list ap);
    +%}
    +
    +%varargs(const char *) my_vprintf;
    +%rename(vprintf) my_vprintf;
    +
    +%inline %{
    +int my_vprintf(const char *fmt, ...) {
    +  va_list ap;
    +  int result;
    +
    +  va_start(ap, fmt);
    +  result = vprintf(fmt, ap);
    +  va_end(ap);
    +  return result;
    +}
    +%}
    +
    +
    + +

    14.8 C++ Issues

    @@ -922,7 +964,7 @@ design or to provide an alternative interface using a helper function than it is fully general wrapper to a varargs C++ member function.

    -

    13.9 Discussion

    +

    14.9 Discussion

    diff --git a/Doc/Manual/Warnings.html b/Doc/Manual/Warnings.html index 2a3ce560d..99b89c425 100644 --- a/Doc/Manual/Warnings.html +++ b/Doc/Manual/Warnings.html @@ -6,7 +6,7 @@ -

    14 Warning Messages

    +

    15 Warning Messages

      @@ -35,7 +35,7 @@ -

      14.1 Introduction

      +

      15.1 Introduction

      @@ -55,7 +55,7 @@ where the generated wrapper code will probably compile, but it may not work like you expect.

      -

      14.2 Warning message suppression

      +

      15.2 Warning message suppression

      @@ -147,7 +147,7 @@ your interface. Ignore the warning messages at your own peril.

      -

      14.3 Enabling extra warnings

      +

      15.3 Enabling extra warnings

      @@ -220,7 +220,7 @@ that is, any warnings suppressed or added in %warnfilter, #pragma S or the -w option.

      -

      14.4 Issuing a warning message

      +

      15.4 Issuing a warning message

      @@ -274,7 +274,7 @@ example.i:24: Warning 901: You are really going to regret this usage of blah * s

    -

    14.5 Symbolic symbols

    +

    15.5 Symbolic symbols

    @@ -309,7 +309,7 @@ or -

    14.6 Commentary

    +

    15.6 Commentary

    @@ -326,7 +326,7 @@ no obvious recovery. There is no mechanism for suppressing error messages.

    -

    14.7 Warnings as errors

    +

    15.7 Warnings as errors

    @@ -335,7 +335,7 @@ option. This will cause SWIG to exit with a non successful exit code if a warning is encountered.

    -

    14.8 Message output format

    +

    15.8 Message output format

    @@ -354,10 +354,10 @@ $ swig -python -Fmicrosoft example.i example.i(4) : Syntax error in input. -

    14.9 Warning number reference

    +

    15.9 Warning number reference

    -

    14.9.1 Deprecated features (100-199)

    +

    15.9.1 Deprecated features (100-199)

      @@ -382,9 +382,10 @@ example.i(4) : Syntax error in input.
    • 119. Deprecated %typemap(ignore).
    • 120. Deprecated command line option (-runtime, -noruntime).
    • 121. Deprecated %name directive. +
    • 126. The 'nestedworkaround' feature is deprecated.
    -

    14.9.2 Preprocessor (200-299)

    +

    15.9.2 Preprocessor (200-299)

      @@ -396,7 +397,7 @@ example.i(4) : Syntax error in input.
    • 206. Unexpected tokens after #directive directive.
    -

    14.9.3 C/C++ Parser (300-399)

    +

    15.9.3 C/C++ Parser (300-399)

      @@ -423,7 +424,8 @@ example.i(4) : Syntax error in input.
    • 322. Redundant redeclaration of 'name'.
    • 323. Recursive scope inheritance of 'name'.
    • 324. Named nested template instantiations not supported. Processing as if no name was given to %template(). -
    • 325. Nested class not currently supported (name ignored). +
    • 325. Nested kind not currently supported (name ignored). +
    • 326. Deprecated %extend name used - the kind name 'name' should be used instead of the typedef name 'name'.
    • 350. operator new ignored.
    • 351. operator delete ignored.
    • 352. operator+ ignored. @@ -472,7 +474,7 @@ example.i(4) : Syntax error in input.
    • 395. operator delete[] ignored.
    -

    14.9.4 Types and typemaps (400-499)

    +

    15.9.4 Types and typemaps (400-499)

      @@ -497,11 +499,13 @@ example.i(4) : Syntax error in input.
    • 471. Unable to use return type type in director method
    • 474. Method method usage of the optimal attribute ignored in the out typemap as the following cannot be used to generate optimal code: code
    • 475. Multiple calls to method might be generated due to optimal attribute usage in the out typemap. +
    • 476. Initialization using std::initializer_list. +
    • 477. No directorthrows typemap defined for type
    -

    14.9.5 Code generation (500-599)

    +

    15.9.5 Code generation (500-599)

      @@ -526,9 +530,11 @@ example.i(4) : Syntax error in input.
    • 519. %template() contains no name. Template method ignored: declaration
    • 520. Base/Derived class 'classname1' of 'classname2' is not similarly marked as a smart pointer.
    • 521. Illegal destructor name name. Ignored. +
    • 522. Use of an illegal constructor name 'name' in %extend is deprecated, the constructor name should be 'name'. +
    • 523. Use of an illegal destructor name 'name' in %extend is deprecated, the destructor name should be 'name'.
    -

    14.9.6 Language module specific (700-899)

    +

    15.9.6 Language module specific (700-899)

      @@ -551,6 +557,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).
      @@ -577,14 +585,14 @@ example.i(4) : Syntax error in input.
    • 871. Unrecognized pragma pragma. (Php).
    -

    14.9.7 User defined (900-999)

    +

    15.9.7 User defined (900-999)

    These numbers can be used by your own application.

    -

    14.10 History

    +

    15.10 History

    diff --git a/Doc/Manual/Windows.html b/Doc/Manual/Windows.html index 6349f355a..0685242ba 100644 --- a/Doc/Manual/Windows.html +++ b/Doc/Manual/Windows.html @@ -79,8 +79,8 @@ If you want to build your own swig.exe have a look at examples using Cygwin. @@ -147,7 +147,7 @@ PERL5_LIB: D:\nsPerl5.004_04\lib\CORE\perl.lib

    -PYTHON_INCLUDE : Set this to the directory that contains python.h
    +PYTHON_INCLUDE : Set this to the directory that contains Python.h
    PYTHON_LIB : Set this to the python library including path for linking

    Example using Python 2.1.1:
    @@ -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,15 +300,19 @@ 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.
  • diff --git a/Doc/Manual/chapters b/Doc/Manual/chapters index a3200ff52..9c376b636 100644 --- a/Doc/Manual/chapters +++ b/Doc/Manual/chapters @@ -4,6 +4,7 @@ Windows.html Scripting.html SWIG.html SWIGPlus.html +CPlusPlus11.html Preprocessor.html Library.html Arguments.html diff --git a/Doc/Manual/index.html b/Doc/Manual/index.html index 30c69578f..fbe105a7e 100644 --- a/Doc/Manual/index.html +++ b/Doc/Manual/index.html @@ -1,10 +1,10 @@ -SWIG-2.0 Documentation +SWIG-3.0 Documentation -

    SWIG-2.0 Documentation

    +

    SWIG-3.0 Documentation

    The SWIG documentation is available in one of the following formats.