diff --git a/.gitignore b/.gitignore index e94087e29..5df510547 100644 --- a/.gitignore +++ b/.gitignore @@ -66,6 +66,7 @@ CCache/ccache_swig_config.h CCache/config.h CCache/config.log CCache/config.status +CCache/config_win32.h Examples/Makefile Examples/d/example.mk Examples/guile/Makefile @@ -85,6 +86,8 @@ swig.spec # Build Artifacts .dirstamp CCache/ccache-swig +CCache/ccache-swig.1 +CCache/web/ccache-swig-man.html Lib/swigwarn.swg Source/CParse/parser.c Source/CParse/parser.h @@ -149,14 +152,29 @@ Examples/guile/*/my-guile Examples/test-suite/java/*/ Examples/java/*/*.java !Examples/java/*/runme.java +Examples/java/doxygen/javadocs # Javascript Examples/test-suite/javascript/*/ *.gyp +# OCaml +Examples/test-suite/ocaml/*.ml* +Examples/test-suite/ocaml/*.cm* +Examples/test-suite/ocaml/*_runme +!Examples/test-suite/ocaml/*runme.ml +Examples/ocaml/**/example.ml* +Examples/ocaml/**/runme +Examples/ocaml/**/runme_top +Examples/ocaml/**/*.cm* +Examples/ocaml/**/swig.ml* +Examples/ocaml/**/swigp4.ml + # Octave swigexample*.oct Examples/test-suite/octave/*.oct +Examples/test-suite/octave/octheaders.hpp +Examples/test-suite/octave/octheaders.hpp.gch # Perl5 Examples/test-suite/perl5/*.pm @@ -177,11 +195,16 @@ Examples/php/*/example.php /__pycache__/ Examples/test-suite/python/*.py !Examples/test-suite/python/*runme.py -Examples/python/*/example.py Examples/python/**/bar.py Examples/python/**/base.py +Examples/python/**/example.py Examples/python/**/foo.py +Examples/python/**/robin.py +Examples/python/**/runme3.py Examples/python/**/spam.py +Examples/python/import_packages/module_is_init/pkg1/__init__.py +Examples/python/import_packages/namespace_pkg/path4.zip +Examples/python/doxygen/example.html # R Examples/test-suite/r/*.R diff --git a/.travis.yml b/.travis.yml index d9dc92312..3ed261b6e 100644 --- a/.travis.yml +++ b/.travis.yml @@ -4,307 +4,454 @@ matrix: - compiler: clang os: linux env: SWIGLANG= - sudo: required - dist: trusty + dist: xenial + - compiler: clang + os: linux + env: SWIGLANG= BUILDSYSTEM=cmake + dist: xenial - compiler: gcc os: linux env: SWIGLANG= + dist: xenial - compiler: gcc os: linux - env: SWIGLANG= - sudo: required - dist: trusty + env: SWIGLANG= BUILDSYSTEM=cmake + dist: xenial - os: linux - env: SWIGLANG= SWIG_CC=gcc-5 SWIG_CXX=g++-5 CPP11=1 - sudo: required - dist: trusty + env: SWIGLANG= GCC=4.4 + dist: xenial - os: linux - env: SWIGLANG= SWIG_CC=gcc-6 SWIG_CXX=g++-6 - sudo: required - dist: trusty + env: SWIGLANG= GCC=4.6 + dist: xenial + - os: linux + env: SWIGLANG= GCC=4.7 + dist: xenial + - os: linux + env: SWIGLANG= GCC=4.8 + dist: xenial + - os: linux + env: SWIGLANG= GCC=4.9 + dist: xenial + - os: linux + env: SWIGLANG= GCC=6 + dist: xenial + - os: linux + env: SWIGLANG= GCC=7 + dist: xenial + - os: linux + env: SWIGLANG= GCC=8 + dist: xenial + - os: linux + env: SWIGLANG= GCC=9 + dist: xenial - compiler: gcc os: linux env: SWIGLANG=csharp - sudo: required - dist: trusty + dist: xenial - compiler: gcc os: linux - env: SWIGLANG=d - sudo: required - dist: trusty + env: SWIGLANG=d VER=2.066.0 + dist: xenial - compiler: gcc os: linux - env: SWIGLANG=go - sudo: required - dist: trusty + env: SWIGLANG=d VER=2.086.1 + dist: xenial - compiler: gcc os: linux - env: SWIGLANG=go VER=1.5 - sudo: required - dist: trusty + env: SWIGLANG=go VER=1.3 + dist: xenial + - compiler: gcc + os: linux + env: SWIGLANG=go VER=1.8 + dist: xenial + - compiler: gcc + os: linux + env: SWIGLANG=go VER=1.12 + dist: xenial - compiler: gcc os: linux env: SWIGLANG=guile - sudo: required - dist: trusty + dist: xenial - compiler: gcc os: linux env: SWIGLANG=java - sudo: required - dist: trusty + dist: xenial - compiler: gcc os: linux - env: SWIGLANG=javascript ENGINE=node + env: SWIGLANG=javascript ENGINE=node VER=6 CPP11=1 + dist: xenial + - compiler: gcc + os: linux + env: SWIGLANG=javascript ENGINE=node VER=8 CPP11=1 + dist: xenial + - compiler: gcc + os: linux + env: SWIGLANG=javascript ENGINE=node VER=10 CPP11=1 + dist: xenial + - compiler: gcc + os: linux + env: SWIGLANG=javascript ENGINE=node VER=12 CPP11=1 + sudo: required + dist: xenial - compiler: gcc os: linux env: SWIGLANG=javascript ENGINE=jsc - sudo: required - dist: trusty + dist: xenial - compiler: gcc os: linux env: SWIGLANG=javascript ENGINE=v8 - sudo: required - dist: trusty + dist: xenial - compiler: gcc os: linux env: SWIGLANG=lua - sudo: required - dist: trusty + dist: xenial - compiler: gcc os: linux env: SWIGLANG=lua VER=5.3 - sudo: required - dist: trusty + dist: xenial - compiler: gcc os: linux - env: SWIGLANG=octave SWIGJOBS=-j2 # 3.2 - - compiler: gcc - os: linux - env: SWIGLANG=octave SWIGJOBS=-j2 VER=3.8 - - compiler: gcc - os: linux - env: SWIGLANG=octave SWIGJOBS=-j2 VER=4.0 - - compiler: gcc - os: linux - env: SWIGLANG=perl5 - sudo: required - dist: trusty - - compiler: gcc - os: linux - env: SWIGLANG=php5 - sudo: required - dist: trusty - - compiler: gcc - os: linux - env: SWIGLANG=php VER=7.0 - sudo: required - dist: trusty - - compiler: gcc - os: linux - env: SWIGLANG=php VER=7.1 - sudo: required - dist: trusty - - compiler: gcc - os: linux - env: SWIGLANG=python VER=2.4 - sudo: required - dist: trusty - - compiler: gcc - os: linux - env: SWIGLANG=python VER=2.5 - sudo: required - dist: trusty - - compiler: gcc - os: linux - env: SWIGLANG=python VER=2.6 - sudo: required - dist: trusty - - compiler: gcc - os: linux - env: SWIGLANG=python # 2.7 - sudo: required - dist: trusty - - compiler: gcc - os: linux - env: SWIGLANG=python PY3=3 VER=3.2 - sudo: required - dist: trusty - - compiler: gcc - os: linux - env: SWIGLANG=python PY3=3 VER=3.3 - sudo: required - dist: trusty - - compiler: gcc - os: linux - env: SWIGLANG=python PY3=3 VER=3.4 - sudo: required - dist: trusty - - compiler: gcc - os: linux - env: SWIGLANG=python PY3=3 VER=3.5 - sudo: required - dist: trusty - - compiler: gcc - os: linux - env: SWIGLANG=python SWIG_FEATURES=-builtin VER=2.6 - sudo: required - dist: trusty - - compiler: gcc - os: linux - env: SWIGLANG=python SWIG_FEATURES=-builtin - sudo: required - dist: trusty - - compiler: gcc - os: linux - env: SWIGLANG=python SWIG_FEATURES=-builtin PY3=3 VER=3.4 - sudo: required - dist: trusty - - compiler: gcc - os: linux - env: SWIGLANG=python SWIG_FEATURES=-builtin PY3=3 VER=3.5 - sudo: required - dist: trusty - - compiler: gcc - os: linux - env: SWIGLANG=python SWIG_FEATURES=-builtin PY3=3 VER=3.5 SWIGOPTPY3= - sudo: required - dist: trusty - - compiler: gcc - os: linux - env: SWIGLANG=python SWIG_FEATURES=-O - sudo: required - dist: trusty - - compiler: gcc - os: linux - env: SWIGLANG=python SWIG_FEATURES=-classic - sudo: required - dist: trusty - - compiler: gcc - os: linux - env: SWIGLANG=r - sudo: required - dist: trusty - - compiler: gcc - os: linux - env: SWIGLANG=ruby VER=1.9.3 - sudo: required - dist: trusty - - compiler: gcc - os: linux - env: SWIGLANG=ruby VER=2.0.0 - sudo: required - dist: trusty - - compiler: gcc - os: linux - env: SWIGLANG=ruby VER=2.3.0 - sudo: required - dist: trusty - - compiler: gcc - os: linux - env: SWIGLANG=scilab - sudo: required - dist: trusty - - compiler: gcc - os: linux - env: SWIGLANG=tcl - sudo: required - dist: trusty - - os: linux - env: SWIGLANG=csharp SWIG_CC=gcc-5 SWIG_CXX=g++-5 CPP11=1 - sudo: required - dist: trusty - - os: linux - env: SWIGLANG=java SWIG_CC=gcc-5 SWIG_CXX=g++-5 CPP11=1 - sudo: required - dist: trusty - - os: linux - env: SWIGLANG=python SWIG_CC=gcc-5 SWIG_CXX=g++-5 CPP11=1 - sudo: required - dist: trusty - - os: linux - env: SWIGLANG=csharp SWIG_CC=gcc-6 SWIG_CXX=g++-6 CPP14=1 - sudo: required - dist: trusty - - os: linux - env: SWIGLANG=java SWIG_CC=gcc-6 SWIG_CXX=g++-6 CPP14=1 - sudo: required - dist: trusty - - os: linux - env: SWIGLANG=python SWIG_CC=gcc-6 SWIG_CXX=g++-6 CPP14=1 - sudo: required - dist: trusty - - compiler: gcc - os: osx - env: SWIGLANG= - - compiler: clang - os: osx - env: SWIGLANG= - - compiler: clang - os: osx - env: SWIGLANG=csharp - - compiler: clang - os: osx - env: SWIGLANG=go - - compiler: clang - os: osx - env: SWIGLANG=guile - - compiler: clang - os: osx - env: SWIGLANG=java - - compiler: clang - os: osx - env: SWIGLANG=lua - - compiler: clang - os: osx - env: SWIGLANG=perl5 - - compiler: clang - os: osx - env: SWIGLANG=php5 - - compiler: clang - os: osx - env: SWIGLANG=python - - compiler: clang - os: osx - env: SWIGLANG=python PY3=3 - - compiler: clang - os: osx - env: SWIGLANG=ruby - - compiler: clang - os: osx - env: SWIGLANG=tcl - - allow_failures: - # Lots of failing tests currently + env: SWIGLANG=mzscheme + dist: xenial - compiler: gcc os: linux env: SWIGLANG=ocaml - sudo: required - dist: trusty - # Not quite working yet + dist: xenial + - compiler: gcc + os: linux + env: SWIGLANG=octave SWIGJOBS=-j2 + dist: xenial # Octave v4.0.0 + - compiler: gcc + os: linux + env: SWIGLANG=octave SWIGJOBS=-j2 CPP11=1 + dist: bionic # Octave v4.2.2 + - compiler: gcc + os: linux + env: SWIGLANG=perl5 + dist: xenial + - compiler: gcc + os: linux + env: SWIGLANG=php VER=7.0 + dist: xenial + - compiler: gcc + os: linux + env: SWIGLANG=php VER=7.1 + dist: xenial + - compiler: gcc + os: linux + env: SWIGLANG=php VER=7.2 + dist: xenial + - compiler: gcc + os: linux + env: SWIGLANG=php VER=7.3 + dist: xenial + - compiler: gcc + os: linux + env: SWIGLANG=python # 2.7 + dist: xenial + - compiler: gcc + os: linux + env: SWIGLANG=python PY3=3 VER=3.2 + dist: xenial + - compiler: gcc + os: linux + env: SWIGLANG=python PY3=3 VER=3.3 + dist: xenial + - compiler: gcc + os: linux + env: SWIGLANG=python PY3=3 VER=3.4 + dist: xenial + - compiler: gcc + os: linux + env: SWIGLANG=python PY3=3 VER=3.5 + dist: xenial + - compiler: gcc + os: linux + env: SWIGLANG=python PY3=3 VER=3.6 + dist: xenial + - compiler: gcc + os: linux + env: SWIGLANG=python PY3=3 VER=3.7 + dist: xenial + - compiler: gcc + os: linux + env: SWIGLANG=python PY3=3 VER=3.8 + dist: xenial + - compiler: gcc + os: linux + env: SWIGLANG=python PY3=3 VER=3.9 + dist: xenial + - compiler: gcc + os: linux + env: SWIGLANG=python SWIG_FEATURES=-builtin + dist: xenial + - compiler: gcc + os: linux + env: SWIGLANG=python SWIG_FEATURES="-builtin -O" + dist: xenial + - os: linux + env: SWIGLANG=python SWIG_FEATURES=-builtin GCC=6 CPP11=1 + dist: xenial + - os: linux + env: SWIGLANG=python SWIG_FEATURES=-builtin GCC=6 CPP11=1 PY3=3 VER=3.9 + dist: xenial + - compiler: gcc + os: linux + env: SWIGLANG=python SWIG_FEATURES=-builtin PY3=3 VER=3.4 + dist: xenial + - compiler: gcc + os: linux + env: SWIGLANG=python SWIG_FEATURES=-builtin PY3=3 VER=3.5 + dist: xenial + - compiler: gcc + os: linux + env: SWIGLANG=python SWIG_FEATURES=-builtin PY3=3 VER=3.7 + dist: xenial + - compiler: gcc + os: linux + env: SWIGLANG=python SWIG_FEATURES=-builtin PY3=3 VER=3.8 + dist: xenial + - compiler: gcc + os: linux + env: SWIGLANG=python SWIG_FEATURES=-builtin PY3=3 VER=3.9 + dist: xenial + - compiler: gcc + os: linux + env: SWIGLANG=python SWIG_FEATURES="-builtin -O" PY3=3 VER=3.9 + dist: xenial + - compiler: gcc + os: linux + env: SWIGLANG=python SWIG_FEATURES=-builtin PY3=3 VER=3.9 SWIGOPTPY3= + dist: xenial - compiler: gcc os: linux env: SWIGLANG=python SWIG_FEATURES=-O - sudo: required - dist: trusty + dist: xenial + - compiler: gcc + os: linux + env: SWIGLANG=python SWIG_FEATURES=-O PY3=3 VER=3.9 + dist: xenial + - compiler: gcc + os: linux + env: SWIGLANG=r + dist: xenial + - compiler: gcc + os: linux + env: SWIGLANG=ruby VER=1.9 + dist: xenial + - compiler: gcc + os: linux + env: SWIGLANG=ruby VER=2.0 + dist: xenial + - compiler: gcc + os: linux + env: SWIGLANG=ruby VER=2.1 + dist: xenial + - compiler: gcc + os: linux + env: SWIGLANG=ruby VER=2.2 + dist: xenial + - compiler: gcc + os: linux + env: SWIGLANG=ruby VER=2.3 + dist: xenial + - compiler: gcc + os: linux + env: SWIGLANG=ruby VER=2.4 + dist: xenial + - compiler: gcc + os: linux + env: SWIGLANG=ruby VER=2.5 + dist: xenial + - compiler: gcc + os: linux + env: SWIGLANG=ruby VER=2.6 + dist: xenial + - compiler: gcc + os: linux + env: SWIGLANG=ruby VER=2.7 + dist: xenial + - compiler: gcc + os: linux + env: SWIGLANG=scilab + dist: xenial + - compiler: gcc + os: linux + env: SWIGLANG=tcl + dist: xenial + - os: linux + env: SWIGLANG=csharp CPP11=1 + dist: xenial + - os: linux + env: SWIGLANG=go VER=1.6 CPP11=1 + dist: xenial + - os: linux + env: SWIGLANG=java CPP11=1 + dist: xenial + - os: linux + env: SWIGLANG=python CPP11=1 + dist: xenial + - os: linux + env: SWIGLANG=r CPP11=1 # Note: making 'R CMD SHLIB' use a different compiler is non-trivial + dist: xenial + - os: linux + env: SWIGLANG=ruby CPP11=1 + dist: xenial + - os: linux + env: SWIGLANG=tcl CPP11=1 + dist: xenial + - os: linux + env: SWIGLANG=csharp GCC=6 CPP14=1 + dist: xenial + - os: linux + env: SWIGLANG=go VER=1.6 GCC=6 CPP14=1 + dist: xenial + - os: linux + env: SWIGLANG=java GCC=6 CPP14=1 + dist: xenial + - os: linux + env: SWIGLANG=python GCC=6 CPP14=1 + dist: xenial + - os: linux + env: SWIGLANG=ruby GCC=6 CPP14=1 + dist: xenial + - os: linux + env: SWIGLANG=tcl GCC=6 CPP14=1 + dist: xenial + - os: linux + env: SWIGLANG=java GCC=7 CPP14=1 + dist: xenial + - os: linux + env: SWIGLANG=python GCC=7 CPP14=1 + dist: xenial + - os: linux + env: SWIGLANG=csharp GCC=8 CPP17=1 + dist: xenial + - os: linux + env: SWIGLANG=java GCC=8 CPP17=1 + dist: xenial + - os: linux + env: SWIGLANG=python GCC=8 CPP17=1 PY3=3 VER=3.9 + dist: xenial + - os: linux + env: SWIGLANG=csharp GCC=9 CPP17=1 + dist: xenial + - os: linux + env: SWIGLANG=java GCC=9 CPP17=1 + dist: xenial + - os: linux + env: SWIGLANG=python GCC=9 CPP17=1 PY3=3 VER=3.9 + dist: xenial + - os: linux + arch: s390x + env: SWIGLANG=ruby CPP11=1 + dist: xenial + - compiler: gcc + os: osx + osx_image: xcode12.2 + env: SWIGLANG= + - compiler: gcc + os: osx + env: SWIGLANG= BUILDSYSTEM=cmake + - compiler: clang + os: osx + env: SWIGLANG= BUILDSYSTEM=cmake + - compiler: clang + os: osx + osx_image: xcode12.2 + env: SWIGLANG= + - compiler: clang + os: osx + osx_image: xcode12.2 + env: SWIGLANG=csharp + - compiler: clang + os: osx + osx_image: xcode12.2 + env: SWIGLANG=go + - compiler: clang + os: osx + osx_image: xcode12.2 + env: SWIGLANG=guile CSTD=c11 + - compiler: clang + os: osx + osx_image: xcode12.2 + env: SWIGLANG=java + - compiler: clang + os: osx + osx_image: xcode12.2 + env: SWIGLANG=lua +# octave-6.1 not working +# - compiler: clang +# os: osx +# osx_image: xcode12.2 +# env: SWIGLANG=octave SWIGJOBS=-j2 CPP11=1 + - compiler: clang + os: osx + osx_image: xcode12.2 + env: SWIGLANG=perl5 + - compiler: clang + os: osx + osx_image: xcode12.2 + env: SWIGLANG=python + - compiler: clang + os: osx + osx_image: xcode12.2 + env: SWIGLANG=python PY3=3 + - compiler: clang + os: osx + osx_image: xcode12.2 + env: SWIGLANG=ruby + - compiler: clang + os: osx + osx_image: xcode12.2 + env: SWIGLANG=tcl + - compiler: clang + os: osx + osx_image: xcode12.2 + env: SWIGLANG=java CPP17=1 + - compiler: clang + os: osx + osx_image: xcode12.2 + env: SWIGLANG=python PY3=3 CPP17=1 + + allow_failures: + # Newer version of D not yet working/supported + - compiler: gcc + os: linux + env: SWIGLANG=d VER=2.086.1 + dist: xenial + # seg fault in director_basic testcase + - compiler: gcc + os: linux + env: SWIGLANG=php VER=7.2 + dist: xenial + # Experimental languages + - compiler: gcc + os: linux + env: SWIGLANG=mzscheme + dist: xenial + - compiler: gcc + os: linux + env: SWIGLANG=ocaml + dist: xenial + before_install: - date -u - uname -a - - if test "$TRAVIS_OS_NAME" = "linux"; then lscpu && cat /proc/cpuinfo | grep "model name" && cat /proc/meminfo | grep MemTotal; fi + - if test "$TRAVIS_OS_NAME" = "linux"; then lscpu; grep "model name" /proc/cpuinfo || echo 'Unknown CPU model'; grep "MemTotal" /proc/meminfo || echo 'Unknown system memory amount'; fi - if test "$TRAVIS_OS_NAME" = "osx"; then sysctl -a | grep brand_string; fi - # Travis overrides CC environment with compiler predefined values - - if test -n "$SWIG_CC"; then export CC="$SWIG_CC"; fi - - if test -n "$SWIG_CXX"; then export CXX="$SWIG_CXX"; fi + # Travis overrides CC environment with compiler predefined values + - if test -n "$GCC"; then export CC="gcc-$GCC" && export CXX="g++-$GCC"; fi install: - if test "$TRAVIS_OS_NAME" = "linux"; then source Tools/travis-linux-install.sh; fi - if test "$TRAVIS_OS_NAME" = "osx"; then source Tools/travis-osx-install.sh; fi + - ls -la $(which $CC) $(which $CXX) && $CC --version && $CXX --version +script: + - if test "$BUILDSYSTEM" = "cmake"; then mkdir -p build/build && cd build/build && cmake -DCMAKE_INSTALL_PREFIX=~/.local ../.. && make install && ctest --output-on-failure -V && exit 0; fi + - echo 'Configuring...' && echo -en 'travis_fold:start:script.1\\r' - if test -n "$CPP11"; then CONFIGOPTS+=(--enable-cpp11-testing --without-maximum-compile-warnings "CXXFLAGS=-std=c++11 -Wall -Wextra" "CFLAGS=-std=c11 -Wall -Wextra") && export CSTD=c11 && export CPPSTD=c++11; fi - if test -n "$CPP14"; then CONFIGOPTS+=(--enable-cpp11-testing --without-maximum-compile-warnings "CXXFLAGS=-std=c++14 -Wall -Wextra" "CFLAGS=-std=c11 -Wall -Wextra") && export CSTD=c11 && export CPPSTD=c++14; fi - - ls -la $(which $CC) - - ls -la $(which $CXX) - - $CC --version - - $CXX --version -script: - - echo 'Configuring...' && echo -en 'travis_fold:start:script.1\\r' + - if test -n "$CPP17"; then CONFIGOPTS+=(--enable-cpp11-testing --without-maximum-compile-warnings "CXXFLAGS=-std=c++17 -Wall -Wextra" "CFLAGS=-std=c17 -Wall -Wextra") && export CSTD=c17 && export CPPSTD=c++17; fi - if test -n "$SWIGLANG"; then CONFIGOPTS+=(--without-alllang --with-$WITHLANG); fi - echo "${CONFIGOPTS[@]}" - ./autogen.sh && mkdir -p build/build && cd build/build && ../../configure "${CONFIGOPTS[@]}" @@ -324,5 +471,6 @@ script: - if test -n "$SWIGLANG"; then make $SWIGJOBS check-$SWIGLANG-examples CFLAGS="$cflags" CXXFLAGS="$cxxflags"; fi - if test -n "$SWIGLANG"; then make $SWIGJOBS check-$SWIGLANG-test-suite CFLAGS="$cflags" CXXFLAGS="$cxxflags"; fi - echo 'Cleaning...' && echo -en 'travis_fold:start:script.3\\r' - - make check-maintainer-clean && ../../configure $CONFIGOPTS + # Skip on osx as often fails with: rm: Resource temporarily unavailable + - if test "$TRAVIS_OS_NAME" != "osx"; then make check-maintainer-clean && ../../configure $CONFIGOPTS; fi - echo -en 'travis_fold:end:script.3\\r' diff --git a/ANNOUNCE b/ANNOUNCE index aa5424a1a..e50bcd463 100644 --- a/ANNOUNCE +++ b/ANNOUNCE @@ -1,8 +1,8 @@ -*** ANNOUNCE: SWIG 3.0.12 (in progress) *** +*** ANNOUNCE: SWIG 4.1.0 (in progress) *** http://www.swig.org -We're pleased to announce SWIG-3.0.12, the latest SWIG release. +We're pleased to announce SWIG-4.1.0, the latest SWIG release. What is SWIG? ============= @@ -10,13 +10,11 @@ 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 programming languages including Perl, Python, Tcl, Ruby, -PHP, C#, Go, Java, Javascript, Lua, Scheme (Guile, MzScheme, CHICKEN), -D, Ocaml, Pike, Modula-3, Octave, R, Scilab, 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. +PHP, C#, Go, Java, Javascript, Lua, Scheme (Guile, MzScheme), D, +Ocaml, Octave, R, Scilab. SWIG can also export its parse tree in +the form of XML. Major applications of SWIG include generation of +scripting language extension modules, rapid prototyping, testing, +and user interface development for large C/C++ systems. Release Notes ============= @@ -27,11 +25,11 @@ Availability ============ The release is available for download on Sourceforge at - http://prdownloads.sourceforge.net/swig/swig-3.0.12.tar.gz + http://prdownloads.sourceforge.net/swig/swig-4.1.0.tar.gz A Windows version is also available at - http://prdownloads.sourceforge.net/swig/swigwin-3.0.12.zip + http://prdownloads.sourceforge.net/swig/swigwin-4.1.0.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/Makefile.in b/CCache/Makefile.in index 67fd3f363..d1bb8c526 100644 --- a/CCache/Makefile.in +++ b/CCache/Makefile.in @@ -8,6 +8,7 @@ bindir=@bindir@ mandir=@mandir@ INSTALLCMD=@INSTALL@ PACKAGE_NAME=@PACKAGE_NAME@ +PROGRAM_NAME=@PROGRAM_NAME@ # Soft link test can be skipped on systems that don't support soft linking NOSOFTLINKSTEST= @@ -17,13 +18,10 @@ SWIG=swig SWIG_LIB=../$(srcdir)/../Lib EXEEXT=@EXEEXT@ -# Use standard autoconf approach to transform executable name using --program-prefix and --program-suffix -transform = @program_transform_name@ - LIBS= @LIBS@ OBJS= ccache.o mdfour.o hash.o execute.o util.o args.o stats.o \ cleanup.o snprintf.o unify.o -HEADERS = ccache.h mdfour.h +HEADERS = ccache.h mdfour.h config.h config_win32.h all: $(PACKAGE_NAME)$(EXEEXT) @@ -32,7 +30,7 @@ Makefile: $(srcdir)/Makefile.in ./config.status $(SHELL) ./config.status # Note that HTML documentation is actually generated and used from the main SWIG documentation Makefile -docs: $(srcdir)/$(PACKAGE_NAME).1 $(srcdir)/web/ccache-man.html +docs: $(srcdir)/$(PACKAGE_NAME).1 $(srcdir)/web/$(PACKAGE_NAME)-man.html $(PACKAGE_NAME)$(EXEEXT): $(OBJS) $(HEADERS) $(CC) $(CFLAGS) $(LDFLAGS) -o $@ $(OBJS) $(LIBS) @@ -40,40 +38,43 @@ $(PACKAGE_NAME)$(EXEEXT): $(OBJS) $(HEADERS) $(srcdir)/$(PACKAGE_NAME).1: $(srcdir)/ccache.yo -yodl2man -o $(srcdir)/$(PACKAGE_NAME).1 $(srcdir)/ccache.yo -$(srcdir)/web/ccache-man.html: $(srcdir)/ccache.yo - yodl2html -o $(srcdir)/web/ccache-man.html $(srcdir)/ccache.yo +$(srcdir)/web/$(PACKAGE_NAME)-man.html: $(srcdir)/ccache.yo + yodl2html -o $(srcdir)/web/$(PACKAGE_NAME)-man.html $(srcdir)/ccache.yo install: $(PACKAGE_NAME)$(EXEEXT) @echo "Installing $(PACKAGE_NAME)" - @echo "Installing $(DESTDIR)${bindir}/`echo $(PACKAGE_NAME) | sed '$(transform)'`$(EXEEXT)" + @echo "Installing $(DESTDIR)${bindir}/$(PROGRAM_NAME)$(EXEEXT)" ${INSTALLCMD} -d $(DESTDIR)${bindir} - ${INSTALLCMD} -m 755 $(PACKAGE_NAME)$(EXEEXT) $(DESTDIR)${bindir}/`echo $(PACKAGE_NAME) | sed '$(transform)'`$(EXEEXT) + ${INSTALLCMD} -m 755 $(PACKAGE_NAME)$(EXEEXT) $(DESTDIR)${bindir}/$(PROGRAM_NAME)$(EXEEXT) install-docs: $(srcdir)/$(PACKAGE_NAME).1 - @echo "Installing $(DESTDIR)${mandir}/man1/`echo $(PACKAGE_NAME) | sed '$(transform)'`.1" + @echo "Installing $(DESTDIR)${mandir}/man1/$(PROGRAM_NAME).1" ${INSTALLCMD} -d $(DESTDIR)${mandir}/man1 - ${INSTALLCMD} -m 644 $(srcdir)/$(PACKAGE_NAME).1 $(DESTDIR)${mandir}/man1/`echo $(PACKAGE_NAME) | sed '$(transform)'`.1 + ${INSTALLCMD} -m 644 $(srcdir)/$(PACKAGE_NAME).1 $(DESTDIR)${mandir}/man1/$(PROGRAM_NAME).1 uninstall: $(PACKAGE_NAME)$(EXEEXT) - rm -f $(DESTDIR)${bindir}/`echo $(PACKAGE_NAME) | sed '$(transform)'`$(EXEEXT) + rm -f $(DESTDIR)${bindir}/$(PROGRAM_NAME)$(EXEEXT) uninstall-docs: $(srcdir)/$(PACKAGE_NAME).1 - rm -f $(DESTDIR)${mandir}/man1/`echo $(PACKAGE_NAME) | sed '$(transform)'`.1 + rm -f $(DESTDIR)${mandir}/man1/$(PROGRAM_NAME).1 -clean: +clean: clean-docs /bin/rm -f $(OBJS) *~ $(PACKAGE_NAME)$(EXEEXT) +clean-docs: + rm -f $(srcdir)/$(PACKAGE_NAME).1 $(srcdir)/web/$(PACKAGE_NAME)-man.html + test: test.sh - SWIG_LIB='$(SWIG_LIB)' PATH=../..:$$PATH SWIG='$(SWIG)' CC='$(CC)' NOSOFTLINKSTEST='$(NOSOFTLINKSTEST)' $(srcdir)/test.sh + SWIG_LIB='$(SWIG_LIB)' PATH=../..:$$PATH SWIG='$(SWIG)' CC='$(CC)' NOSOFTLINKSTEST='$(NOSOFTLINKSTEST)' CCACHE='../$(PACKAGE_NAME)' CCACHE_PROG=$(PROGRAM_NAME) $(srcdir)/test.sh check: test distclean: clean - /bin/rm -f Makefile config.h config.sub config.log build-stamp config.status ccache_swig_config.h + /bin/rm -f Makefile config.h config.sub config.log build-stamp config.status ccache_swig_config.h config_win32.h /bin/rm -rf autom4te.cache maintainer-clean: distclean - /bin/rm -f $(srcdir)/$(PACKAGE_NAME).1 $(srcdir)/web/ccache-man.html + /bin/rm -f $(srcdir)/$(PACKAGE_NAME).1 $(srcdir)/web/$(PACKAGE_NAME)-man.html # FIXME: To fix this, test.sh needs to be able to take ccache from the diff --git a/CCache/ccache.h b/CCache/ccache.h index a79d88322..25e786496 100644 --- a/CCache/ccache.h +++ b/CCache/ccache.h @@ -6,7 +6,7 @@ #include "config.h" #else #include -#define PACKAGE_NAME "ccache-swig.exe" +#include "config_win32.h" #endif #include @@ -51,7 +51,7 @@ #define STATUS_FATAL 4 #define STATUS_NOCACHE 5 -#define MYNAME PACKAGE_NAME +#define MYNAME PROGRAM_NAME #define LIMIT_MULTIPLE 0.8 diff --git a/CCache/config_win32.h.in b/CCache/config_win32.h.in new file mode 100644 index 000000000..2d5ab97e3 --- /dev/null +++ b/CCache/config_win32.h.in @@ -0,0 +1,3 @@ +#if !defined(PROGRAM_NAME) +#define PROGRAM_NAME "@PROGRAM_NAME@.exe" +#endif diff --git a/CCache/configure.ac b/CCache/configure.ac index dfbf86dbc..e1c761860 100644 --- a/CCache/configure.ac +++ b/CCache/configure.ac @@ -7,6 +7,7 @@ AC_CONFIG_SRCDIR([ccache.h]) AC_MSG_NOTICE([Configuring ccache]) AC_CONFIG_HEADER(config.h) +AC_CONFIG_FILES([config_win32.h]) dnl Checks for programs. AC_PROG_CC @@ -14,6 +15,20 @@ AC_PROG_CPP AC_PROG_INSTALL AC_ARG_PROGRAM # for program_transform_name +AC_SUBST(PROGRAM_NAME) +if test "x$program_prefix" != "xNONE" -a "x$program_prefix" != "x" +then + PROGRAM_NAME="$program_prefix$PACKAGE_NAME" +else + PROGRAM_NAME="$PACKAGE_NAME" +fi +if test "x$program_suffix" != "xNONE" -a "x$program_suffix" != "x" +then + PROGRAM_NAME="$PROGRAM_NAME$program_suffix" +fi + +AC_DEFINE_UNQUOTED(PROGRAM_NAME, "$PROGRAM_NAME", [Define my program name]) + AC_DEFINE([_GNU_SOURCE], 1, [Define _GNU_SOURCE so that we get all necessary prototypes]) diff --git a/CCache/snprintf.c b/CCache/snprintf.c index 32187c1a5..9bf8a817b 100644 --- a/CCache/snprintf.c +++ b/CCache/snprintf.c @@ -292,6 +292,7 @@ static size_t dopr(char *buffer, size_t maxlen, const char *format, va_list args break; case 'X': flags |= DP_F_UP; + /* FALLTHROUGH */ case 'x': flags |= DP_F_UNSIGNED; if (cflags == DP_C_SHORT) @@ -314,6 +315,7 @@ static size_t dopr(char *buffer, size_t maxlen, const char *format, va_list args break; case 'E': flags |= DP_F_UP; + /* FALLTHROUGH */ case 'e': if (cflags == DP_C_LDOUBLE) fvalue = va_arg (args, LDOUBLE); @@ -322,6 +324,7 @@ static size_t dopr(char *buffer, size_t maxlen, const char *format, va_list args break; case 'G': flags |= DP_F_UP; + /* FALLTHROUGH */ case 'g': if (cflags == DP_C_LDOUBLE) fvalue = va_arg (args, LDOUBLE); diff --git a/CCache/test.sh b/CCache/test.sh index 438e782cd..3c44e859c 100755 --- a/CCache/test.sh +++ b/CCache/test.sh @@ -20,7 +20,12 @@ fi PATH="`echo $PATH | \ sed -e 's!:/usr\(/local\)*/lib\([0-9]\)*/ccache\(/\)*!!g'`" -CCACHE=../ccache-swig +if test -n "$CCACHE"; then + CCACHE="$CCACHE" +else + CCACHE=../ccache-swig +fi + TESTDIR=test.$$ test_failed() { @@ -406,6 +411,10 @@ swigtests() { # main program rm -rf $TESTDIR mkdir $TESTDIR +if test -n "$CCACHE_PROG"; then + ln -s $CCACHE $TESTDIR/$CCACHE_PROG + CCACHE=./$CCACHE_PROG +fi cd $TESTDIR || exit 1 unset CCACHE_DIR @@ -442,14 +451,16 @@ swigtests if test -z "$NOSOFTLINKSTEST"; then testsuite="link" - ln -s $CCACHE $COMPILER - CCACHE_COMPILE="./$COMPILER" + compilername=`basename $COMPILER` + ln -s $CCACHE ./$compilername + CCACHE_COMPILE="./$compilername" basetests - rm "./$COMPILER" - ln -s $CCACHE $SWIG - CCACHE_COMPILE="./$SWIG" + rm "./$compilername" + compilername=`basename $SWIG` + ln -s $CCACHE ./$compilername + CCACHE_COMPILE="./$compilername" swigtests - rm "./$SWIG" + rm "./$compilername" else echo "skipping testsuite link" fi diff --git a/CHANGES b/CHANGES index 4347c126a..05834910a 100644 --- a/CHANGES +++ b/CHANGES @@ -5,6 +5,1953 @@ See the RELEASENOTES file for a summary of changes in each release. Issue # numbers mentioned below can be found on Github. For more details, add the issue number to the end of the URL: https://github.com/swig/swig/issues/ +Version 4.0.2 (8 Jun 2020) +========================== + +2020-06-07 vigsterkr + [Ruby] #1717 Nil fix mangling strings + +2020-06-07 vadz + #1748 Fix doxygen comments quoting issue + +2020-06-07 munoah + #1800 Escape spaces in file paths for dependencies (-M -MM etc) + +2020-06-06 andreas-schwab + [Ruby] #1801 Fix encoding on big endian systems when wrapping std::wstring. + +2020-05-31 kwwette + [Octave] #1789 error handling improvements and return error code on exit for SWIG wrapped modules. + +2020-05-30 msteinbeck + [D] #1593 Replace broken imports when using newer versions of D. + +2020-05-29: ZackerySpytz + [Python] #1716 Performance improvements converting strings when using Python >= 3.3. + +2020-05-28: ZackerySpytz + #1776 Quite dramatically decrease run times when generating very large interface files by changing + some internal memory pool sizes. + +2020-05-28: mcfarljm + #1788 Fix handling of Doxygen \endlink command. + +2020-05-24: vapier + [Javascript] #1796 Fix pkg-config invocation in configure. + +2020-04-30: kwwette + [Octave] Fix exception raising for newer Octave versions + Since (at least) Octave 5.1.0, the Octave error() function now raises a C++ exception, + which if uncaught immediately exits a SWIG wrapper function, bypassing any cleanup code + that may appear after a "fail:" label. This patch adds a "try { ... } catch(...) { }" + block around the contents of SWIG wrapper functions to first execute the cleanup code + before rethrowing any exception raised. It is backward compatible with earlier versions + of Octave where error() does not raise an exception, which will still branch to the + "fail:" block to execute cleanup code if an error is encountered. + + Note that the new "try { ... } catch(...) { }" block will localise any local variables + used in typemaps that were NOT declared through SWIG's %typemap(...) syntax, so it's + possible this could break existing SWIG wrappers which were implicitly sharing local + variables between typemaps. This can be fixed, however, by declaring local variables + which need to be shared between typemaps through SWIG's %typemap(...) syntax. + +2020-02-18: ryannevell + [Lua] #1728 Add support for LUA lightuserdata to SWIG_Lua_ConvertPtr. + +2020-02-18: dmach + [Ruby] #1725 Fix gcc -Wcatch-value warnings. + +2020-02-14: treitmayr + #1724 Fix wrapping of abstract user-defined conversion operators. + +2020-02-13: ddurham2 + [Python] #1512 Fix memleak when using STL containers of shared_ptr objects. + +2020-02-06: wsfulton + [Python] #1673 #1674 Fix setting 'this' when extending a proxy class with __slots__. + +2020-01-31: vadz + [Ruby] #1651 Add std::auto_ptr<> typemaps. + +2020-01-31: ZackerySpytz + [Python] #1700 More robust error checking for failures in calls to Python C API: + PyBytes_AsStringAndSize() and PyString_AsStringAndSize(). + +2020-01-31: vadz + [Python] #1710 Fix crash parsing empty docstrings. + +2020-01-30: Alzathar + [R] #910 #914 Fix R memory leak on exception. + +2020-01-30: richardbeare + [R] #1511 Fix bug wrapping functions. These were previously incorrectly wrapped as if + they were variables. This happened when 'get' or 'set' was in the name of the function + or method, but sometimes also in some other circumstances. If you were using R + attribute syntax to access these methods, you'll need to switch to calling them as R + methods. + + *** POTENTIAL INCOMPATIBILITY *** + +2020-01-24: etse-dignitas, wsfulton + [C#, D, Java] #1533 Fix upcasting for shared_ptr's of templated types. + +2020-01-16: mcfarljm + #1643 #1654 When using -doxygen, fix segfault when nameless parameters or vararg parameters + are used. + +2020-01-16: mcfarljm + #1632 #1659 Fix newline handling for doxygen "///" comments. + +2020-01-14: mcfarljm + #1647 #1656 Fix crash handling empty doxygen comments. + +2020-01-14: mcfarljm + #1608 Improve doxygen support. + - Add support for \param[] commands such as: \param[in]. + - Optional arguments are marked as 'optional' in pydoc. + - Improve support for \code commands so that other languages are supported as code blocks. + Support added for java, c and py. For example Python: \code{.py} ... \endcode + - Fix doxygen handling of \em and \p tags for Python. + +2020-01-13: wsfulton + [Python] #1595 Python -builtin constructors silently ignored keyword arguments. + Instead of silenty ignoring them, now a "TypeError: f() takes no keyword arguments" + exception is thrown if keyword arguments are used. Hence constructors and normal methods/ + functions behave in the same way. Note, -keyword should be used with -builtin to obtain + keyword argument support. + +2020-01-05: jschueller shadchin + [Python] #1670 #1696 Add missing field initializers introduced in python 3.8: + tp_vectorcall and tp_print. + +2020-01-05: friedrichatgc + [Octave] #1688 Change swig_this() to use size_t instead of long for compatibility + with Windows 64 bit. + +2020-01-05: treitmayr + [Ruby] #1692 #1689 Add support for Ruby 2.7 + +2019-12-30: treitmayr + [Ruby] #1653 #1668 Fix code generated when using -globalmodule option. + +2019-12-29: ZackerySpytz + [OCaml] #1686 Fix compilation errors with OCaml 4.09.0. + +2019-12-10: wsfulton + #1679 Fix parsing of C++11 identifiers with special meaning (final and override) when + they are used as part of the scope name of an identifier, such as a namespace name. + +2019-11-26: wsfulton + [C#] #1628 'out' or 'ref' used in a cstype typemap was not always stripped out in parts + of director code generation. + +2019-11-01: wsfulton + [Python] #1595 Fix bug in support for keyword arguments (kwargs feature or -keyword) + when using -builtin. The fix is in the argument error checking when wrapping zero + argument constructors only. + +Version 4.0.1 (21 Aug 2019) +=========================== + +2019-08-20: TekuConcept + [Javascript] #1535 Add %native support to Javascript. + +2019-08-20: bkotzz + [Java] #1616 Add SWIG_JavaIllegalStateException to support throwing + java.lang.IllegalStateException from JNI code. + +2019-08-19: sjml + [Lua] #1596 tostring output changes to show the underlying C/C++ pointer. + +2019-08-08: rokups + [C#, Java] #1601 Fix invalid code generated for "%constant enum EnumType. + +2019-08-07: wsfulton + [Python] Fix method overloading of methods that take STL containers of different + types. The following usage (using std::vector) would fail when using -builtin: + + %include + %include + + %inline %{ + struct X {}; + %} + + %template(VectorX) std::vector; + %template(VectorInt) std::vector; + + %inline %{ + using namespace std; + string VectorOverload(vector v); + string VectorOverload(vector v); + %} + + The following would incorrectly fail: + + s = VectorOverload([1, 2, 3]) + + With: + + Traceback (most recent call last): + File "runme3.py", line 20, in + ret = VectorOverload([1, 2, 3]) + TypeError: Wrong number or type of arguments for overloaded function 'VectorOverload'. + Possible C/C++ prototypes are: + VectorOverload(std::vector< Number,std::allocator< Number > >) + VectorOverload(std::vector< int,std::allocator< int > >) + + The problem was due to some error handling that was not cleared during typehecking. + In this case an error was not cleared when the elements in the list failed the + typecheck for converting to X. Only occurs in Python 3+. + + In some combinations of overloaded methods, the following type of error message would + occur: + + RuntimeError: in sequence element 0 + + The above exception was the direct cause of the following exception: + + Traceback (most recent call last): + File "runme3.py", line 23, in + check(VectorOverload(v), "vector") + SystemError: returned a result with an error set + +2019-08-01: wsfulton + #1602 Fix regression in 4.0.0 where a template function containing a parameter + with the same name as the function name led to the parameter name used in the + target language being incorrectly modified. + +2019-07-29: wsfulton + Remove all generated files on error. Previously generated files were not removed, + potentially breaking Makefiles using file dependencies, especially when -Werror + (warnings as errors) was used. + +2019-07-23: smithx + [C#] #1530 #1532 Fix marshalling of std::wstring to C#. + +2019-07-18: gicmo + [Python] #1587 Python 3.8 support - remove use of deprecated PyObject_GC_UnTrack. + +2019-07-18: cher-nov + [Python] #1573 Generated Python code uses consistent string quoting style - double + quotes. + +2019-07-16: geefr + [C#] #616 #1576 Fix C# bool INPUT[], bool OUTPUT[], bool INOUT[] typemaps to marshall + as 1-byte. + +2019-07-12: vadz + [C#, Java] #1568 #1583 Fix std::set<> typemaps for primitive types. + +2019-07-12: vadz + #1566 #1584 Regression in 4.0.0 - fix missing value for first item of enums with + trailing comma. + +2019-07-11: mcfarljm + #1548 #1578 Fix segfault in Doxygen parser parsing empty lines in some commands like + \code. + +2019-07-09: IsaacPascual + [C#, Java] #1570 Fix name of generated C#/Java classes for %interface macros + in swiginterface.i when wrapping nested C++ classes. + +2019-07-05: wsfulton + [Python] #1547 Whitespace fixes in Doxygen translated comments into pydoc comments + for Sphinx compatibility. + +2019-06-28: wsfulton + [MzScheme, OCaml] #1559 $arg and $input were incorrectly substituted in the + argout typemap when two or more arguments were present. + +2019-06-24: wsfulton + [Python, Ruby] #1538 Remove the UnknownExceptionHandler class in order to be + C++17 compliant as it uses std::unexpected_handler which was removed in C++17. + This class was intended for director exception handling but was never used by + SWIG and was never documented. + + *** POTENTIAL INCOMPATIBILITY *** + +2019-06-06: bkotzz + [Java] #1552 Improve performance in Java std::vector constructor wrapper that takes + a native Java array as input. + +2019-06-03: olly + [Python] Fix regression in implicit_conv handling of tuples, + introduced in SWIG 4.0.0. Fixes #1553, reported by Alexandre + Duret-Lutz. + +2019-05-24: wsfulton + [Octave] Fix detection of Octave on MacOS. + +2019-05-24: opoplawski + [Octave] #1522 Adapt OCTAVE_LDFLAGS for Octave 5.1. + +2019-05-22: ferdynator + [PHP] #1528 Don't add a closing '?>' PHP tag to generated files. + PSR-2 says it MUST be omitted for files containing only PHP. +Version 4.0.0 (27 Apr 2019) +=========================== + +2019-04-24: vadz + #1517 Fix crash if "@return" Doxygen tag was used on a node without any return type. + +2019-04-24: vadz + #1515 Fix parsing of enums with trailing comma when using -doxygen. + +2019-04-19: ianlancetaylor + [Go] #1055 When generating Go code, make -cgo the default. Add new -no-cgo option + to disable the default. + +2019-04-19: pbecherer + [Tcl] #1508 Fix Visual Studio 2015 and later compilation errors due to snprintf macro + definition. + +2019-04-09: wsfulton + [C#] Fix FxCop warning CA2002 in SWIGPendingException - a lock on a reference of + type 'Type'. + +2019-03-30: wsfulton + [Java, D] Add the parameters typemap attribute to the javadestruct, + javadestruct_derived, ddispose, ddispose_derived typemaps to mirror enhanced + flexibility in the csdisposing and csdisposing_derived (C#) typemaps. If provided + the contents are generated as the delete/dispose method's parameters declaration. + +2019-03-30: wsfulton + [C#] #421 Fix FxCop warning CA1063 by implementing the recommended Dispose methods for + the IDisposable interface. Previously just the Dispose() method was generated. + Now the Dispose() and Dispose(bool disposing) methods are generated. + Changes are required if custom "csfinalize", "csdestruct" or "csdestruct_derived" + typemaps are being used. Details in #421 on Github. SWIG will error out if one of + the "csfinalize, "csdestruct" or "csdestruct_derived" typemaps are found. Example + error message: + + foo.h:60: Error: A deprecated csfinalize typemap was found for Foo, please remove + it and replace all csdestruct, csdestruct_derived and csfinalize typemaps by the + csdispose, csdispose_derived, csdisposing and csdisposing_derived typemaps. + + *** POTENTIAL INCOMPATIBILITY *** + +2019-03-25: Liryna + [C#] #1143 Add std_list.i for std::list support. + The C# std::list wrappers are made to look and feel like a C# + System.Collections.Generic.LinkedList<> collection. + The IEnumerable<> interface is implemented in the proxy class. + The ICollection<> interface can also be implemented to provide enhanced functionality + whenever a C++ operator== is available. This is the case for when T is a + primitive type or a pointer. If T does define an operator==, then use the + SWIG_STD_LIST_ENHANCED macro to obtain this enhanced functionality, for example: + + SWIG_STD_LIST_ENHANCED(SomeNamespace::Klass) + %template(ListKlass) std::list; + +2019-03-18: richardbeare + [R] #1328 Non-trivial enums are working now. The enum values are now obtained from + the C/C++ layer. const reference enums and C++11 enum classes are also now working. + +2019-03-14: mochizk + [Javascript] #1500 Fix compilation errors due to deprecating V8 API in Node.js. + New V8 API is used if node.js >= v10.12, or if V8 >= v7.0. + +2019-03-12: vadz + [C#] #1495 Add std_set.i for std::set support. + +2019-03-11: dirteat,opoplawski + [Octave] Fix compilation errors in Octave 5.1. + + error: format not a string literal and no format arguments [-Werror=format-security] + +2019-02-28: wsfulton + [Java] std::vector improvements for types that do not have a default constructor. + + The std::vector wrappers have been changed to work by default for elements that are + not default insertable, i.e. have no default constructor. This has been achieved by + not wrapping: + + vector(size_type n); + + Previously the above had to be ignored via %ignore. + + If the above constructor is still required it can be added back in again via %extend: + + %extend std::vector { + vector(size_type count) { return new std::vector< T >(count); } + } + + Alternatively, the following wrapped constructor could be used as it provides near-enough + equivalent functionality: + + vector(jint count, const value_type& value); + + *** POTENTIAL INCOMPATIBILITY *** + +2019-02-25: wsfulton + [Python] Fix compile errors wrapping overloaded functions/constructors where a vararg + function is declared after a non-vararg function. + +2019-02-23: zphensley42 + Use fully qualified name 'java.lang.Object' instead of 'Object' in generated code to + avoid clashes with wrapped C++ classes called 'Object'. + +2019-02-23: gtbX + [Java] #1035 Add (const char *STRING, size_t LENGTH) typemaps in addition to the non-const + typemaps (char *STRING, size_t LENGTH) which does not attempt to write back to the const + string. + +2019-02-22: tamuratak + [Ruby] #984 Add support for RTypedData introduced in Ruby 1.9.3. + +2019-02-22: ZackerySpytz + #1483 Fix compilation failures when a director class has final methods. + +2019-02-21: wsfulton + [Java] #1240 Suppress Java 9 deprecation warnings on finalize method. + +2019-02-21: ZackerySpytz + #1480 Fix some rejections of valid floating-point literals. + +2019-02-19: wsfulton + #1475 Fix regression parsing gcc preprocessor linemarkers in the form: + + # linenum filename flags + +2019-02-18: jakecobb + [Python] #945 #1234 Elements in std::vector memory access fix. + + Accessing an element in a std::vector obtains a reference to the element via an + iterator pointing to the element in the container. If the vector is garbage collected, + the SWIG wrapper containing the pointer to the element becomes invalid. The fix is + to obtain a back-reference to the container by the wrapper to the element in the Python + layer to prevent the garbage collector from destroying the underlying container. + +2019-02-17: wsfulton + Fix typemap matching to expand template parameters when the name contains + template parameters. In the %typemap below the type is T and the name is X::make + and the name now expands correctly to X< int >::make + + template struct X { + %typemap(out) T X::make "..." + T make(); + }; + + %template(Xint) X; + +2019-02-16: wsfulton + Fix parser error containing multiple #define statements inside an enum. + + The second #define fails to parse: + + enum FooEnum { + ENUM1 = 0, + ENUM2 = 1, + + #define MACRO_DEF1 "Hello" + #define MACRO_DEF2 "World!" + + ENUM3 = 2, + ENUM4 = 3, + }; + + Bug mentioned at https://sourceforge.net/p/swig/patches/333/ + +2019-02-14: wsfulton + Add some missing copy constructors into STL containers. + +2019-02-14: bkotzz + [Java] #1356 Add STL containers: + std::unordered_map + std::unordered_set + std::set + +2019-02-14: bkotzz + [Java] #1356 std::map wrappers have been modified. Now the Java proxy class + extends java.util.AbstractMap. The std::map container looks and feels much like + a java.util.HashMap from Java. + + A few members have changed their names. If the old method signatures are needed, + then copy std_map.i from swig-3.0.12 and use that instead. Alternatively, + add the old missing methods to the new methods by using the following %proxycode: + + %extend std::map { + %proxycode %{ + // Old API + public boolean empty() { + return isEmpty(); + } + public void set($typemap(jboxtype, K) key, $typemap(jboxtype, T) x) { + put(key, x); + } + public void del($typemap(jboxtype, K) key) { + remove(key); + } + public boolean has_key($typemap(jboxtype, K) key) { + return containsKey(key); + } + %} + } + + *** POTENTIAL INCOMPATIBILITY *** + +2019-02-13: ZackerySpytz + #1469 Add support for C++17 hexadecimal floating literals. + +2019-02-11: wsfulton + [OCaml] #1437 OCaml has been give the 'Experimental' language status. The examples work + and most of the test-suite is also working, so it is quite close to being a 'Supported' language. + +2019-02-10: ZackerySpytz + #1464 Add support for C++14 binary integer literals. + +2019-02-10: ZackerySpytz + #1450 Add support for C++11 UCS-2 and UCS-4 character literals. Also, add support for + C++17 UTF-8 character literals. + +2019-02-10: wsfulton + [MzScheme] #1437 MzScheme/Racket is now an 'Experimental' language. The examples work + and a large portion of the test-suite is also working. + +2019-02-10: wsfulton + [MzScheme] Destructor wrappers were not being generated. + +2019-02-10: wsfulton + [MzScheme] Static variable wrappers fixed - $argnum was not expanded. + +2019-02-10: sethrj + #1452 Fix %apply for anonymous template instantiations + +2019-02-09: olly + [PHP] Fix access to already released memory during PHP module + shutdown, which often didn't cause visible problems, but could + result in segmentation faults, bus errors, etc. Fixes #1170, + reported by Jitka Plesníková. + +2019-02-09: olly + [PHP] A renamed constructor is now wrapped as a static method in + PHP. + +2019-02-08: olly + [PHP] Don't generate code which references $r when $r hasn't been + defined. This could happen in overloaded methods which returned + void and took at least one const std::string& parameter. + +2019-02-08: olly + [PHP] The generated code is now compatible with PHP 7.3, and the + testsuite now runs cleanly with this version too. + +2019-02-05: wsfulton + #1437 SWIG now classifies the status of target languages into either 'Experimental' or + 'Supported'. This status is provided to indicate the level of maturity to expect when using + a particular target language as not all target languages are fully developed. Details are + in the Introduction.html chapter of the documentation. + +2019-02-04: wsfulton + [CFFI] #1447 Common Lisp CFFI has been disabled as a target language in SWIG as part of a + clean up to remove target languages that have been neglected/not functional. + +2019-02-04: wsfulton + [Allegrocl] #1447 Allegro Common Lisp has been disabled as a target language in SWIG as part of a + clean up to remove target languages that have been neglected/not functional. + +2019-02-04: wsfulton + [Chicken] #1447 CHICKEN has been disabled as a target language in SWIG as part of a + clean up to remove target languages that have been neglected/not functional. + +2019-02-04: wsfulton + [CLISP] #1447 GNU Common Lisp has been disabled as a target language in SWIG as part of a + clean up to remove target languages that have been neglected/not functional. + +2019-02-04: wsfulton + [S-EXP] #1447 Common Lisp S-Exp has been disabled as a target language in SWIG as part of a + clean up to remove target languages that have been neglected/not functional. + +2019-02-04: wsfulton + [UFFI] #1447 Common Lisp UFFI has been disabled as a target language in SWIG as part of a + clean up to remove target languages that have been neglected/not functional. + +2019-02-04: wsfulton + [Pike] #1447 Pike has been disabled as a target language in SWIG as part of a + clean up to remove target languages that have been neglected/not functional. + +2019-02-04: wsfulton + [Modula3] #1447 Modula3 has been disabled as a target language in SWIG as part of a + clean up to remove target languages that have been neglected/not functional. + +2019-02-02: ahnolds + [Python] Documentation enhancements for Python: + + #728 Fixed the handling of autodoc when using -fastproxy. + + #1367 Added documentation to wrapped member variables using the + property(... doc="...") construct. + + Only show a single documentation entry for functions with default arguments when + using autodoc. + + Fixed a bug where a cached doxygen docstring could be deleted while still in use, + causing swig to segfault. + +2019-01-31: olly + SWIG now requires a target language to be specified instead of + defaulting to wrapping for Tcl. Specifying swig --help without + a target language now just shows the generic help. The -nolang + option has been removed. + +2019-01-28: ZackerySpytz + [OCaml] #1429 Remove support for OCaml versions < 3.12.0. + + *** POTENTIAL INCOMPATIBILITY *** + +2019-01-22: vadz + [Ruby, Octave] #1424 Improve autodoc parameter naming. + +2019-01-22: vadz + [Python] #1271 #1423 Always include default parameter values in autodoc strings. + +2019-01-19: vadz + #1272, #1421 When a function's parameter is a keyword, the name of the paramater is + no longer simply changed to argN, where N is the argument number. Instead the + parameter name is changed to the renaming rules for keywords that normally apply to + symbols such as classes/functions etc. Note that unlike other symbol renaming, + parameter renaming does not issue a warning when the parameter is renamed. This + change only affects languages where the parameter names are actually used, for example, + Java function parameter lists in the proxy class or Python documentation comments. + +2019-01-18: wsfulton + #1420 Fix gdb debugger functions 'swigprint' and 'locswigprint' from swig.gdb to + work with newer versions of gdb-8. Fixes errors when debugging SWIG source with gdb: + + (gdb) swigprint n + Undefined command: "Printf". Try "help". + +2019-01-16: wsfulton + Python static method wrapper changes + + - Static method wrappers were using the 'fastproxy' approach by default. + This is inconsistent with instance method wrappers. The fastproxy approach + is now turned off by default to be consistent with instance methods. + Static method wrappers can now also be controlled using the -fastproxy and + -olddefs options. + + Example: + + struct Klass { + static int statmethod(int a = 2); + }; + + generates by default: + + class Klass(object): + ... + @staticmethod + def statmethod(a=2): + return _example.Klass_statmethod(a) + + instead of the following (which can be restored by using -fastproxy): + + class Klass(object): + ... + statmethod = staticmethod(_example.Klass_statmethod) + + - Modernise wrappers for static methods to use decorator syntax - @staticmethod. + + - Add missing runtime test for static class methods and using the actual class method. + +2019-01-12: ZackerySpytz + [OCaml] #1403 #1194 Fix compilation problems for OCaml >= 4.03.0 due to OCaml using + int64_t instead of int64. + +2019-01-11: ZackerySpytz + [OCaml] #1400 Fix the getters and setters of non-static member variables. + +2019-01-07: wsfulton + #358 Add VOID to windows.i + +2019-01-05: wsfulton + #948 #1019 #1273 Fix for C++11 raw strings where the delimiters were mistakenly left + in the string contents in situations where the string was copied into generated code. + For example, %constant, the "docstring" feature and for C#/Java/D constants turned on + with %javaconst/%csconst/%dmanifestconst. + +2019-01-05: wsfulton + [Ruby] #538. Fix Ruby support for %feature("docstring"). + +2019-01-03: wsfulton + #1202 Fix overloading of non-pointer class types in scripting languages when overloaded + with a pointer and a NULL scripting language equivalent is used, eg None in Python. + + The implementation changes the SWIGTYPE, SWIGTYPE& and SWIGTYPE&& typecheck typemaps to + prevent accepting a conversion to a NULL pointer. + +2019-01-03: ZackerySpytz + [OCaml] #1386 Fix the OCaml examples and test suite for out-of-source builds. + +2019-01-01: wsfulton + [Python] #639 remove duplicate proxy method definitions for global function wrappers. + + Global functions previously generated two definitions, eg: + + def foo(): + return _example.foo() + foo = _example.foo + + The first definition is replaced by the second definition and so the second definition + is the one used when the method is actually called. Now just the first definition is + generated by default and if the -fastproxy command line option is used, just the second + definition is generated. The second definition is faster as it avoids the proxy Python + method as it calls the low-level C wrapper directly. Using both -fastproxy and -olddefs + command line options will restore the previously generated code as it will generate both + method definitions. + + With this change, the wrappers for global C/C++ functions and C++ class methods now work + in the same way wrt to generating just a proxy method by default and control via + -fastproxy/-olddefs options. + +2018-12-20: hasinoff,wsfulton + [Java] #1334 Set Java thread name to native thread name when using directors. + + Default is to use name "Thread-XXX" and is still works like this by default. However, + adding the following will turn on the thread name setting (works for more recent + versions of Linux and MacOS): + + %begin %{ + #define SWIG_JAVA_USE_THREAD_NAME + %} + +2018-12-20: chlandsi + [Python] #1357. Fix overriding __new__ in Python 3.6. + + Fixes SystemError: Objects/tupleobject.c:81: bad argument to internal function" + +2018-12-16: wsfulton + [Python] #848 #1343 The module import logic has changed to stop obfuscating real ImportError + problems. Only one import of the low-level C/C++ module from the pure Python module is + attempted now. Previously a second import of the low-level C/C++ module was attempted + after an ImportError occurred and was done to support 'split modules'. A 'split module' is + a configuration where the pure Python module is a module within a Python package and the + low-level C/C++ module is a global Python module. Now a 'split module' configuration is + no longer supported by default. This configuration can be supported with a simple + customization, such as: + + %module(package="mypackage", moduleimport="import $module") foo + + or if using -builtin: + + %module(package="mypackage", moduleimport="from $module import *") foo + + instead of + + %module(package="mypackage") foo + + See the updated Python chapter titled "Location of modules" in the documentation. + +2018-12-11: tlby + [Perl] #1374 repair EXTEND() handling in typemaps + +2018-12-06: vadz + #1359 #1364 Add missing nested class destructor wrapper when the nested class is + inside a template. Removes associated bogus 'Illegal destructor name' warning. Only + occurred when the nested class' destructor is explicitly specified. + +2018-12-04: adr26 + [Python] #1368 #1369 Access Violation in tp_print caused by mismatched Python/extension + CRT usage + + Remove all use of tp_print, as this API uses a FILE*, which can be + mismatched when modules are built with different C libraries from + the main python executable. + + This change also brings consistent output between Python 2 and 3 for the 'cvar' SWIG + object (that contains the global variables) and SWIG packed objects (such as callback + constants). + +2018-12-04: wsfulton + [Python] #1282 Fix running 'python -m' when using 'swig -builtin' + + Similar to the earlier PEP 366 conforming fix for non-builtin. + +2018-11-29: adr26 + [Python] #1360 Leak of SWIG var link object + + Fix reference counting on _SWIG_globals to allow var link to be freed on module unload. + +2018-11-28: wsfulton + [Python] When using -builtin, the two step C-extension module import is now + one step and the wrapped API is only available once and not in an underlying + module attribute like it is without -builtin. To understand this, consider a + module named 'example' (using: %module example). The C-extension is compiled into + a Python module called '_example' and a pure Python module provides the actual + API from the module called 'example'. It was previously possible to additionally + access the API from the module attribute 'example._example'. The latter was an + implementation detail and is no longer available. It shouldn't have been used, but + if necessary it can be resurrected using the moduleimport attribute described in the + Python chapter of the documentation. If both modules are provided in a Python + package, try: + + %module(moduleimport="from . import _example\nfrom ._example import *") example + or more generically: + %module(moduleimport="from . import $module\nfrom .$module import *") example + + and if both are provided as global modules, try: + + %module(moduleimport="import _example\nfrom _example import *") example + or more generically: + %module(moduleimport="import $module\nfrom $module import *") example + + The module import code shown will appear in the example.py file. + +2018-11-24: vadz + #1358 Fix handling of abstract base classes nested inside templates + + Correct detecting of whether a derived class method overrides a pure virtual + base class method when both classes are nested inside a template class: this + notably didn't work correctly for methods taking parameters of the base class + type. + +2018-11-22: rupertnash + [Python] #1282 Make generated module runnable via python -m (PEP 366 conforming) + + Previously any SWIG generated modules in a package would fail with an ImportError + when using 'python -m' for example 'python -m mypkg.mymodule'. + + This fix also allows the SWIG generated module to be placed into a directory and + then renamed __init__.py to convert the module into a package again. This ability + stopped working in swig-3.0.9. However, only Python 2.7 or 3.3 and later work. If + Python 3.2 support is needed, use moduleimport in %module to customise the import + code. + +2018-11-13: wsfulton + #1340 Remove -cppcast and -nocppcast command line options (this was an option + available to the scripting language targets). + + The -cppcast option is still turned on by default. The -nocppcast option + to turn off the use of c++ casts (const_cast, static_cast etc) has been + removed. However, defining SWIG_NO_CPLUSPLUS_CAST will still generate C casts + instead of C++ casts for C++ wrappers. + + *** POTENTIAL INCOMPATIBILITY *** + +2018-11-13: wsfulton + [Python] #1340 Remove -outputtuple and -nooutputtuple command line options. + + Both the command line and %module options of the same name have been + removed. These were undocumented. The -outputtuple option returned a + Python tuple instead of a list, mostly typically in the OUTPUT + typemap implementations. + + It unclear why a tuple instead of a list return type is needed and + hence this option has been removed as part of the simplification of + the SWIG Python command line options for SWIG 4. + +2018-11-13: wsfulton + [Python] #1340 Remove -noproxyimport command line option. + + This option turned off the insertion of Python import statements + derived from a %import directive. For example given: + + %module module_b + %import "module_a.i" + + then module_b.py will contain: + + import module_a + + *** POTENTIAL INCOMPATIBILITY *** + +2018-10-29: AlexanderGabriel + [PHP] The following PHP7 reserved keywords are now only renamed by + SWIG when used as function names in the API being wrapper: + __halt_compiler array die echo empty eval exit include include_once + isset list print require require_once return unset + +2018-10-22: olly,wsfulton + [Python] #1261 #1340 Turn on many optimisation options by default and rationalise the + number of command line options. + + There were an unnecessary number of command line options and many of these have now + been removed in a drive for simplification. Some were needed to support older versions + of Python (2.6 and earlier). + + Many of the options could be turned on individually and when using -O. Previously -O + resulted in turning on a set of options: + + -modern -fastdispatch -nosafecstrings -fvirtual -noproxydel + -fastproxy -fastinit -fastunpack -fastquery -modernargs -nobuildnone + + Now -O results in turning on this reduced set: + + -fastdispatch -fastproxy -fvirtual + + The following options are now on by default, a deprecated warning is displayed if they + are used: + -fastinit Class initialisation code done in C/C++ rather than in Python code. + -fastquery Python dictionary used for lookup of types. + -fastunpack Faster unpacking of function arguments in C/C++ wrappers. + -modern Use Python 2.3 features such as object and property. + -modernargs Use Python 2.3 C APIs for unpacking arguments in tuples. + -noproxydel Stop generating a proxy __del__ method for backwards compatiblity. + -safecstrings No discernable difference + + The following options have been removed altogether: + -aliasobj0 + -buildnone + -classptr + -new_repr + -newrepr + -noaliasobj0 + -nobuildnone + -nocastmode + -nodirvtable + -noextranative + -nofastinit + -nofastproxy + -nofastquery + -nomodern + -nomodernargs + -nooutputtuple + -nosafecstrings + -old_repr + -oldrepr + -proxydel + + -new_vwm is no longer supported. Use the -newvwm alias instead. + + *** POTENTIAL INCOMPATIBILITY *** + +2018-10-22: olly + [Python] #1261 Remove command line option no longer needed as Python 2.3 and earlier + are no longer supported: + + -classic + +2018-10-09: wsfulton + [D, Go, Guile, Lua, Mzscheme, Ocaml, Perl5, Php, Scilab, Tcl] + Allow wrapping of std::map using non-default comparison function. + +2018-10-09: vadz + [Java] #1274 Allow wrapping of std::map using non-default comparison function. + +2018-10-04: wsfulton + [Python] #1126 Fix C default arguments with -builtin and -fastunpack and -modernargs. + Problem occurred when there is just one (defaulted) parameter in the parameter list. + +2018-09-24: wsfulton + [Python] #1319 C++11 hash tables implementation is finished now (including for -builtin): + std::unordered_map + std::unordered_set + std::unordered_multimap + std::unordered_multiset + +2018-09-21: wsfulton + [Python] Fix when using -builtin and wrapping std::map, std::set, std::unordered_map or + std::unordered_set to ensure __contains__ is called. This is a wrapper for the STL + container's find method. Without it, Python will do its own slower sequence search. + +2018-09-19: wsfulton + [Python] Fix functors (wrapped as __call__) when using -builtin -modern -fastunpack. + +2018-09-02: andreas.gaeer,tkrasnukha + [Python] #1321 Fix assert in PyTuple_GET_SIZE in debug interpreter builds of python-3.7 + when calling tp_new. + +2018-09-01: ChristopherHogan + [Guile] #1288 Fix garbage collection for guile >= 2.0.12. + +2018-08-31: wsfulton + [Python] #1319 C++11 hash tables support: + std::unordered_map + std::unordered_set + std::unordered_multimap + std::unordered_multiset + is now compiling and working (sorting using -builtin not fully functional yet though). + +2018-08-20: wkalinin + #1305 Fix nested structure symbol tables in C mode to fix member name conflicts + in different structs with the same nested struct member name. + +2018-08-18: wsfulton + [Python] #688 Fix makefile recursion when running python test-suite. + +2018-08-18: wsfulton + [Python] #1310 Re-implement Python -fastproxy option. + + The previous implementation failed with Python 3 and abstract base clases. + The new implementation replaces the Python 2 implementation using + new.instancemethod with the C API PyMethod_New to match the equivalent Python 3 + implementation which uses PyInstanceMethod_New. + + The new approach runs slightly faster. See #1310. + +2018-08-12: gmazzamuto + [Python] #1283 Update pybuffer.i library to use new-style Python buffer C API. + +2018-08-12: brianhatwood,wsfulton + [Java] #1303 #1304 Fix crash in directors when using OUTPUT and INOUT typemaps in typemaps.i and + passing NULL pointers in C++ to director method overloaded and implemented in Java. + +2018-08-10: wsfulton + [Python] #1293 Improve TypeError message inconsistencies between default and fastdispatch + mode when handling overloaded C++ functions. Previously the error message did not always + display the possible C/C++ prototypes in fastdispatch mode. + +2018-08-02: furylynx,jacobwgillespie,p2k + [Javascript] #1290, #968. Add support for NodeJS versions 2-10. + +2018-07-31: wsfulton + [Python] #1293 Overloaded C++ function wrappers now raise a TypeError instead + of NotImplementedError when the types passed are incorrect. This change means + there is now consistency with non-overloaded function wrappers which have always + raised TypeError when the incorrect types are passed. The error message remains + the same and is for example now: + + TypeError: Wrong number or type of arguments for overloaded function 'f'. + Possible C/C++ prototypes are: + f(int) + f(char const *) + + instead of: + + NotImplementedError: Wrong number or type of arguments for overloaded function 'f'. + Possible C/C++ prototypes are: + f(int) + f(char const *) + + *** POTENTIAL INCOMPATIBILITY *** + +2018-06-23: wsfulton + [Python] #718 Fix pythonnondynamic feature for modern classes + + Fixes nondynamic mode when an instance variable is set with the same + name as a class variable in a class derived from a SWIG proxy class. + This corner case set an instance variable instead of raising an AttributeError. + + Also fix %pythonnondynamic in Python 3 with -modern. The metaclass + containing the implementation was previously not being applied in Python 3. + +2018-07-17: petrmitrichev,wsfulton + [Python] #1275 #1279 Initialize function-local statics (singletons) that call Python + code during Python module initialization in order to avoid deadlocks with subsequent + multi-threaded usage. + +2018-06-15: wsfulton + [Python] Fix seg fault using Python 2 when passing a Python string, containing + invalid utf-8 content, to a wstring or wchar * parameter. A TypeError is thrown instead, eg: + + %include + void instring(const std::wstring& s); + + instring(b"h\xe9llooo") # Python + +2018-06-15: wsfulton + [Python] Python 3.7 support: Replace use of deprecated PyUnicode_GetSize with + PyUnicode_GetLength to remove deprecated warnings compiling the C/C++ wrappers. + +2018-06-12: wsfulton + [Python] Python 3.7 support: The %pythonabc feature in pyabc.i now uses base classes + collections.abc.MutableSequence + collections.abc.MutableMapping + collections.abc.MutableSet + instead of + collections.MutableSequence + collections.MutableMapping + collections.MutableSet + as the latter are deprecated in Python 3.7 and are due to be removed in Python 3.8. + The classes in collections.abc.* are available from Python 3.3 onwards. If you + require support for Python 3.2, then copy the pyabc.i file and modify by removing + the few instances of the .abc sub-module. + + *** POTENTIAL INCOMPATIBILITY *** + +2018-06-12: olly,wsfulton + [Python] #701 Remove support for Python versions < 2.7 and 3.0 and 3.1. + + *** POTENTIAL INCOMPATIBILITY *** + +2018-06-11: olly + [Python] Fix new GCC8 warnings in generated code by avoiding casts + between incompatible function types where possible, and by + suppressing the warning when it's due to the design of Python's C + API. Fixes #1259. + +2018-06-08: philippkraft + [Python] Stop exposing _swigregister to Python. It's not + useful for user Python code to call this, and it just clutters the + API unnecessarily. Fixes #1225. + +2018-06-07: cmfoil, kabbi, Jamie Kirkpatrick, markok314, vadz, wsfulton, Yann Diorcet + #170 Doxygen documentation support added. This allows translation of Doxygen comments + into JavaDoc and PyDoc documentation. It is enabled via the -doxygen command line + option. See the Doxygen.html chapter in the documentation for further information. + +2018-06-07: olly + [PHP] We've finally removed support for %pragma(php4) which was + deprecated back in 2008. Use %pragma(php) instead, which has been + supported since at least 2005. + + *** POTENTIAL INCOMPATIBILITY *** + +2018-06-07: olly + [PHP5] Support for PHP5 has been removed. PHP5 is no longer + actively supported by the PHP developers and security support for + it ends completely at the end of 2018, so it doesn't make sense + to include support for it in the upcoming SWIG 4.0.0 release. + + *** POTENTIAL INCOMPATIBILITY *** + +2018-06-06: olly + [Lua] Improve configure probes for Lua headers and libs used in testsuite. + +2018-05-15: kwwette + [Octave] add support for version 4.4 + - Should not introduce any user-visible incompatibilities + +2018-05-15: wsfulton + [C#, D, Java] Fix lookup of csconstruct, dconstruct and javaconstruct typemaps. + The C++ namespace was previously ignored when looking up the typemap. + +2018-05-15: wsfulton + [Javascript] Fix generated C++ code when using %nspace on namespaces that are more + than two levels deep. + +2018-05-14: wsfulton + Issue #1251 Add support for C++17 nested namespace definitions, + for example: + namespace A::B { ... } + +2018-05-11: wsfulton + [C#, D, Java] Add support so that the %csmethodmodifiers, %dmethodmodifiers, + %javamethodmodifiers can modify the method modifiers for the destructor wrappers + in the proxy class: dispose, Dispose, delete. With this feature, it is now possible + to make a C# proxy class sealed, eg when wrapping a class X, the virtual method modifiers + can be removed using: + + %typemap(csclassmodifiers) X "public sealed class" + %csmethodmodifiers X::~X "public /*virtual*/"; + +2018-04-18: olly + [Python] Suppress new pycodestyle warning: + E252 missing whitespace around parameter equals + +2018-04-07: goatshriek + [Ruby] #1213 Fix ruby %alias directive for global C/C++ functions. + +2018-04-03: olly + [Ruby] Fix to pass Qnil instead of NULL to rb_funcall(), which silences GCC + -Wconversion-null warning (on by default with recent GCC). + +2018-03-09: wsfulton + [Java] #1184 Fix swigReleaseOwnership() and swigTakeOwnership() regression + for non-director classes. Restores a dynamic_cast which was previously removed. + +2018-03-07: llongi + Github PR #1166 - Fix preprocessor handling of macros with commas + in a // comment. + +2018-02-18: JPEWdev + Patch #1164 - Add support for a command-line options file, also sometimes + called a response file. This is useful if the command-line options exceed + the system command-line length limit. To use, put the command-line options + into a file, then provide the file name prefixed with @, for example using + a file called args.txt: + + swig @args.txt + +2018-02-11: wsfulton + [Javascript] #1187 Fix compilation error wrapping std::complex via + std_complex.i. + +2018-01-30: smarchetto + [Scilab] add type name argument in SWIG_ptr() function to cast from pointer address to typed pointers + +2018-01-16: wsfulton + Expressions following a preprocessor directive must now be separated by whitespace + or non-numeric characters. This syntax change makes the SWIG preprocessor work like + the C preprocessor in this area. + + For example, the following code used be accepted as valid syntax: + #if1 + #define ABC 123 + #endif + + Now you get an error: + example.h:1: Error: Unknown SWIG preprocessor directive: if1 (if this is a block of + target language code, delimit it with %{ and %}) + example.h:3: Error: Extraneous #endif. + + The following is the correct syntax: + #if 1 + #define ABC 123 + #endif + + The following of course also works: + #if(1) + #define ABC 123 + #endif + + *** POTENTIAL INCOMPATIBILITY *** + +2018-01-15: wsfulton + Fix issue #1183. Floating point exception evaluating preprocessor expressions + resulting in division by zero. + +2018-01-14: wsfulton + Fix issue #1172. Seg fault parsing invalid exponents in the preprocessor. + +2018-01-12: Liryna + [C#] Patch #1128. Add ToArray function to std::vector wrappers. + +2018-01-12: wsfulton + [Java] Fix issue #1156. Add missing throws clause for interfaces when using the + %interface family of macros. + +2018-01-05: wsfulton + Fix default arguments using expressions containing -> syntax error. Problem reported on + swig-user mailing list. + +2017-12-30: wsfulton + [Python] Replace pep8 with pycodestyle for checking the Python code style when + running Python tests. + +2017-12-30: davedissian + Fixed a symbol lookup issue when encountering a typedef of a symbol from the tag + namespace to the global namespace when the names are identical, such as 'typedef + struct Foo Foo;'. + +2017-12-13: wsfulton + [Perl] add missing support for directorfree typemaps. + +2017-12-13: wsfulton + Issue #1167 Fix directorout typemaps which were causing undefined behaviour when + returning pointers by reference. + +2017-12-08: olly + [PHP] Use ZEND_MODULE_GLOBALS_ACCESSOR to access globals so the + generated code builds when PHP was built with ZTS enabled. + +2017-12-04: wsfulton + [Python] Add missing checks for failures in calls to PyUnicode_AsUTF8String. Previously a + seg fault could occur when passing invalid UTF8 strings (low surrogates), eg passing + u"\udcff" to the C layer (Python 3). + +2017-11-24: joequant + [R] Fix #1124 and return R_NilValue for null pointers + +2017-11-29: wsfulton + [Java] director exception handling improvements. + + When a director method throws an exception and it is caught by DirectorException + and passed back to Java using Swig::DirectorException::throwException, the Java + stack trace now contains the original source line that threw the exception. + + Deprecate Swig::DirectorException::raiseJavaException, please replace usage with + Swig::DirectorException::throwException. + + *** POTENTIAL INCOMPATIBILITY *** + +2017-10-26: wsfulton + Add support for C++11 ref-qualifiers when using directors. + +2017-10-26: wsfulton + Fix generated code when using directors and methods returning const ref pointers. + +2017-10-26: wsfulton + [C#, D, Java, Octave, R, Scilab] Port director typemaps to these additional languages. + Issue #700. + +2017-10-26: radarsat1 + [Ruby Python] Patch #1029 - Correct handling of null using directors and shared_ptr. + +2017-10-10: joequant + [R] pass enum expressions to R. This will generate + incorrect files when there is an arithmetic expression + in the enum, but this is better than silently generating + incorrect code + +2017-10-09: olly + [PHP] Fix incorrect wrapper code generated when there's a + combination of overloading, parameters with a default value + and %newobject. Fixes https://sourceforge.net/p/swig/bugs/1350/ + +2017-10-09: olly + Remove GCJ support. It isn't in a good state and doesn't seem to + be used, and GCC7 dropped GCJ. Closes + https://sourceforge.net/p/swig/bugs/823/ + +2017-10-07: olly + Fix preprocessor handling of empty macro arguments to match that of + C/C++ compilers. Fixes issue #1111 and + https://sourceforge.net/p/swig/bugs/826/ + +2017-10-06: wsfulton + [Python] Issue #1108. Fix platform inconsistency in Python default argument handling. + 32 bit and 64 bit compiled versions of SWIG generated different Python files + when default arguments were outside the range of 32 bit signed integers. + The default arguments specified in Python are now only those that are in the + range of a 32 bit signed integer, otherwise the default is obtained from C/C++ code. + +2017-10-02: wsfulton + [C#] Fix std::complex types passed by value. + +2017-10-02: wsfulton + [Javascript, Python, Ruby] Issue #732 - Missing type information for std::complex + in std_complex.i meant that previously std::complex always had to be fully qualified + in order to be wrapped with the appropriate typemaps. + +2017-10-01: joequant + allow R package names with docs + allowing multiple get accessors in R + fix smart-pointer and NAMESPACE support + constructors now returning smart pointers (if class + declared as such) + smart-pointer classes deriving from parent smart-pointers + +2017-09-29: wsfulton + Issue #1100 - Allow an instantiated template to have the same name in the target + language as the C++ template name, for example, this is now possible: + + template struct X { ... }; + %template(X) X; + +2017-09-23: wsfulton + Issue #1098. Fix overloading of shared_ptr with underlying pointer types, eg: + + void m(std::shared_ptr p); + void m(T &p); + void m(T *p); + + Only the first method is wrapped and the others are ignored/shadowed. + The implementation is done via a new attribute in the 'typecheck' typemap called + 'equivalent'. If specified, it must contain the equivalent pointer type for overloading + and can only be used for the special SWIG_TYPECHECK_POINTER precedence level. + The shared_ptr 'typecheck' typemaps have been modified accordingly. + Here is a simplified version: + + %typemap(typecheck, precedence=SWIG_TYPECHECK_POINTER, equivalent="T *") + T, + T CONST &, + T CONST *, + T *CONST&, + std::shared_ptr< T >, + std::shared_ptr< T > &, + std::shared_ptr< T > *, + std::shared_ptr< T > *& + { ... } + + Overloading with any of these types will result in SWIG ignoring all but the first + overloaded method by default. Without the 'equivalent' attribute, wrapping the overloaded + methods resulted in types being shadowed (scripting languages) or code that did not + compile (statically typed languages). + +2017-09-19: futatuki + [Python] #1003 Add --with-2to3=/path/to/2to3 option to configure. + +2017-09-18: wsfulton + Fix type promotion wrapping constant expressions of the form: + # define EXPR_MIXED1 (0x80 + 11.1) - 1 + This was previously an integral type instead of a floating point type. + +2017-09-17: wsfulton + Fix generated code for constant expressions containing wchar_t L literals such as: + # define __WCHAR_MAX (0x7fffffff + L'\0') + # define __WCHAR_MIN (-__WCHAR_MAX - 1) + +2017-09-10: mlamarre + [Python] Patch #1083. Define_DEBUG to 1 to do exactly like Visual Studio + /LDd, /MDd or /MTd compiler options. + +2017-08-25: wsfulton + Issue #1059. Add support for C++11 ref-qualifiers on non-static member functions. + Members with lvalue ref-qualifiers such as: + + struct RQ { + void m1(int x) &; + void m2(int x) const &; + }; + + are wrapped like any other member function. Member functions with rvalue ref-qualifiers + are ignored by default, such as: + + struct RQ { + void m3(int x) &&; + void m4(int x) const &&; + }; + + example.i:7: Warning 405: Method with rvalue ref-qualifier m3(int) && ignored. + example.i:8: Warning 405: Method with rvalue ref-qualifier m4(int) const && ignored. + + These can be unignored and exposed to the target language, see further documentation in + CPlusPlus11.html. + +2017-08-16: wsfulton + Fix #1063. Add using declarations to templates into typedef table. + + Using declarations to templates were missing in SWIG's internal typedef tables. + This led to a few problems, such as, templates that did not instantiate and generated + C++ code that did not compile as SWIG did not know what scope the template was + in. This happened mostly when a using declaration was used on a template type in a + completely unrelated namespace. + +2017-08-16: wsfulton + Fix type lookup in the presence of using directives and using declarations. + + Fix some cases of type lookup failure via a combination of both using directives and + using declarations resulting in C++ code that did not compile as the generated type was + not fully qualified for use in the global namespace. Example below: + + namespace Space5 { + namespace SubSpace5 { + namespace SubSubSpace5 { + struct F {}; + } + } + using namespace SubSpace5; + using SubSubSpace5::F; + void func(SubSubSpace5::F f); + } + +2017-08-16: wsfulton + Issue #1051. %template scope enforcement and class definition fixes. + + The scoping rules around %template have been specified and enforced. + The %template directive for a class template is the equivalent to an + explicit instantiation of a C++ class template. The scope for a valid + %template instantiation is now the same as the scope required for a + valid explicit instantiation of a C++ template. A definition of the + template for the explicit instantiation must be in scope where the + instantiation is declared and must not be enclosed within a different + namespace. + + For example, a few %template and C++ explicit instantiations of std::vector + are shown below: + + // valid + namespace std { + %template(vin) vector; + template class vector; + } + + // valid + using namespace std; + %template(vin) vector; + template class vector; + + // valid + using std::vector; + %template(vin) vector; + template class vector; + + // ill-formed + namespace unrelated { + using std::vector; + %template(vin) vector; + template class vector; + } + + // ill-formed + namespace unrelated { + using namespace std; + %template(vin) vector; + template class vector; + } + + // ill-formed + namespace unrelated { + namespace std { + %template(vin) vector; + template class vector; + } + } + + // ill-formed + namespace unrelated { + %template(vin) std::vector; + template class std::vector; + } + + When the scope is incorrect, an error now occurs such as: + + cpp_template_scope.i:34: Error: 'vector' resolves to 'std::vector' and + was incorrectly instantiated in scope 'unrelated' instead of within scope 'std'. + + Previously SWIG accepted the ill-formed examples above but this led to + numerous subtle template scope problems especially in the presence of + using declarations and using directives as well as with %feature and %typemap. + + Actually, a valid instantiation is one which conforms to the C++03 + standard as C++11 made a change to disallow using declarations and + using directives to find a template. + + // valid C++03, ill-formed C++11 + using std::vector; + template class vector; + + Similar fixes for defining classes using forward class references have + also been put in place. For example: + + namespace Space1 { + struct A; + } + namespace Space2 { + struct Space1::A { + void x(); + } + } + + will now error out with: + + cpp_class_definition.i:5: Error: 'Space1::A' resolves to 'Space1::A' and + was incorrectly instantiated in scope 'Space2' instead of within scope 'Space1'. + + Previously some symbols would have been instantiated in the wrong scope and led + to lots of scope problems involving SWIG typemaps, features, renames etc. + You will need to correct the scope used in other SWIG directives which do not + support 'using declarations' and 'using directives'. For example, if you previously had: + + %rename(Zap) vector::clear; + using namespace std; + %template(VectorInt) vector; + + Prior versions of SWIG incorrectly instantiated vector in the global namespace + and so the %rename matched. Now the template is instantiated in the correct namespace, + so is fully qualified as std::vector. The other SWIG directives need correcting as + they do not follow 'using declarations' and 'using directives'. Change it to: + + %rename(Zap) std::vector::clear; + using namespace std; + %template(vin) vector; + + + *** POTENTIAL INCOMPATIBILITY *** + +2017-08-16: wsfulton + Fix scope lookup for template parameters containing unary scope operators. + + Fixes cases like: + + namespace Alloc { + template struct Rebind { + typedef int Integer; + }; + } + %template(RebindBucket) Alloc::Rebind< Bucket >; + OR + %template(RebindBucket) Alloc::Rebind< ::Bucket >; + + Alloc::Rebind< Bucket >::Integer Bucket1(); + Alloc::Rebind< ::Bucket >::Integer Bucket2(); + Alloc::Rebind<::template TemplateBucket>::Integer Bucket3(); + +2017-08-16: wsfulton + For templates only, the template parameters are fully resolved when + handling typemaps. Without this, it is too hard to have decent rules + to apply typemaps when parameter types are typedef'd and template + parameters have default values. + + Fixes %clear for typedefs in templates, eg: + + %typemap("in") XXX::Long "..." + template typename struct XXX { + typedef long Long; + }; + %clear XXX::Long; + + as the typemap was previously incorrectly stored as a typemap for long + instead of XXX::Long. + +2017-08-05: olly + [C++11] Allow static_assert at the top level (and disallow it right + after template). Fixes issue 1031 reported by Artem V L. + +2017-08-02: wsfulton + Fix incorrectly shown warning when an empty template instantiation was used on a + class used as a base class and that base class was explicitly ignored with %ignore. + Example of the warning which will no longer appear: + + Warning 401: Base class 'Functor< int,int >' has no name as it is an empty + template instantiated with '%template()'. Ignored. + +2017-07-17: fflexo + [Java] #674 Add std_list.i to add support for std::list containers. The Java proxy + extends java.util.AbstractSequentialList and makes the C++ std::list container look + and feel much like a java.util.LinkedList from Java. + +2017-07-07: wsfulton + [Python] Fix display of documented template types when using the autodoc + feature. For example when wrapping: + + %feature("autodoc"); + template struct T {}; + %template(TInteger) T; + + the generated documentation contains: + """Proxy of C++ T< int > class.""" + instead of: + """Proxy of C++ T<(int)> class.""" + and + """__init__(TInteger self) -> TInteger""" + instead of + """__init__(T<(int)> self) -> TInteger""" + +2017-06-27: nihaln + [PHP] Update the OUTPUT Typemap to add return statement to the + PHP Wrapper. + +2017-06-27: nihaln + [PHP] Update the enum and value examples to use the OO wrappers + rather than the flat functions produced with -noproxy. There's + not been a good reason to use -noproxy for since PHP5 OO wrapping + was fixed back in 2005. + +2017-06-23: m7thon + [Python] fix and improve default argument handling: + + 1. Fix negative octals. Currently not handled correctly by `-py3` + (unusual case, but incorrect). + 2. Fix arguments of type "octal + something" (e.g. `0640 | 04`). + Currently drops everything after the first octal. Nasty! + 3. Fix bool arguments "0 + something" (e.g. `0 | 1`) are always + "False" (unusual case, but incorrect). + 4. Remove special handling of "TRUE" and "FALSE" from + `convertValue` since there's no reason these have to match + "true" and "false". + 5. Remove the Python 2 vs. Python 3 distinction based on the + `-py3` flag. Now the same python code is produced for default + arguments for Python 2 and Python 3. For this, octal default + arguments, e.g. 0644, are now wrapped as `int('644', 8)`. This + is required, as Python 2 and Python 3 have incompatible syntax + for octal literals. + + Fixes #707 + +2017-06-21: futatuki + #1004 - Fix ccache-swig executable name to respect configure's --program-prefix and + --program-suffix values if used. + +2017-06-21: tamuratak + [Ruby] #911 - Add std::wstring support. + +2017-06-19: wsfulton + [Python] Fix handling of rich comparisons when wrapping overloaded operators: + + operator< operator<= operator> operator>= operator== operator!= + + Previously a TypeError was always thrown if the type was not correct. NotImplemented + is now returned from these wrapped functions if the type being compared with is + not correct. The subsequent behaviour varies between different versions of Python + and the comparison function being used, but is now consistent with normal Python + behaviour. For example, for the first 4 operator overloads above, a TypeError + 'unorderable types' is thrown in Python 3, but Python 2 will return True or False. + NotImplemented should be returned when the comparison cannot be done, see PEP 207 and + https://docs.python.org/3/library/constants.html#NotImplemented + + Note that the bug was only present when overloaded operators did not also have a + function overload. + + Fixes SF bug #1208 (3441262) and SF patch #303. + + *** POTENTIAL INCOMPATIBILITY *** + +2017-06-17: fabrice102 + [Go] Fix Go callback example. Fixes github #600, #955, #1000. + +2017-06-16: wsfulton + Make sure warning and error messages are not split up by other processes writing to + stdout at the same time. + +2017-06-16: wsfulton + [R] Fix wrapping function pointers containing rvalue and lvalue reference parameters. + +2017-06-13: olly + [Perl] Fix testsuite to work without . in @INC - it was removed in + Perl 5.26 for security reasons, and has also been removed from + older versions in some distros. Fixes #997 reported by lfam. + +2017-06-03: wsfulton + Fix %import on a file containing a file scope %fragment forced inclusion to not + generate the fragment contents as %import should not result in code being generated. + The behaviour is now the same as importing code insertion blocks. + Wrapping FileC.i in the following example will result in no generated code, whereas + previously "#include " was generated: + + // FileA.i + %fragment("", "header") %{ + #include + %} + + %{ + #include + %} + %fragment(""); + + // FileC.i + %import "FileA.i" + + *** POTENTIAL INCOMPATIBILITY *** + +2017-05-26: Volker Diels-Grabsch, vadz + [Java] #842 Extend from java.util.AbstractList<> and implement java.util.RandomAccess for + std::vector wrappers. This notably allows to iterate over wrapped vectors in a natural way. + Note that boxed types are now used in the Java layer when wrapping vector of C primitive + types, for example. This may introduce some subtle incompatibilities due to some + differences in how Java converts boxed types and unboxed types. For example, + + int i=0; + double d1 = i; // ok + Double d2 = i; // error: incompatible types: int cannot be converted to Double + + This can be a problem when calling the add and set functions. A suggested backwards + compatible workaround is to use something like (shown for std::vector: + + #if defined(SWIGJAVA) + // Add in old api that uses non-boxed types + %extend std::vector { + %proxycode %{ + public void add(double x) { + add(Double.valueOf(x)); + } + public void set(int i, double val) { + set(i, Double.valueOf(val)); + } + %} + } + #endif + + %include "std_vector.i" + %template(VectorDouble) std::vector; + + *** POTENTIAL INCOMPATIBILITY *** + +2017-05-30: davidcl + [Scilab] #994 Undefined symbol error when loading in Scilab 6 + +2017-05-25: asibross + [Java] #370 #417 Missing smart pointer handling in Java director extra methods + swigReleaseOwnership() and swigTakeOwnership(). + +2017-05-23: wsfulton + [Java] #230 #759 Fix Java shared_ptr and directors for derived classes java compilation + error. + + For shared_ptr proxy proxy classes, add a protected method swigSetCMemOwn for modifying + the swigCMemOwn and swigCMemOwnDerived member variables which are used by various other + methods for controlling memory ownership. + +2017-05-21: Sghirate + [Java, C#, D] #449 Remove unnecessary use of dynamic_cast in directors to enable + non-RTTI compilation. + +2017-05-21: wsfulton + [Python] #993 Fix handling of default -ve unsigned values, such as: + void f(unsigned = -1U); + +2017-05-20: jschueller + [Python] #991 Fix E731 PEP8 warning: do not assign a lambda expression + +2017-05-16: nihal95 + [PHP] Add %pragma version directive to allow the version of the + extension to be set. Patch #970, fixes #360. + +2017-05-13: yag00 + Patch #975 - Add support for noexcept on director methods. + +2017-04-27: redbrain + Issue #974, Patch #976 - Fix preprocessor handling of macros with commas in a comment. + +2017-04-25: jleveque + [Lua] #959 - Fix Visual Studio C4244 conversion warnings in Lua wrappers. + +2017-04-21: tamuratak + [Ruby] #964 - Add shared_ptr director typemaps. + +2017-04-20: wsfulton + [Ruby] #586, #935 Add assert for invalid NULL type parameter when calling SWIG_Ruby_NewPointerObj. + +2017-04-20: tamuratak + [Ruby] #930, #937 - Fix containers of std::shared_ptr. + Upcasting, const types (eg vector>) and NULL/nullptr support added. + +2017-04-12: smarchetto + [Scilab] New parameter targetversion to specify the Scilab target version (5, 6, ..) for code generation + With Scilab 6 target specified, identifier names truncation is disabled (no longer necessary) + +2017-03-24: tamuratak + [Ruby] Fix #939 - Wrapping std::vector fix due to incorrect null checks + on VALUE obj. + +2017-03-17: vadz + [C#] #947 Add support for std::complex + +2017-03-17: wsfulton + [Go] Fix handling of typedef'd function pointers and typedef'd member function pointers + such as: + + typedef int (*FnPtr_td)(int, int); + int do_op(int x, int y, FnPtr_td op); + +2017-03-16: wsfulton + Add support for member const function pointers such as: + + int fn(short (Funcs::* parm)(bool)) const; + + Also fix parsing of references/pointers and qualifiers to member + pointers such as: + + int fn(short (Funcs::* const parm)(bool)); + int fn(short (Funcs::* & parm)(bool)); + +2017-03-10: wsfulton + Extend C++11 alternate function syntax parsing to support const and noexcept, such as: + + auto sum1(int x, int y) const -> int { return x + y; } + auto sum2(int x, int y) noexcept -> int { return x + y; } + +2017-02-29: tamuratak + [Ruby] #917 - Add Enumerable module to all container class wrappers. It was missing + for std::list, std::multiset, std::unordered_multiset and std::unordered_map. + +2017-02-27: assambar + [C++11] Extend parser to support throw specifier in combination + with override and/or final. + +2017-02-10: tamuratak + [Ruby] #883 - Add support for C++11 hash tables: + std::unordered_map + std::unordered_set + std::unordered_multimap + std::unordered_multiset + +2017-02-08: jcsharp + [C#] #887 Improve std::vector wrapper constructors - + Replace constructor taking ICollection with IEnumerable and also add IEnumerable + constructor to avoid the boxing and unboxing overhead of the original constructor, + when the type parameter is a value type. + +Version 3.0.12 (27 Jan 2017) +============================ + +2017-01-27: wsfulton + [C#] #882 Fix missing filename in error messages when there is a problem + writing out C# files. + +2017-01-27: briancaine + [Guile] #744 Fix compilation errors in Guile wrappers - regression + introduced in swig-3.0.11. + +2017-01-24: andrey-starodubtsev + [Java] Apply #704 - director typemap improvements. + Memory leak fixes, add support for "directorargout" typemap and + add director support to typemaps.i. + +2017-01-24: wsfulton + Enhance %extend to extend a class with template constructors, eg: + + struct Foo { + %extend { + template + Foo(int a, T b) { + ... + } + } + }; + %template(Foo) Foo::Foo; + +2017-01-22: wsfulton + Issue #876 Enhance %extend to extend a class with template methods, eg: + + struct Foo { + %extend { + template + void do_stuff(int a, T b) { + ... + } + } + }; + %template(do_stuff_inst) Foo::do_stuff; + + Similarly for static template methods. + +2017-01-22: kwwette + [Octave] add support for version 4.2 + - The Octave API now uses some C++11 features. It is recommended to use + the mkoctfile program supplied by Octave to compile the SWIG-generated + wrapper code, as mkoctfile will ensure the correct C++ compiler/options + are used. Otherwise, the value of `mkoctfile -p CXX` should be parsed + for any -std=* flags which might be present. + - Octave has dropped support for << and >> operators, so SWIG now + ignores them. + - The Octave error() function now raises C++ exceptions to propagate + Octave errors, so %exception directives may need to be modified. + For convenience the SWIG_RETHROW_OCTAVE_EXCEPTIONS macro can be used + to rethrow any Octave exceptions for Octave itself to handle, e.g.: + + try { + $action // may call error() + } + SWIG_RETHROW_OCTAVE_EXCEPTIONS // error() exceptions are rethrown + catch(...) { + ... // all other exceptions + } + + *** POTENTIAL INCOMPATIBILITY *** + +2017-01-16: wkalinin + [C#] Fix #733 regression introduced in swig-3.0.9. + Missing virtual function override in C# layer when using %import. + +2017-01-16: fschlimb + Fix #813 template symbol name lookup bug when typedef names are the same but in different + namespaces. + +2017-01-15: wsfulton + [C# D Java] + The SWIG library no longer uses the javatype, dtype or cstype typemaps, thereby + completely freeing them up for users to use without having to replicate the library + code that they previously added. The code previously generated by these typemaps + has been replaced by the new %proxycode directive. Their use in the library code + was fairly minimal: + + C# cstype: std_array.i std_map.i std_vector.i + D dtype: std_vector.i + Java javatype: arrays_java.i + +2017-01-14: wsfulton + The %extend directive can now optionally support one of the 'class', 'struct' or 'union' + keywords before the identifier name, for example: + + struct X { ... }; + %extend struct X { ... } + + Previously this had to specified as: + + struct X { ... }; + %extend X { ... } + +2017-01-13: wsfulton + [C# D Java] Add new %proxycode directive which is a macro for %insert("proxycode"). + This is a way of adding pure C#/D/Java code into the appropriate proxy class, eg: + + %extend Proxy2 { + %proxycode %{ + public int proxycode2(int i) { + return i+2; + } + %} + } + + %inline %{ + struct Proxy2 {}; + %} + + There will then be a pure Java/C#/D method called proxycode2 in the Proxy2 class. + +2016-12-31: ajrheading1 + Issue #860 - Remove use of std::unary_function and std::binary_function + which is deprecated in C++11. + +2016-12-30: olly + [PHP7] Register internal 'swig_runtime_data_type_pointer' constant + as "CONST_PERSISTENT" to avoid segmentation fault on module unload. + Fixes #859 reported by Timotheus Pokorra. Thanks also to Javier Torres + for a minimal reproducer. + Version 3.0.11 (29 Dec 2016) ============================ @@ -45,7 +1992,7 @@ Version 3.0.11 (29 Dec 2016) [Python] Fix #446 Python %array_class of carrays.i failed with -builtin option. -2016-12-16: bcaine +2016-12-16: briancaine [Guile] Patch #744 Added support for Guile's native pointer functionality 2016-12-01: wsfulton @@ -11477,7 +13424,7 @@ Version 1.3.23 (November 11, 2004) - Properly qualify type in syntax as 'long(2)' or 'Foo()', this solve old problem with default args, and probably other problems around. However, the default arg problem - was also already solved by William (see bellow). + was also already solved by William (see below). - Fix feature_set and feature_get methods. Before they look from particular to general and keep the first @@ -11685,7 +13632,7 @@ Version 1.3.23 (November 11, 2004) ie, no additional pointer elements are created, and the original 'foo' and 'A.bar' can be used as parameters. - In the case of member fucntion however, still you need + In the case of member function however, still you need to use the special variable Class::_cb_ptr, ie: foobarm(3, a, A.barm_cb_ptr) @@ -20988,7 +22935,7 @@ Version 1.3.7 (September 3, 2001) typedef __name vector; %enddef - An a specific instantiation is created in exactly the same way: + A specific instantiation is created in exactly the same way: %template(intvec) vector; diff --git a/CHANGES.current b/CHANGES.current index 04a7e277b..0f69796f2 100644 --- a/CHANGES.current +++ b/CHANGES.current @@ -4,15 +4,89 @@ See the RELEASENOTES file for a summary of changes in each release. Issue # numbers mentioned below can be found on Github. For more details, add the issue number to the end of the URL: https://github.com/swig/swig/issues/ -Version 3.0.12 (in progress) -============================ +Version 4.1.0 (in progress) +=========================== -2016-12-31: ajrheading1 - Issue #860 - Remove use of std::unary_function and std::binary_function - which is deprecated in C++11. +2021-03-01: xantares, Oliver Buchtala, geographika + #1040 Add support for building SWIG with CMake. See documentation in Windows.html. -2016-12-30: olly - [PHP7] Register internal 'swig_runtime_data_type_pointer' constant - as "CONST_PERSISTENT" to avoid segmentation fault on module unload. - Fixes https://github.com/swig/swig/issues/859 reported by Timotheus - Pokorra - thanks also to Javier Torres for a minimal reproducer. +2021-03-01: vadz + #1952 Fix incorrect warning "Unknown Doxygen command: ." + +2021-02-28: p2k + #969 [Javascript] v8/node - prevent crash calling a constructor without new keyword. + +2021-02-28: alecmev + #405 #1121 [Javascript] Fix OUTPUT typemaps on methods that don't return void. + The output value is appended to the return value. + +2021-02-26: murillo128, wsfulton + #1269 [Javascript] Fix handling of large positive unsigned long and + unsigned long long values. + +2021-02-24: tomleavy, yegorich, tungntpham + #1746 [Javascript] Add support for Node v12. + SWIG support is now for Node v6 and later only. + +2020-10-10: wsfulton + #252 complex can now be used as a C identifier and doesn't give a syntax error. + +2020-10-10: lpsinger + #1770 Correct C complex support. + _Complex is now parsed as a keyword rather than complex as per the C99 standard. + The complex macro is available in the ccomplex.i library file along with other + complex number handling provided by the complex.h header. + +2020-10-07: ZackerySpytz + [Python] #1812 Fix the error handling for the PyObject_GetBuffer() calls in + pybuffer.i. + +2020-10-07: treitmayr + #1824 Add missing space in director method declaration returning + const pointer. + +2020-10-07: adelva1984 + #1859 Remove all (two) exceptions from SWIG executable. + +2020-09-25: wsfulton + [C#, Java] #1874 Add ability to change the modifiers for the interface + generated when using the %interface macros. + + For C# use the 'csinterfacemodifiers' typemap. + For Java use the 'javainterfacemodifiers' typemap. + + For example: + + %typemap(csinterfacemodifiers) X "internal interface" + + +2020-09-24: geefr + [C#] #1868 Fix wchar_t* csvarout typemap for member variable wrappers. + +2020-08-28: wsfulton + [Java] #1862 Fix crashes in swig_connect_director during director class construction + when using the director class from multiple threads - a race condition initialising + block scope static variables. The fix is guaranteed when using C++11, but most + compilers also fix it when using C++03/C++98. + +2020-08-16: wsfulton + [Python] Add missing initializer for member ‘_heaptypeobject::ht_module’ when using + -builtin to complete Python 3.9 support. + +2020-08-16: wsfulton + [Python] Remove PyEval_InitThreads() call for Python 3.7 and later as Python calls + it automatically now. This removes a deprecation warning when using Python 3.9. + +2020-08-15: wsfulton + [Python] All Python examples and tests are written to be Python 2 and Python 3 + compatible, removing the need for 2to3 to run the examples or test-suite. + +2020-08-13: wsfulton + [C#] Add support for void *VOID_INT_PTR for member variables. + +2020-07-29: chrisburr + #1843 [Python] Compilation error fix in SwigPyBuiltin_SetMetaType when using PyPy. + +2020-06-14: ZackerySpytz + #1642 #1809 Fix virtual comparison operators in director classes - remove incorrect + space in the function name, for example, operator= = is now operator==. diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 000000000..b36f441fe --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,161 @@ +cmake_minimum_required (VERSION 3.2) + +if (NOT DEFINED CMAKE_BUILD_TYPE) + set (CMAKE_BUILD_TYPE Release CACHE STRING "Build type") +endif () + +project (swig) + +if (POLICY CMP0074) + cmake_policy (SET CMP0074 NEW) +endif() + +file (STRINGS configure.ac line LIMIT_COUNT 1 REGEX "AC_INIT\\(.*\\)" ) +if (line MATCHES "AC_INIT\\(\\[(.*)\\],[ \t]*\\[(.*)\\],[ \t]*\\[(.*)\\]\\)" ) + set (SWIG_VERSION ${CMAKE_MATCH_2}) + set (PACKAGE_BUGREPORT ${CMAKE_MATCH_3}) +else () + message (SEND_ERROR "Could not parse version from configure.ac") +endif () + +set (SWIG_ROOT ${PROJECT_SOURCE_DIR}) + +set (SWIG_LIB share/swig/${SWIG_VERSION}) + +# Project wide configuration variables +# ------------------------------------ + +set (SWIG_SOURCE_DIR ${SWIG_ROOT}/Source CACHE INTERNAL "Path of swig sources" FORCE) + +set (PACKAGE_NAME swig) +set (PACKAGE_VERSION ${SWIG_VERSION}) + +# Configure +# --------- + +list (APPEND CMAKE_MODULE_PATH ${SWIG_ROOT}/Tools/cmake) + +include (CheckIncludeFiles) +include (CheckIncludeFile) +include (CheckIncludeFileCXX) +include (CheckTypeSize) +include (CheckSymbolExists) +include (CheckFunctionExists) +include (CheckLibraryExists) +include (CheckCSourceCompiles) + +# HACK: didn't get the bool check working for Visual Studio 2008 +if (MSVC) + set(HAVE_BOOL 1) +else() + set (CMAKE_EXTRA_INCLUDE_FILES stdbool.h) + check_type_size ("bool" HAVE_BOOL) + set (CMAKE_EXTRA_INCLUDE_FILES) +endif() + +check_include_file ("inttypes.h" HAVE_INTTYPES_H) +check_include_file ("stddef.h" HAVE_STDDEF_H) +check_include_file ("stdint.h" HAVE_STDINT_H) +check_include_file ("stdio.h" HAVE_STDIO_H) +check_include_file ("stdlib.h" HAVE_STDLIB_H) +check_include_file ("string.h" HAVE_STRING_H) +check_include_file ("strings.h" HAVE_STRINGS_H) +check_include_file ("sys/stat.h" HAVE_SYS_STAT_H) +check_include_file ("sys/types.h" HAVE_SYS_TYPES_H) +check_include_file ("unistd.h" HAVE_UNISTD_H) +check_include_files ("stdlib.h;stdarg.h;string.h;float.h" STDC_HEADERS) + +check_include_file_cxx ("boost/shared_ptr.hpp" HAVE_BOOST) +check_library_exists (dl dlopen "" HAVE_LIBDL) +check_function_exists (popen HAVE_POPEN) + +set (PCRE_REQUIRED_ARG "REQUIRED" CACHE STRING "required arg") +find_package (PCRE ${PCRE_REQUIRED_ARG}) +if (PCRE_FOUND) + set (HAVE_PCRE 1) + include_directories (${PCRE_INCLUDE_DIRS}) +endif() + +if (WIN32) + file (TO_NATIVE_PATH ${CMAKE_INSTALL_PREFIX}/${SWIG_LIB} SWIG_LIB_WIN_UNIX) +endif () +configure_file (${SWIG_ROOT}/Tools/cmake/swigconfig.h.in + ${CMAKE_CURRENT_BINARY_DIR}/Source/Include/swigconfig.h) + +find_package (BISON REQUIRED) + + +# Compiler flags +# -------------- + +include_directories ( + ${SWIG_SOURCE_DIR}/CParse + ${SWIG_SOURCE_DIR}/Include + ${SWIG_SOURCE_DIR}/DOH + ${SWIG_SOURCE_DIR}/Swig + ${SWIG_SOURCE_DIR}/Preprocessor + ${SWIG_SOURCE_DIR}/Modules + ${PROJECT_BINARY_DIR}/Source/Include + ${PROJECT_BINARY_DIR}/Source/CParse + ${PROJECT_SOURCE_DIR}/Source/Doxygen +) + +# generate the parser source code (depends on bison) +file (MAKE_DIRECTORY ${PROJECT_BINARY_DIR}/Source/CParse) + +BISON_TARGET (swig_parser + ${SWIG_SOURCE_DIR}/CParse/parser.y + ${PROJECT_BINARY_DIR}/Source/CParse/parser.c +) + +# generate swigwarn.swg +file (READ ${SWIG_SOURCE_DIR}/Include/swigwarn.h SWIG_WARN_H) +string (REGEX REPLACE "#define WARN([^ \\t]*)[ \\t]*([0-9]+)" "%define SWIGWARN\\1 \\2 %enddef" SWIG_WARN_SWG ${SWIG_WARN_H}) +file (WRITE ${CMAKE_CURRENT_BINARY_DIR}/swigwarn.swg ${SWIG_WARN_SWG}) +set_property (SOURCE ${CMAKE_CURRENT_BINARY_DIR}/swigwarn.swg PROPERTY GENERATED 1) + +# install lib +install (DIRECTORY ${SWIG_ROOT}/Lib/ DESTINATION ${SWIG_LIB}) +install (FILES ${CMAKE_CURRENT_BINARY_DIR}/swigwarn.swg DESTINATION ${SWIG_LIB}) + +# sources +# --------- +file (GLOB DOH_SOURCES ${SWIG_SOURCE_DIR}/DOH/*.c) +file (GLOB CPARSE_SOURCES ${SWIG_SOURCE_DIR}/CParse/*.c) +list (APPEND CPARSE_SOURCES) +file (GLOB PREPROCESSOR_SOURCES ${SWIG_SOURCE_DIR}/Preprocessor/*.c) +file (GLOB CORE_SOURCES ${SWIG_SOURCE_DIR}/Swig/*.c) +file (GLOB DOXYGEN_SOURCES ${SWIG_SOURCE_DIR}/Doxygen/*.cxx) +file (GLOB MODULES_SOURCES ${SWIG_SOURCE_DIR}/Modules/*.cxx) + +add_executable (swig + ${CPARSE_SOURCES} + ${DOH_SOURCES} + ${DOXYGEN_SOURCES} + ${MODULES_SOURCES} + ${CORE_SOURCES} + ${PREPROCESSOR_SOURCES} + ${PROJECT_BINARY_DIR}/Source/Include/swigconfig.h + ${SWIG_SOURCE_DIR}/Include/swigwarn.h + ${PROJECT_BINARY_DIR}/Source/CParse/parser.c + ${PROJECT_BINARY_DIR}/Source/CParse/parser.h +) +if (PCRE_FOUND) + target_link_libraries (swig ${PCRE_LIBRARIES}) +endif () +install (TARGETS swig DESTINATION bin) + +# 'make package-source' creates tarballs +set (CPACK_PACKAGE_NAME ${PACKAGE_NAME}) +set (CPACK_SOURCE_GENERATOR "TGZ;TBZ2") +set (CPACK_SOURCE_IGNORE_FILES "/.git;/build;.*~;${CPACK_SOURCE_IGNORE_FILES}") +set (CPACK_SOURCE_PACKAGE_FILE_NAME ${PACKAGE_NAME}-${PACKAGE_VERSION}) +include (CPack) + +# few tests +enable_testing () +add_test (NAME cmd_version COMMAND swig -version) +add_test (NAME cmd_swiglib COMMAND swig -swiglib) +add_test (NAME cmd_external_runtime COMMAND swig -external-runtime ext_rt.h) +set_tests_properties(cmd_external_runtime PROPERTIES ENVIRONMENT "SWIG_LIB=${PROJECT_SOURCE_DIR}/Lib") + diff --git a/COPYRIGHT b/COPYRIGHT index c3fbbdebd..e6df73ff8 100644 --- a/COPYRIGHT +++ b/COPYRIGHT @@ -19,6 +19,7 @@ Active SWIG Developers: Oliver Buchtala (oliver.buchtala@gmail.com) (Javascript) Neha Narang (narangneha03@gmail.com) (Javascript) Simon Marchetto (simon.marchetto@scilab-enterprises.com) (Scilab) + Zackery Spytz (zspytz@gmail.com) (OCaml, SWIG core) Past SWIG developers and major contributors include: Dave Beazley (dave-swig@dabeaz.com) (SWIG core, Python, Tcl, Perl) @@ -28,7 +29,7 @@ Past SWIG developers and major contributors include: Mikel Bancroft (mikel@franz.com) (Allegro CL) Surendra Singhi (efuzzyone@netscape.net) (CLISP, CFFI) Marcelo Matus (mmatus@acms.arizona.edu) (SWIG core, Python, UTL[python,perl,tcl,ruby]) - Art Yerkes (ayerkes@speakeasy.net) (Ocaml) + Art Yerkes (ayerkes@speakeasy.net) (OCaml) Lyle Johnson (lyle@users.sourceforge.net) (Ruby) Charlie Savage (cfis@interserv.com) (Ruby) Thien-Thi Nguyen (ttn@glug.org) (build/test/misc) @@ -62,7 +63,8 @@ Past SWIG developers and major contributors include: John Lenz (Guile, MzScheme updates, Chicken module, runtime system) Baozeng Ding (Scilab) Ian Lance Taylor (Go) - Vadim Zeitlin (PCRE, Python) + Dmitry Kabak (userdima@gmail.com) (Doxygen) + Vadim Zeitlin (PCRE, Python, Doxygen) Stefan Zager (szager@gmail.com) (Python) Vincent Couvert (Scilab) Sylvestre Ledru (Scilab) diff --git a/Doc/Devel/plan-gsoc-2012.txt b/Doc/Devel/plan-gsoc-2012.txt new file mode 100644 index 000000000..ac764fb2a --- /dev/null +++ b/Doc/Devel/plan-gsoc-2012.txt @@ -0,0 +1,341 @@ + + + + + Project Plan + ============ + SWIG Code Comments + Google Summer of Code 2012 + + +This document describes goals for the Google Summer of Code 2012, +SWIG code documentation project. + +Author: Marko Klopcic, Dmitry Kabak + + +Introduction +============ + +The goal of this project is _not_ to translate _any_ possible Doxygen +formatted comment to JavaDoc or PyDoc, but to make it possible to +translate a subset of comment types in C/C++ code to +JavaDoc and PyDoc. Covering all the Doxygen functionality would be to +complex for the limited time. However, the code must be flexible so +that implementing missing features would not require redesign of the +comment handling code in SWIG. + +There will also be a possibility to add untranslated comments to Java +and Python code (## comments, see Doxygen manual), if the user will +prefer to use Doxygen on the generated code. + +Note: +'-OK-' tick below means that the item is implemented, committed and +working. + +Abbreviations: + JD - JavaDoc + PD - PyDoc + + +Functionality +============= + + Types of comments + ----------------- + + Note: + See 'http://www.stack.nl/~dimitri/doxygen/docblocks.html' for + the detailed description of Doxygen syntax and terms used in this + section. + + 1. -OK- Only JavaDoc (/** */) and Qt (/*! */) styles of comment blocks + will be supported by SWIG translator. + + 2. -OK- The following doc after members will be supported: + + int var; ///< Detailed description after the member + //!< + + int var; //!< Brief description after the member + + int var; ///< Brief description after the member + + + 3. -OK- Only comments before or after declaration/definition will be + supported. Comments with structural commands will be ignored + (warning will be written). (What about writing them to + 'package.info.java' for JD?) + + + Tags + ---- + + This section contains all doxygen tags taken from + http://www.stack.nl/~dimitri/doxygen/commands.html. If a tag is + marked as 'ignored', then the tag is ignored, but the text is copied + to the destination documentation. 'Not implemented' means that the + tag with it's contents is stripped out of the output. + + Doxygen tags: + + All tags: -OK- + + \a - translated to in JD, surrounded with _ in PD + \addindex - ignored + \addtogroup - ignored + \anchor - ignored, not supported by JD and PD + \arg - equivalent to \li + \attention - ignored + \authors, \author - translated to @author in JD, 'Author:' in PD + \b - in JD, surrounded with __ in PD + \brief - ignored + \bug - ignored + \c - translated to in JD, ignored in PD + \callgraph - ignored, not supported by JD and PD + \callergraph - ignored, not supported by JD and PD + \category - ignored, used only in Objective C + \cite - translated to in JD, single quotes in PD + \class - ignored (structural command) + \code - translated to {@code ...} in JD, ignored in PD + \cond - translated to 'Conditional comment: '. Later + SWIG may support definitions of conditions in config file. + \copybrief - ignored. Later SWIG may support this command by + performing copy + \copydetails - ignored. Later SWIG may support this command by + performing copy + \copydoc - ignored. Later SWIG may support this command by + performing copy + \copyright - replaced with text 'Copyright' in PD and PD + \date - ignored + \def - ignored (structural command) + \defgroup - not supported + \deprecated - translated to @deprecated in JD, 'Deprecated:' in PD + \details - ignored + \dir - not supported + \dontinclude - not supported + \dot - not supported. Later SWIG may call dot and produce the graph image + to include in JD and PD + \dotfile - see note for \dot + \e - equivalent \a + \else - see note for \cond + \elseif - see note for \cond + \em - equivalent to \a + \endcode - see note for \code + \endcond - translated to 'End of conditional comment: '. Later + SWIG may support definitions of conditions in config file. + \enddot - see note for \dot + \endhtmlonly - ignored + \endif - see note for \cond + \endinternal - ignored + \endlatexonly - ignored + \endlink - see note for \link + \endmanonly - ignored + \endmsc - see note for \msc + \endrtfonly - ignored + \endverbatim - see note for \verbatim + \endxmlonly - ignored + \enum - ignored (structural command) + \example - translated to 'Example:' in JD and PD + \exception - equivalent to throws, but translates to @exception in JD + \extends - not supported + \f$ - ignored. Later swig may call LATeX to produce bitmaps with formulas + to include in JD and PD + \f[ - see note for \f$ + \f] - see note for \f$ + \f{ - see note for \f$ + \f} - see note for \f$ + \file - ignored (structural command) + \fn - ignored (structural command) + \headerfile - not supported + \hideinitializer - not supported + \htmlinclude - not supported + \htmlonly - ignored + \if - see note for \cond + \ifnot - see note for \cond + \image - translated to in JD only when target=HTML, translated to + 'Image: filename(Title)' + \implements - not supported + \include - not supported + \includelineno - not supported + \ingroup - not supported. Later swig may print group names as plain text + in comments like 'Code group: something' in both JD and PD + \internal - ignored + \invariant - ignored + \interface - ignored (structural command) + \latexonly - ignored + \li - trabslated to
  • in JD, ignored in PD + \line - not supported + \link - translated to {@link ...} in JD, ignored in PD + \mainpage - ignored + \manonly - ignored + \memberof - not supported + \msc - not supported. Later SWIG may call dot and produce the graph image + to include in JD and PD + \mscfile - see note for \msc + \n - prints the new line + \name - ignored + \namespace - included in package-info.java if nspace feature is enabled, + otherwise ignored, ignored in PD + \nosubgrouping - ignored + \note - translated to 'Note:' in both JD and PD + \overload - prints 'This is an overloaded member function, provided for + convenience. It differs from the above function only in what + argument(s) it accepts.' to the output in both JD and PD + \p - equivalent to \c + \package - is kept same in JD (it is already a JD tag), ignored in PD + \page - ignored + \par - translated to

    in JD, 'Title: ...' in PD + \paragraph - ignored + \param - translated to @param in JD, special formatting in PD + \post - ignored + \pre - ignored + \private - ignored + \privatesection - ignored + \property - ignored + \protected - ignored + \protectedsection - ignored + \protocol - ignored (Objective-C tag) + \public - ignored + \publicsection - ignored + \ref - ignored, not supported by JD and PD + \related - ignored + \relates - ignored + \relatedalso - ignored + \relatesalso - ignored + \remark - translated to 'Remarks:' in both JD and PD + \remarks - equivalent to remark + \result - translated to @return in JD, 'Return:' in PD + \return - equivalent to result + \returns - equivalent to result + \retval - ignored + \rtfonly - ignored + \sa - translated to @see in JD, 'See also:' in PD + \section - not supported + \see - equivalent to \sa + \short - equivalent to \brief + \showinitializer - not supported + \since - translated to @since in JD, 'Since:' in PD + \skip - not supported + \skipline - not supported + \snippet - not supported + \struct - ignored (structural command) + \subpage - not supported + \subsection - not supported + \subsubsection - not supported + \tableofcontents - not supported + \test - ignored + \throw - translated to @throws in JD, 'Throws:' in PD + \throws - equivalent to \throw + \todo - translated to 'TODO:' in both JD and PD + \tparam - similar to \arg + \typedef - ignored (structural command) + \union - ignored (structural command) + \until - not supported + \var - ignored (structural command) + \verbatim - translated to {@literal ...} in JD, ignored in PD + \verbinclude - ignored + \version - translated to @version in JD, 'Version:' in PD + \warning - translated to 'Warning:' in both JD and PD + \weakgroup - not supported + \xmlonly - ignored + \xrefitem - ignored + \$ - this and all the others below: these commands insert single char, + it is escaped as HTML char in JD, kept as-is in PD + \@ + \\ + \& + \~ + \< + \> + \# + \% + \" + \. + \:: + +Optional functionality +====================== + +That section describes some complex cases where the current code +does not behave really well. Like a short to-do list of special cases. + +-OK- When translating functions with default parameters in swig to +java, it creates overloaded functions with all the parameters +except the default ones. We need to copy the doxygen comment to +such functions and correct the list of @param tags. + +-OK- In doxygen there is a special tags (and even a special option) +to create links to some code members from the current comment. +Sometimes it needs a type of parameters specified because of the +overloaded functions. And the same linking tags are supported in JD, +but it has a completely different typesystem, so we need to translate +the types of function parameters in comments also. For example: +{@link MyClass#doSomething(const std::string &)} +does not make sense in Java, so the type should be converted. +{@link MyClass#doSomething(String)} + + +Tests +===== + +The following test cases will be implemented: + +-OK- Class comments. + +-OK- Struct comments. +-OK- Enum comments. +-OK- Function comments. +-OK- Var comments. + +-OK- Class attributes, comment before and after declaration. +-OK- Class methods, comment of parameters in function + comment. +-OK- Class methods, comment of parameters + after parameter declaration. + +-OK- Struct attributes, comment before and after declaration. +-OK- Struct methods, comment of parameters in function + comment. +-OK- Struct methods, comment of parameters + after parameter declaration. + +-OK- Enum items JD and Qt style, comment before items +-OK- Enum items JD and Qt style, comment after items + +-OK- Class comment, with all supported tags. +-OK- Class comment, with all doxygen tags, including + ignored ones. + +The list of all tests, in form of shell commands to make it simple +to test project by copying the text below into terminal program. +make doxygen_parsing.cpptest -s +make doxygen_translate.cpptest -s +make doxygen_translate_all_tags.cpptest -s +make doxygen_basic_translate.cpptest -s +make doxygen_basic_notranslate.cpptest -s +make doxygen_translate_links.cpptest -s +make doxygen_tricky_constructs.cpptest -s + + +Refactoring +=========== + +All the code in directory _Doxygen_ should be refactored: +-OK- all methods should be class members +-OK- most static methods should be normal members +-OK- replace C arrays of strings and sequential searches with STL data + structures and algorithms. +-OK- use singletons instead of class instantiaion for each comment found. + + +Documentation +============= + +SWIG documentation will contain: +-OK- command line options +-OK- list of implemented features (types and placements of comments) +-OK- list of unimplemented features (types and placements of comments) +-OK- list of tags and their translations (all Doxygen tags). +-OK- some amount of debugging and development information + diff --git a/Doc/Devel/runtime.txt b/Doc/Devel/runtime.txt index f88edf767..ae9c83275 100644 --- a/Doc/Devel/runtime.txt +++ b/Doc/Devel/runtime.txt @@ -57,7 +57,7 @@ Alternatively, if the language supports modules, a module named named "type_table" SWIG_TYPE_TABLE_NAME can be created inside it. The most common approach is to store the mod pointer in some global variable in the target language, but if the language provides an alternative place to store data -(like the chicken module), then that is good too. +then that is good too. The way the code is set up, SetModule should only be called when GetModule returns NULL, and if SetModule is called a second time, the behavior is @@ -105,7 +105,7 @@ Standard Functions These functions are not required and their API is not formalized, but almost all language modules implement them for consistency across languages. Throughout this discussion, I will use LangType to represent the underlying language type -(C_word in chicken, Scheme_Object * in mzscheme, PyObject * in python, etc) +(Scheme_Object * in mzscheme, PyObject * in python, etc) diff --git a/Doc/Devel/tree.html b/Doc/Devel/tree.html index 73a49ed55..5bb4b6a1e 100644 --- a/Doc/Devel/tree.html +++ b/Doc/Devel/tree.html @@ -236,7 +236,7 @@ The following functions can be used to help debug SWIG parse trees.
    Prints the tag-structure of the parse tree to standard output. node is the top-level parse tree node. prefix is -a string prefix thats added to the start of each line. Normally, you would specify the empty string or NIL for prefix. +a string prefix that's added to the start of each line. Normally, you would specify the empty string or NIL for prefix. This function is called by the -debug-tags option to SWIG.
    diff --git a/Doc/Manual/Allegrocl.html b/Doc/Manual/Allegrocl.html
    index ddb6fba55..4069ecd8b 100644
    --- a/Doc/Manual/Allegrocl.html
    +++ b/Doc/Manual/Allegrocl.html
    @@ -8,7 +8,7 @@
     
     
     
    -

    18 SWIG and Allegro Common Lisp

    +

    20 SWIG and Allegro Common Lisp

      @@ -129,16 +129,16 @@ It is significant to note that, while this is a vendor-specific module, we would like to acknowledge the current and ongoing work by developers in the open source lisp community that are working on similar interfaces to implementation-independent -foreign function interfaces (UFFI or CFFI, for example). Such +foreign function interfaces (CFFI, for example). Such work can only benefit the lisp community, and we would not be unhappy to see some enterprising folk use this work to add to it.

      -

      18.1 Basics

      +

      20.1 Basics

      -

      18.1.1 Running SWIG

      +

      20.1.1 Running SWIG

      @@ -155,7 +155,7 @@ SWIG directives. SWIG can be furnished with a header file, but an interface can also be generated without library headers by supplying a simple text file--called the interface file, which is typically named with a .i extension--containing any foreign declarations of -identifiers you wish to use. The most common approach is to use a an +identifiers you wish to use. The most common approach is to use an interface file with directives to parse the needed headers. A straight parse of library headers will result in usable code, but SWIG directives provides much freedom in how a user might tailor the @@ -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.

      -

      18.1.2 Command Line Options

      +

      20.1.2 Command Line Options

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

      -

      18.1.3 Inserting user code into generated files

      +

      20.1.3 Inserting user code into generated files

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

      -

      18.2 Wrapping Overview

      +

      20.2 Wrapping Overview

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

      -

      18.2.1 Function Wrapping

      +

      20.2.1 Function Wrapping

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

    -

    18.2.2 Foreign Wrappers

    +

    20.2.2 Foreign Wrappers

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

    -

    18.2.3 FFI Wrappers

    +

    20.2.3 FFI Wrappers

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

    -

    18.2.4 Non-overloaded Defuns

    +

    20.2.4 Non-overloaded Defuns

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

    -

    18.2.5 Overloaded Defuns

    +

    20.2.5 Overloaded Defuns

    - In the case of overloaded functions, mulitple layers are + In the case of overloaded functions, multiple layers are generated. First, all the overloads for a given name are separated out into groups based on arity, and are wrapped in defmethods. Each method calls a distinct wrapper function, but are @@ -622,7 +622,7 @@ char *xxx(); can be manipulated via the lout typemap.

    -

    18.2.6 What about constant and variable access?

    +

    20.2.6 What about constant and variable access?

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

    -

    18.2.7 Object Wrapping

    +

    20.2.7 Object Wrapping

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

    -

    18.3 Wrapping Details

    +

    20.3 Wrapping Details

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

    -

    18.3.1 Namespaces

    +

    20.3.1 Namespaces

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

    -

    18.3.2 Constants

    +

    20.3.2 Constants

    @@ -803,7 +803,7 @@ namespace car { not use the -nocwrap command-line option.

    -

    18.3.3 Variables

    +

    20.3.3 Variables

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

    18.3.4 Enumerations

    +

    20.3.4 Enumerations

    @@ -957,7 +957,7 @@ EXPORT const int ACL_ENUM___FOO3__SWIG_0 = FOO3; -

    18.3.5 Arrays

    +

    20.3.5 Arrays

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

    18.3.6 Classes and Structs and Unions (oh my!)

    +

    20.3.6 Classes and Structs and Unions (oh my!)

    -

    18.3.6.1 CLOS wrapping of

    +

    20.3.6.1 CLOS wrapping of

    @@ -1123,7 +1123,7 @@ namespace BAR { integer values.

    -

    18.3.6.2 CLOS Inheritance

    +

    20.3.6.2 CLOS Inheritance

    @@ -1136,7 +1136,7 @@ namespace BAR { parameter.

    -

    18.3.6.3 Member fields and functions

    +

    20.3.6.3 Member fields and functions

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

    -

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

    +

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

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

    -

    18.3.7 Templates

    +

    20.3.7 Templates

    -

    18.3.7.1 Generating wrapper code for templates

    +

    20.3.7.1 Generating wrapper code for templates

    @@ -1187,7 +1187,7 @@ them. This is done via the directive.

    -

    18.3.7.2 Implicit Template instantiation

    +

    20.3.7.2 Implicit Template instantiation

    @@ -1197,7 +1197,7 @@ to include these templated classes in the foreign-type and CLOS class schema.

    -

    18.3.8 Typedef, Templates, and Synonym Types

    +

    20.3.8 Typedef, Templates, and Synonym Types

    @@ -1239,7 +1239,7 @@ int zzz(A *inst = 0); /* return inst->x + inst->y */ We resolve this issue, by noting synonym relationships between types while generating the interface. A Primary type is selected (more on this below) from the candidate list of synonyms. For - all other synonyms, intead of generating a distinct CLOS class + all other synonyms, instead of generating a distinct CLOS class definition, we generate a form that expands to:

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

    18.3.8.1 Choosing a primary type

    +

    20.3.8.1 Choosing a primary type

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

    18.3.9 Function overloading/Parameter defaulting

    +

    20.3.9 Function overloading/Parameter defaulting

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

    18.3.10 Operator wrapping and Operator overloading

    +

    20.3.10 Operator wrapping and Operator overloading

    @@ -1607,7 +1607,7 @@ opoverload> -

    18.3.11 Varargs

    +

    20.3.11 Varargs

    @@ -1628,7 +1628,7 @@ opoverload> with other ways such functions can be wrapped.

    -

    18.3.12 C++ Exceptions

    +

    20.3.12 C++ Exceptions

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

    -

    18.3.13 Pass by value, pass by reference

    +

    20.3.13 Pass by value, pass by reference

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

    -

    18.4 Typemaps

    +

    20.4 Typemaps

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

    -

    18.4.1 Code Generation in the C++ Wrapper

    +

    20.4.1 Code Generation in the C++ Wrapper

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

    18.4.1.1 IN Typemap

    +

    20.4.1.1 IN Typemap

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

    18.4.1.2 OUT Typemap

    +

    20.4.1.2 OUT Typemap

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

    18.4.1.3 CTYPE Typemap

    +

    20.4.1.3 CTYPE Typemap

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

    -

    18.4.2 Code generation in Lisp wrappers

    +

    20.4.2 Code generation in Lisp wrappers

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

    -

    18.4.2.1 LIN Typemap

    +

    20.4.2.1 LIN Typemap

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

    18.4.2.2 LOUT Typemap

    +

    20.4.2.2 LOUT Typemap

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

    18.4.2.3 FFITYPE Typemap

    +

    20.4.2.3 FFITYPE Typemap

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

    18.4.2.4 LISPTYPE Typemap

    +

    20.4.2.4 LISPTYPE Typemap

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

    18.4.2.5 LISPCLASS Typemap

    +

    20.4.2.5 LISPCLASS Typemap

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

    18.4.3 Modifying SWIG behavior using typemaps

    +

    20.4.3 Modifying SWIG behavior using typemaps

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

    18.5 Identifier Converter functions

    +

    20.5 Identifier Converter functions

    -

    18.5.1 Creating symbols in the lisp environment

    +

    20.5.1 Creating symbols in the lisp environment

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

    -

    18.5.2 Existing identifier-converter functions

    +

    20.5.2 Existing identifier-converter functions

    Two basic identifier routines have been defined. -

    18.5.2.1 identifier-convert-null

    +

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

    -

    18.5.2.2 identifier-convert-lispify

    +

    20.5.2.2 identifier-convert-lispify

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

    -

    18.5.2.3 Default identifier to symbol conversions

    +

    20.5.2.3 Default identifier to symbol conversions

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

    -

    18.5.3 Defining your own identifier-converter

    +

    20.5.3 Defining your own identifier-converter

    @@ -2128,7 +2128,7 @@ indicating the number of arguments passed to the routine indicated by this identifier.

    -

    18.5.4 Instructing SWIG to use a particular identifier-converter

    +

    20.5.4 Instructing SWIG to use a particular identifier-converter

    diff --git a/Doc/Manual/Android.html b/Doc/Manual/Android.html index b295b5e04..da475e9a4 100644 --- a/Doc/Manual/Android.html +++ b/Doc/Manual/Android.html @@ -6,7 +6,7 @@ -

    19 SWIG and Android

    +

    22 SWIG and Android

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

      19.1 Overview

      +

      22.1 Overview

      @@ -41,14 +41,14 @@ Everything in the Java chapter applies to generatin This chapter contains a few Android specific notes and examples.

      -

      19.2 Android examples

      +

      22.2 Android examples

      -

      19.2.1 Examples introduction

      +

      22.2.1 Examples introduction

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

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

      -

      19.2.2 Simple C example

      +

      22.2.2 Simple C example

      @@ -326,7 +326,7 @@ include $(BUILD_SHARED_LIBRARY)

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

    @@ -399,7 +399,7 @@ Run the app again and this time you will see the output pictured below, showing
    Android screenshot of SwigSimple example
    -

    19.2.3 C++ class example

    +

    22.2.3 C++ class example

    @@ -409,7 +409,7 @@ All the steps required to compile and use a simple hierarchy of classes for shap

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

    @@ -747,7 +747,7 @@ Run the app to see the result of calling the C++ code from Java:
    Android screenshot of SwigClass example
    -

    19.2.4 Other examples

    +

    22.2.4 Other examples

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

    -

    19.3 C++ STL

    +

    22.3 C++ STL

    diff --git a/Doc/Manual/Arguments.html b/Doc/Manual/Arguments.html index 9dae9fdcd..3d633f336 100644 --- a/Doc/Manual/Arguments.html +++ b/Doc/Manual/Arguments.html @@ -7,7 +7,7 @@ -

    10 Argument Handling

    +

    13 Argument Handling

      @@ -32,7 +32,7 @@

      -In Chapter 3, SWIG's treatment of basic datatypes and pointers was +In Chapter 5, SWIG's treatment of basic datatypes and pointers was described. In particular, primitive types such as int and double are mapped to corresponding types in the target language. For everything else, pointers are used to refer to @@ -43,7 +43,7 @@ return multiple values through the arguments of a function. This chapter describes some of the techniques for doing this.

      -

      10.1 The typemaps.i library

      +

      13.1 The typemaps.i library

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

      -

      10.1.1 Introduction

      +

      13.1.1 Introduction

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

    -

    10.1.2 Input parameters

    +

    13.1.2 Input parameters

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

    10.1.3 Output parameters

    +

    13.1.3 Output parameters

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

    10.1.4 Input/Output parameters

    +

    13.1.4 Input/Output parameters

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

    -

    10.1.5 Using different names

    +

    13.1.5 Using different names

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

    -

    10.2 Applying constraints to input values

    +

    13.2 Applying constraints to input values

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

    -

    10.2.1 Simple constraint example

    +

    13.2.1 Simple constraint example

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

    -

    10.2.2 Constraint methods

    +

    13.2.2 Constraint methods

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

    10.2.3 Applying constraints to new datatypes

    +

    13.2.3 Applying constraints to new datatypes

    diff --git a/Doc/Manual/CCache.html b/Doc/Manual/CCache.html index d23b0cb2f..1a94709ae 100644 --- a/Doc/Manual/CCache.html +++ b/Doc/Manual/CCache.html @@ -7,7 +7,7 @@ -

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

    +

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

    -

    17.14 HISTORY

    +

    21.14 HISTORY

    -ccache was inspired by the compilercache shell script script written +ccache was inspired by the compilercache shell script written by Erik Thiele and I would like to thank him for an excellent piece of work. See http://www.erikyyy.de/compilercache/ @@ -423,7 +423,7 @@ I wrote ccache because I wanted to get a bit more speed out of a compiler cache and I wanted to remove some of the limitations of the shell-script version.

    -

    17.15 DIFFERENCES FROM COMPILERCACHE

    +

    21.15 DIFFERENCES FROM COMPILERCACHE

    @@ -441,7 +441,7 @@ are:

  • ccache avoids a double call to cpp on a cache miss

    -

    17.16 CREDITS

    +

    21.16 CREDITS

    @@ -453,12 +453,12 @@ Thanks to the following people for their contributions to ccache

  • Paul Russell for many suggestions and the debian packaging

    -

    17.17 AUTHOR

    +

    21.17 AUTHOR

    ccache was written by Andrew Tridgell -http://samba.org/~tridge/. +https://www.samba.org/~tridge/. ccache was adapted to create ccache-swig for use with SWIG by William Fulton.

    If you wish to report a problem or make a suggestion then please email diff --git a/Doc/Manual/CPlusPlus11.html b/Doc/Manual/CPlusPlus11.html index 4d4261cd7..e5d7fbc2d 100644 --- a/Doc/Manual/CPlusPlus11.html +++ b/Doc/Manual/CPlusPlus11.html @@ -32,6 +32,7 @@

  • Type alias and alias templates
  • Unrestricted unions
  • Variadic templates +
  • New character literals
  • New string literals
  • User-defined literals
  • Thread-local storage @@ -42,6 +43,7 @@
  • Exception specifications and noexcept
  • Control and query object alignment
  • Attributes +
  • Methods with ref-qualifiers
  • Standard library changes
      @@ -334,6 +336,10 @@ int i; int j; decltype(i+j) k; // syntax error
  • +

    SWIG does not support auto as a type specifier for variables, only +for specifying the return type of lambdas +and functions.

    +

    7.2.7 Range-based for-loop

    @@ -713,7 +719,24 @@ 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

    +

    7.2.19 New character literals

    + + +

    +C++11 adds support for UCS-2 and UCS-4 character literals. +These character literals are preceded by either 'u' or 'U'. +

    + +
    +char16_t a = u'a';
    +char32_t b = U'b';
    +
    + +

    +Compatibility note: SWIG-4.0.0 was the first version to support these Universal Coded Character Set (UCS) character literals. +

    + +

    7.2.20 New string literals

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

    @@ -743,7 +766,7 @@ Note: There is a bug currently where SWIG's preprocessor incorrectly parses an o inside raw string literals.

    -

    7.2.20 User-defined literals

    +

    7.2.21 User-defined literals

    @@ -810,7 +833,7 @@ OutputType var2 = 1234_suffix; OutputType var3 = 3.1416_suffix; -

    7.2.21 Thread-local storage

    +

    7.2.22 Thread-local storage

    SWIG correctly parses the thread_local keyword. For example, variables @@ -830,7 +853,7 @@ A variable will be thread local if accessed from different threads from the targ same way that it will be thread local if accessed from C++ code.

    -

    7.2.22 Explicitly defaulted functions and deleted functions

    +

    7.2.23 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. @@ -868,16 +891,17 @@ This is a C++ compile time check and SWIG does not make any attempt to detect if 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

    +

    7.2.24 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

    +

    7.2.25 Static assertions

    -SWIG correctly parses the new static_assert declarations. +SWIG correctly parses the new static_assert declarations (though 3.0.12 and earlier +had a bug which meant this wasn't accepted at file scope). This is a C++ compile time directive so there isn't anything useful that SWIG can do with it.

    @@ -888,7 +912,7 @@ struct Check { }; -

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

    +

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

    @@ -909,7 +933,7 @@ const int SIZE = sizeof(A::member); // does not work with C++03. Okay with C++11 8 -

    7.2.26 Exception specifications and noexcept

    +

    7.2.27 Exception specifications and noexcept

    @@ -925,7 +949,7 @@ int noex2(int) noexcept(true); int noex3(int, bool) noexcept(false); -

    7.2.27 Control and query object alignment

    +

    7.2.28 Control and query object alignment

    @@ -957,7 +981,7 @@ Use the preprocessor to work around this for now: -

    7.2.28 Attributes

    +

    7.2.29 Attributes

    @@ -970,6 +994,104 @@ int [[attr1]] i [[attr2, attr3]]; [[noreturn, nothrow]] void f [[noreturn]] (); + +

    7.2.30 Methods with ref-qualifiers

    + + +

    +C++11 non-static member functions can be declared with ref-qualifiers. +Member functions declared with a & lvalue ref-qualifiers are wrapped like any other function without ref-qualifiers. +Member functions declared with a && rvalue ref-qualifiers are ignored by default +as they are unlikely to be required from non-C++ languages where the concept of rvalue-ness +for the implied *this pointer does not apply. +The warning is hidden by default, but can be displayed as described in the section on Enabling extra warnings. +

    + +

    +Consider: +

    + +
    +struct RQ {
    +  void m1(int x) &;
    +  void m2(int x) &&;
    +};
    +
    + +

    +The only wrapped method will be the lvalue ref-qualified method m1 +and if SWIG is run with the -Wextra command-line option, the following warning will be issued indicating m2 is not wrapped: +

    + +
    +
    +example.i:7: Warning 405: Method with rvalue ref-qualifier m2(int) && ignored.
    +
    +
    + +

    +If you unignore the method as follows, wrappers for m2 will be generated: +

    + +
    +%feature("ignore", "0") RQ::m2(int x) &&;
    +struct RQ {
    +  void m1(int x) &;
    +  void m2(int x) &&;
    +};
    +
    + +

    +Inspection of the generated C++ code, will show that std::move is used on the instance +of the RQ * class: +

    + +
    +  RQ *arg1 = (RQ *) 0 ;
    +  int arg2 ;
    +
    +  arg1 = ...marshalled from target language...
    +  arg2 = ...marshalled from target language...
    +
    +  std::move(*arg1).m2(arg2);
    +
    + +

    +This will compile but when run, the move effects may not be what you want. +As stated earlier, rvalue ref-qualifiers aren't really applicable outside the world of C++. +However, if you really know what you are doing, full control over the call to the method is +possible via the low-level "action" feature. +This feature completely replaces the call to the underlying function, that is, the last line in the snippet of code above. +

    + +
    +%feature("ignore", "0") RQ::m2(int x) &&;
    +%feature("action") RQ::m2(int x) && %{
    +  RQ().m2(arg2);
    +%}
    +struct RQ {
    +  void m1(int x) &;
    +  void m2(int x) &&;
    +};
    +
    + +

    +resulting in: +

    + +
    +  RQ *arg1 = (RQ *) 0 ;
    +  int arg2 ;
    +
    +  arg1 = ...marshalled from target language...
    +  arg2 = ...marshalled from target language...
    +
    +  RQ().m2(arg2);
    +
    + +

    +Compatibility note: SWIG-4.0.0 was the first version to support ref-qualifiers. +

    7.3 Standard library changes

    @@ -994,7 +1116,8 @@ Variadic template support requires further work to provide substantial tuple wra

    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. +These are not available in all target languages. +Any missing support can in principle be easily implemented by adapting the current STL containers.

    7.3.4 Regular expressions

    @@ -1175,5 +1298,6 @@ 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/CPlusPlus14.html b/Doc/Manual/CPlusPlus14.html new file mode 100644 index 000000000..b162c7818 --- /dev/null +++ b/Doc/Manual/CPlusPlus14.html @@ -0,0 +1,60 @@ + + + +SWIG and C++14 + + + + + +

    8 SWIG and C++14

    + + + + + + +

    8.1 Introduction

    + + +

    This chapter gives you a brief overview about the SWIG +implementation of the C++14 standard. +There isn't much in C++14 that affects SWIG, however, work has only just begun on adding +C++14 support. +

    + +

    +Compatibility note: SWIG-4.0.0 is the first version to support any C++14 features. +

    + +

    8.2 Core language changes

    + + +

    8.2.1 Binary integer literals

    + + +

    +C++14 added binary integer literals and SWIG supports these. +Example: +

    + +
    +
    +int b = 0b101011;
    +
    +
    + +

    8.3 Standard library changes

    + + + + diff --git a/Doc/Manual/CPlusPlus17.html b/Doc/Manual/CPlusPlus17.html new file mode 100644 index 000000000..a2346660a --- /dev/null +++ b/Doc/Manual/CPlusPlus17.html @@ -0,0 +1,109 @@ + + + +SWIG and C++17 + + + + + +

    9 SWIG and C++17

    + + + + + + +

    9.1 Introduction

    + + +

    This chapter gives you a brief overview about the SWIG +implementation of the C++17 standard. +There isn't much in C++17 that affects SWIG, however, work has only just begun on adding +C++17 support. +

    + +

    +Compatibility note: SWIG-4.0.0 is the first version to support any C++17 features. +

    + +

    9.2 Core language changes

    + + +

    9.2.1 Nested namespace definitions

    + + +

    +C++17 offers a more concise syntax for defining namespaces. +SWIG has support for nested namespace definitions such as: +

    + +
    +
    +namespace A::B::C {
    +  ...
    +}
    +
    +
    + +

    +This is the equivalent to the C++98 namespace definitions: +

    + +
    +
    +namespace A {
    +  namespace B {
    +    namespace C {
    +      ...
    +    }
    +  }
    +}
    +
    +
    + +

    9.2.2 UTF-8 character literals

    + + +

    +C++17 added UTF-8 (u8) character literals. +These are of type char. +Example: +

    + +
    +
    +char a = u8'a';
    +
    +
    + +

    9.2.3 Hexadecimal floating literals

    + + +

    +C++17 added hexadecimal floating literals. +For example: +

    + +
    +
    +double f = 0xF.68p2;
    +
    +
    + +

    9.3 Standard library changes

    + + + + diff --git a/Doc/Manual/CPlusPlus20.html b/Doc/Manual/CPlusPlus20.html new file mode 100644 index 000000000..0a8b0027f --- /dev/null +++ b/Doc/Manual/CPlusPlus20.html @@ -0,0 +1,42 @@ + + + +SWIG and C++20 + + + + + +

    10 SWIG and C++20

    + + + + + + +

    10.1 Introduction

    + + +

    This chapter gives you a brief overview about the SWIG +implementation of the C++20 standard. +Work has only just begun on adding C++20 support. +

    + +

    +Compatibility note: SWIG-4.1.0 is the first version to support any C++20 features. +

    + +

    10.2 Core language changes

    + + +

    10.3 Standard library changes

    + + + + diff --git a/Doc/Manual/CSharp.html b/Doc/Manual/CSharp.html index 5be63a340..fe8f7c4bd 100644 --- a/Doc/Manual/CSharp.html +++ b/Doc/Manual/CSharp.html @@ -6,7 +6,7 @@ -

    20 SWIG and C#

    +

    23 SWIG and C#

    @@ -54,7 +55,7 @@ -

    20.1 Introduction

    +

    23.1 Introduction

    @@ -63,18 +64,24 @@ The wrapper code implementation uses C# and the Platform Invoke (PInvoke) interf The PInvoke interface has been chosen over Microsoft's Managed C++ interface as it is portable to both Microsoft Windows and non-Microsoft platforms. PInvoke is part of the ECMA/ISO C# specification. It is also better suited for robust production environments due to the Managed C++ flaw called the -Mixed DLL Loading Problem. +Mixed DLL Loading Problem. SWIG C# works equally well on non-Microsoft operating systems such as Linux, Solaris and Apple Mac using -Mono and Portable.NET. +Mono. +

    + +

    +SWIG 3 and later requires .NET 2.0 at a minimum. +There are some minor exceptions, where the minimum required is .NET 4.0. +This is when using the std::complex and std::list STL containers.

    To get the most out of this chapter an understanding of interop is required. -The Microsoft Developer Network (MSDN) has a good reference guide in a section titled "Interop Marshaling". -Monodoc, available from the Mono project, has a very useful section titled Interop with native libraries. +The Microsoft Developer Network (MSDN) has a good reference guide in a section titled "Interop Marshaling". +Monodoc, available from the Mono project, has a very useful section titled Interop with native libraries.

    -

    20.1.1 SWIG 2 Compatibility

    +

    23.1.1 SWIG 2 Compatibility

    @@ -82,7 +89,7 @@ In order to minimize name collisions between names generated based on input to S

    -

    20.1.2 Additional command line options

    +

    23.1.2 Additional command line options

    @@ -134,7 +141,7 @@ Note that the file extension (.cs) will not be automatically added and needs to Due to possible compiler limits it is not advisable to use -outfile for large projects.

    -

    20.2 Differences to the Java module

    +

    23.2 Differences to the Java module

    @@ -231,8 +238,9 @@ javacode -> cscode javaimports -> csimports javabody -> csbody javafinalize -> csfinalize -javadestruct -> csdestruct -javadestruct_derived -> csdestruct_derived +javadestruct -> csdisposing and csdispose +javadestruct_derived -> csdisposing_derived and csdispose_derived +javainterfacemodifiers -> csinterfacemodifiers javainterfacecode -> csinterfacecode

    @@ -555,7 +563,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 C# compilers (Mono or Microsoft) can be detected from within a Cygwin or Mingw environment if installed in your path. -

    20.3 Void pointers

    +

    23.3 Void pointers

    @@ -573,7 +581,7 @@ void * f(void *v); -

    20.4 C# Arrays

    +

    23.4 C# Arrays

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

    -

    20.4.1 The SWIG C arrays library

    +

    23.4.1 The SWIG C arrays library

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

    20.4.2 Managed arrays using P/Invoke default array marshalling

    +

    23.4.2 Managed arrays using P/Invoke default array marshalling

    @@ -642,7 +650,7 @@ passing a direct reference as described in the next section.

    For more information on the subject, see the -Default Marshaling for Arrays article +Default Marshaling for Arrays article on MSDN.

    @@ -677,7 +685,7 @@ As a result, we get the following method in the module class:
     public static void myArrayCopy(int[] sourceArray, int[] targetArray, int nitems) {
    -    examplePINVOKE.myArrayCopy(sourceArray, targetArray, nitems);
    +  examplePINVOKE.myArrayCopy(sourceArray, targetArray, nitems);
     }
     
    @@ -749,7 +757,7 @@ and intermediary class method -

    20.4.3 Managed arrays using pinning

    +

    23.4.3 Managed arrays using pinning

    @@ -762,7 +770,7 @@ another thread may produce enough garbage to trigger garbage collection.

    -For more information, see the fixed statement in the C# language reference. +For more information, see the fixed statement in the C# language reference.

    @@ -844,7 +852,7 @@ public static extern void myArrayCopy(global::System.IntPtr jarg1, global::Syste -

    20.5 C# Exceptions

    +

    23.5 C# Exceptions

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

    -

    20.5.1 C# exception example using "check" typemap

    +

    23.5.1 C# exception example using "check" typemap

    @@ -997,9 +1005,9 @@ When the following C# code is executed:

     public class runme {
    -    static void Main() {
    -      example.positivesonly(-1);
    -    }
    +  static void Main() {
    +    example.positivesonly(-1);
    +  }
     }
     
    @@ -1123,7 +1131,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.

    -

    20.5.2 C# exception example using %exception

    +

    23.5.2 C# exception example using %exception

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

    20.5.3 C# exception example using exception specifications

    +

    23.5.3 C# exception example using exception specifications

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

    -

    20.5.4 Custom C# ApplicationException example

    +

    23.5.4 Custom C# ApplicationException example

    @@ -1378,7 +1386,7 @@ try { -

    20.6 C# Directors

    +

    23.6 C# Directors

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

    -

    20.6.1 Directors example

    +

    23.6.1 Directors example

    @@ -1512,7 +1520,7 @@ CSharpDerived - UIntMethod(123) -

    20.6.2 Directors implementation

    +

    23.6.2 Directors implementation

    @@ -1574,9 +1582,9 @@ public class Base : global::System.IDisposable { private void SwigDirectorConnect() { if (SwigDerivedClassHasMethod("UIntMethod", swigMethodTypes0)) - swigDelegate0 = new SwigDelegateBase_0(SwigDirectorUIntMethod); + swigDelegate0 = new SwigDelegateBase_0(SwigDirectorMethodUIntMethod); if (SwigDerivedClassHasMethod("BaseBoolMethod", swigMethodTypes1)) - swigDelegate1 = new SwigDelegateBase_1(SwigDirectorBaseBoolMethod); + swigDelegate1 = new SwigDelegateBase_1(SwigDirectorMethodBaseBoolMethod); examplePINVOKE.Base_director_connect(swigCPtr, swigDelegate0, swigDelegate1); } @@ -1586,11 +1594,11 @@ public class Base : global::System.IDisposable { return hasDerivedMethod; } - private uint SwigDirectorUIntMethod(uint x) { + private uint SwigDirectorMethodUIntMethod(uint x) { return UIntMethod(x); } - private void SwigDirectorBaseBoolMethod(global::System.IntPtr b, bool flag) { + private void SwigDirectorMethodBaseBoolMethod(global::System.IntPtr b, bool flag) { BaseBoolMethod(new Base(b, false), flag); } @@ -1619,9 +1627,9 @@ It uses a support method, SwigDerivedClassHasMethod(), which simply use BaseBoolMethod, with the list of required parameter types, exists in a subclass. If it does not exist, the delegate is not initialised as there is no need for unmanaged code to call back into managed C# code. However, if there is an overridden method in any subclass, the delegate is required. -It is then initialised to the SwigDirectorBaseBoolMethod which in turn will call BaseBoolMethod if invoked. +It is then initialised to the SwigDirectorMethodBaseBoolMethod which in turn will call BaseBoolMethod if invoked. The delegate is not initialised to the BaseBoolMethod directly as quite often types will need marshalling from the unmanaged type -to the managed type in which case an intermediary method (SwigDirectorBaseBoolMethod) is required for the marshalling. +to the managed type in which case an intermediary method (SwigDirectorMethodBaseBoolMethod) is required for the marshalling. In this case, the C# Base class needs to be created from the unmanaged IntPtr type.

    @@ -1720,7 +1728,7 @@ before SWIG parses the Base class will change all the delegates to internal< -

    20.6.3 Director caveats

    +

    23.6.3 Director caveats

    @@ -1768,11 +1776,11 @@ However, a call from C# to CSharpDefaults.DefaultMethod() will of cours should pass the call on to CSharpDefaults.DefaultMethod(int)using the C++ default value, as shown above.

    -

    20.7 Multiple modules

    +

    23.7 Multiple modules

    -When using multiple modules it is is possible to compile each SWIG generated wrapper +When using multiple modules it is possible to compile each SWIG generated wrapper into a different assembly. However, by default the generated code may not compile if generated classes in one assembly use generated classes in another assembly. @@ -1803,7 +1811,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.

    -

    20.8 C# Typemap examples

    +

    23.8 C# Typemap examples

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

    20.8.1 Memory management when returning references to member variables

    +

    23.8.1 Memory management when returning references to member variables

    @@ -1827,7 +1835,7 @@ Consider the following C++ code:

     struct Wheel {
       int size;
    -  Wheel(int sz) : size(sz) {}
    +  Wheel(int sz = 0) : size(sz) {}
     };
     
     class Bike {
    @@ -1846,12 +1854,12 @@ 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
    -      global::System.GC.Collect();
    -      global::System.GC.WaitForPendingFinalizers();
    -      global::System.Console.WriteLine("wheel size: " + wheel.size);
    +  Wheel wheel = new Bike(10).getWheel();
    +  Console.WriteLine("wheel size: " + wheel.size);
    +  // Simulate a garbage collection
    +  global::System.GC.Collect();
    +  global::System.GC.WaitForPendingFinalizers();
    +  global::System.Console.WriteLine("wheel size: " + wheel.size);
     
    @@ -1935,7 +1943,7 @@ public class Bike : global::System.IDisposable { Note the addReference call.

    -

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

    +

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

    @@ -1980,27 +1988,27 @@ and more or less equivalent usage from C#

    -      Container container = new Container();
    -      Element element = new Element(20);
    -      container.setElement(element);
    +  Container container = new Container();
    +  Element element = new Element(20);
    +  container.setElement(element);
     

    The C++ code will always print out 20, but the value printed out may not be this in the C# equivalent code. -In order to understand why, consider a garbage collection occuring... +In order to understand why, consider a garbage collection occurring...

    -      Container container = new Container();
    -      Element element = new Element(20);
    -      container.setElement(element);
    -      Console.WriteLine("element.value: " + container.getElement().value);
    -      // Simulate a garbage collection
    -      global::System.GC.Collect();
    -      global::System.GC.WaitForPendingFinalizers();
    -      global::System.Console.WriteLine("element.value: " + container.getElement().value);
    +  Container container = new Container();
    +  Element element = new Element(20);
    +  container.setElement(element);
    +  Console.WriteLine("element.value: " + container.getElement().value);
    +  // Simulate a garbage collection
    +  global::System.GC.Collect();
    +  global::System.GC.WaitForPendingFinalizers();
    +  global::System.Console.WriteLine("element.value: " + container.getElement().value);
     
    @@ -2019,42 +2027,55 @@ 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 global::System.Runtime.InteropServices.HandleRef getCPtrAndAddReference(Element element) { - elementReference = element; - return Element.getCPtr(element); - } public void setElement(Element e) { - examplePINVOKE.Container_setElement(swigCPtr, getCPtrAndAddReference(e)); + examplePINVOKE.Container_setElement(swigCPtr, Element.getCPtr(e)); + elementReference = e; } }

    -The following typemaps will generate the desired code. -The 'csin' typemap matches the input parameter type for the setElement method. -The 'cscode' typemap simply adds in the specified code into the C# proxy class. +The following typemaps can be used to generate this code:

    -%typemap(csin) Element *e "getCPtrAndAddReference($csinput)"
    -
     %typemap(cscode) Container %{
       // 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 global::System.Runtime.InteropServices.HandleRef getCPtrAndAddReference(Element element) {
    -    elementReference = element;
    -    return Element.getCPtr(element);
    -  }
     %}
    +
    +%typemap(csin,
    +         post="      elementReference = $csinput;"
    +         ) Element *e "Element.getCPtr($csinput)"
    +
    +
    + +

    +The 'cscode' typemap simply adds in the specified code into the C# proxy class. +The 'csin' typemap matches the input parameter type and name for the setElement method and +the 'post' typemap attribute allows adding code after the PInvoke call. +The 'post' code is generated into a finally block after the PInvoke call so the resulting code isn't quite +as mentioned earlier, setElement is actually: +

    + +
    +
    +  public void setElement(Element e) {
    +    try {
    +      examplePINVOKE.Container_setElement(swigCPtr, Element.getCPtr(e));
    +    } finally {
    +      elementReference = e;
    +    }
    +  }
     
    -

    20.8.3 Date marshalling using the csin typemap and associated attributes

    +

    23.8.3 Date marshalling using the csin typemap and associated attributes

    @@ -2127,7 +2148,7 @@ The CDate & and const CDate & C# code is generated fro

    where '$csclassname' is translated into the proxy class name, CDate and '$csinput' is translated into the name of the parameter, eg dateIn. -From C#, the intention is then to call into a modifed API with something like: +From C#, the intention is then to call into a modified API with something like:

    @@ -2340,7 +2361,7 @@ public class example {
    -

    20.8.4 A date example demonstrating marshalling of C# properties

    +

    23.8.4 A date example demonstrating marshalling of C# properties

    @@ -2440,7 +2461,7 @@ 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

    +

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

    @@ -2483,7 +2504,7 @@ The generated proxy class code will then contain the following wrapper for calli

     ...
    -  private void SwigDirectorsomeCallback(global::System.IntPtr date) {
    +  private void SwigDirectorMethodsomeCallback(global::System.IntPtr date) {
         System.DateTime tempdate = new System.DateTime();
         try {
           someCallback(out tempdate);
    @@ -2502,7 +2523,7 @@ Pay special attention to the memory management issues, using these attributes.
     

    -

    20.8.6 Turning wrapped classes into partial classes

    +

    23.8.6 Turning proxy classes into partial classes

    @@ -2602,7 +2623,97 @@ 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.

    -

    20.8.7 Extending proxy classes with additional C# code

    +

    23.8.7 Turning proxy classes into sealed classes

    + + +

    +The technique in the previous section can be used to make the proxy class a sealed class. +Consider a C++ class NotABaseClass that you don't want to be derived from in C#: +

    + +
    +
    +struct NotABaseClass {
    +  NotABaseClass();
    +  ~NotABaseClass();
    +};
    +
    +
    + +

    +The default C# proxy class method generated with Dispose method is: +

    + +
    +
    +public class NotABaseClass : global::System.IDisposable {
    +  ...
    +  public virtual void Dispose() {
    +    ...
    +  }
    +}
    +
    +
    + +

    +The csclassmodifiers typemap can be used to modify the class modifiers and +the csmethodmodifiers feature can be used on the destructor to modify the proxy's Dispose method: +

    + +
    +
    +%typemap(csclassmodifiers) NotABaseClass "public sealed class"
    +%csmethodmodifiers NotABaseClass::~NotABaseClass "public /*virtual*/";
    +
    +
    + +

    +The relevant generated code is thus: +

    + +
    +
    +public sealed class NotABaseClass : global::System.IDisposable {
    +  ...
    +  public /*virtual*/ void Dispose() {
    +    ...
    +  }
    +}
    +
    +
    + +

    +Any attempt to derive from the NotABaseClass in C# will result in a C# compiler error, for example: +

    + +
    +
    +public class Derived : NotABaseClass {
    +};
    +
    +
    +
    +
    +runme.cs(6,14): error CS0509: `Derived': cannot derive from sealed type `NotABaseClass'
    +
    +
    + +

    +Finally, if you get a warning about use of 'protected' in the generated base class: +

    + +
    +
    +NotABaseClass.cs(14,18): warning CS0628: `NotABaseClass.swigCMemOwn': new protected member declared in sealed class
    +
    +
    + +

    +Either suppress the warning or modify the generated code by copying and tweaking the default +'csbody' typemap code in csharp.swg by modifying swigCMemOwn to not be protected. +

    + +

    23.8.8 Extending proxy classes with additional C# code

    @@ -2641,13 +2752,13 @@ public class ExtendMe : global::System.IDisposable {

    -

    20.8.8 Underlying type for enums

    +

    23.8.9 Underlying type for enums

    C# enums use int as the underlying type for each enum item. If you wish to change the underlying type to something else, then use the csbase typemap. -For example when your C++ code uses a value larget than int, this is necessary as the C# compiler will not compile values which are too large to fit into an int. +For example when your C++ code uses a value larger than int, this is necessary as the C# compiler will not compile values which are too large to fit into an int. Here is an example:

    diff --git a/Doc/Manual/Chicken.html b/Doc/Manual/Chicken.html index b2f434a88..3a80811bd 100644 --- a/Doc/Manual/Chicken.html +++ b/Doc/Manual/Chicken.html @@ -8,7 +8,7 @@ -

    21 SWIG and Chicken

    +

    23 SWIG and Chicken

    -

    21.3 TinyCLOS

    +

    23.3 TinyCLOS

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

    -

    21.4 Linkage

    +

    23.4 Linkage

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

    -

    21.4.1 Static binary or shared library linked at compile time

    +

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

    -

    21.4.2 Building chicken extension libraries

    +

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

    -

    21.4.3 Linking multiple SWIG modules with TinyCLOS

    +

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

    -

    21.5 Typemaps

    +

    23.5 Typemaps

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

    Lib/chicken/chicken.swg.

    -

    21.6 Pointers

    +

    23.6 Pointers

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

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

    -

    21.6.1 Garbage collection

    +

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

    -

    21.7 Unsupported features and known problems

    +

    23.7 Unsupported features and known problems

    -

    21.7.1 TinyCLOS problems with Chicken version <= 1.92

    +

    23.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 11a90c4c3..0370d4724 100644 --- a/Doc/Manual/Contents.html +++ b/Doc/Manual/Contents.html @@ -46,6 +46,11 @@

  • Standard library changes
  • Some typemap examples
      @@ -483,6 +556,9 @@
    • Usage
  • Typemaps and overloading +
  • More about %apply and %clear
  • Passing data between typemaps
  • C++ "this" pointer @@ -491,7 +567,7 @@ -

    12 Customization Features

    +

    15 Customization Features

    @@ -519,7 +595,7 @@
    -

    13 Contracts

    +

    16 Contracts

    @@ -532,7 +608,7 @@
    -

    14 Variable Length Arguments

    +

    17 Variable Length Arguments

    @@ -550,7 +626,55 @@
    -

    15 Warning Messages

    +

    18 SWIG and Doxygen Translation

    + + + + + +

    19 Warning Messages

    @@ -569,7 +693,8 @@
  • Preprocessor (200-299)
  • C/C++ Parser (300-399)
  • Types and typemaps (400-499) -
  • Code generation (500-599) +
  • Code generation (500-559) +
  • Doxygen comments (560-599)
  • Language module specific (700-899)
  • User defined (900-999) @@ -578,7 +703,7 @@ -

    16 Working with Modules

    +

    20 Working with Modules

    @@ -594,7 +719,7 @@
    -

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

    +

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

    @@ -620,91 +745,7 @@
    -

    18 SWIG and Allegro Common Lisp

    - - - - - -

    19 SWIG and Android

    +

    22 SWIG and Android

    @@ -722,7 +763,7 @@
    -

    20 SWIG and C#

    +

    23 SWIG and C#

    @@ -761,7 +802,8 @@
  • 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 +
  • Turning proxy classes into partial classes +
  • Turning proxy classes into sealed classes
  • Extending proxy classes with additional C# code
  • Underlying type for enums @@ -769,45 +811,7 @@ -

    21 SWIG and Chicken

    - - - - - -

    22 SWIG and D

    +

    24 SWIG and D

    @@ -841,7 +845,7 @@
    -

    23 SWIG and Go

    +

    25 SWIG and Go

    @@ -885,7 +889,7 @@
    -

    24 SWIG and Guile

    +

    26 SWIG and Guile

    @@ -921,7 +925,7 @@
    -

    25 SWIG and Java

    +

    27 SWIG and Java

    @@ -1010,12 +1014,16 @@
  • Director threading issues
  • Director performance tuning
  • Java exceptions from directors +
  • Accessing protected members
  • Common customization features @@ -1071,7 +1079,7 @@ -

    26 SWIG and Javascript

    +

    28 SWIG and Javascript

    @@ -1113,30 +1121,7 @@
    -

    27 SWIG and Common Lisp

    - - - - - -

    28 SWIG and Lua

    +

    29 SWIG and Lua

    @@ -1204,108 +1189,7 @@
    -

    29 SWIG and Modula-3

    - - - - - -

    30 SWIG and MzScheme/Racket

    - - - - - -

    31 SWIG and Ocaml

    - - - - - -

    32 SWIG and Octave

    +

    30 SWIG and Octave

    @@ -1345,7 +1229,7 @@
    -

    33 SWIG and Perl5

    +

    31 SWIG and Perl5

    @@ -1421,7 +1305,7 @@
    -

    34 SWIG and PHP

    +

    32 SWIG and PHP

    @@ -1462,31 +1346,7 @@
    -

    35 SWIG and Pike

    - - - - - -

    36 SWIG and Python

    +

    33 SWIG and Python

    @@ -1501,7 +1361,8 @@
  • Using your module
  • Compilation of C++ extensions
  • Compiling for 64-bit platforms -
  • Building Python Extensions under Windows +
  • Building Python extensions under Windows +
  • Additional Python commandline options
  • A tour of basic C/C++ wrapping
  • Memory management -
  • Python 2.2 and classic classes
  • Cross language polymorphism
  • Tips and techniques
  • Docstring Features @@ -1613,11 +1479,16 @@
  • Byte string output conversion
  • Python 2 Unicode +
  • Support for Multithreaded Applications + -

    37 SWIG and R

    +

    34 SWIG and R

    @@ -1628,12 +1499,15 @@
  • General policy
  • Language conventions
  • C++ classes +
  • Enumerations -

    38 SWIG and Ruby

    +

    35 SWIG and Ruby

    @@ -1771,7 +1645,7 @@
    -

    39 SWIG and Scilab

    +

    36 SWIG and Scilab

    @@ -1802,7 +1676,7 @@
  • Pointers
  • Structures @@ -1840,7 +1714,7 @@ -

    40 SWIG and Tcl

    +

    37 SWIG and Tcl

    @@ -1906,7 +1780,74 @@
    -

    41 Extending SWIG to support new languages

    +

    38 SWIG and MzScheme/Racket

    + + + + + +

    39 SWIG and OCaml

    + + + + + +

    40 Extending SWIG to support new languages

    @@ -1964,8 +1905,13 @@
  • Running the test-suite
  • Documentation -
  • Prerequisites for adding a new language module to the SWIG distribution
  • Coding style guidelines +
  • Target language status + +
  • Prerequisites for adding a new language module to the SWIG distribution
  • Debugging Options
  • Guide to parse tree nodes diff --git a/Doc/Manual/Contract.html b/Doc/Manual/Contract.html index ef1228cfb..f7acbba3e 100644 --- a/Doc/Manual/Contract.html +++ b/Doc/Manual/Contract.html @@ -7,7 +7,7 @@ -

    13 Contracts

    +

    16 Contracts

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

      -

      13.1 The %contract directive

      +

      16.1 The %contract directive

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

    -

    13.2 %contract and classes

    +

    16.2 %contract and classes

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

    -

    13.3 Constant aggregation and %aggregate_check

    +

    16.3 Constant aggregation and %aggregate_check

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

    -

    13.4 Notes

    +

    16.4 Notes

    diff --git a/Doc/Manual/Customization.html b/Doc/Manual/Customization.html index 0e5fb2869..5fe0f5b52 100644 --- a/Doc/Manual/Customization.html +++ b/Doc/Manual/Customization.html @@ -7,7 +7,7 @@ -

    12 Customization Features

    +

    15 Customization Features

    -

    12.1.4 Exception handlers for variables

    +

    15.1.4 Exception handlers for variables

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

    12.1.5 Defining different exception handlers

    +

    15.1.5 Defining different exception handlers

    @@ -356,7 +356,7 @@ In this case, the exception handler is only attached to declarations named "allocate". This would include both global and member functions. The names supplied to %exception follow the same rules as for %rename described in the section on -Ambiguity resolution and renaming. +Renaming and ambiguity resolution. For example, if you wanted to define an exception handler for a specific class, you might write this:

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

    -

    12.1.6 Special variables for %exception

    +

    15.1.6 Special variables for %exception

    @@ -516,7 +516,7 @@ The special variables are often used in situations where method calls are logged $action } catch (MemoryError) { - croak("Out of memory in $decl"); + croak("Out of memory in $decl"); } } void log(const char *message); @@ -545,7 +545,7 @@ Below shows the expansions for the 1st of the overloaded something wrap -

    12.1.7 Using The SWIG exception library

    +

    15.1.7 Using The SWIG exception library

    @@ -600,7 +600,7 @@ SWIG_NullReferenceError The SWIG_exception() function can also be used in typemaps.

    -

    12.2 Object ownership and %newobject

    +

    15.2 Object ownership and %newobject

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

    -

    12.3 Features and the %feature directive

    +

    15.3 Features and the %feature directive

    @@ -796,7 +796,7 @@ involving %feature:

    -The name matching rules outlined in the Ambiguity resolution and renaming +The name matching rules outlined in the Renaming and ambiguity resolution section applies to all %feature directives. In fact the %rename directive is just a special form of %feature. The matching rules mean that features are very flexible and can be applied with @@ -839,7 +839,7 @@ The following are all equivalent: The syntax in the first variation will generate the { } delimiters used whereas the other variations will not.

    -

    12.3.1 Feature attributes

    +

    15.3.1 Feature attributes

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

    -

    12.3.2 Feature flags

    +

    15.3.2 Feature flags

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

    -

    12.3.3 Clearing features

    +

    15.3.3 Clearing features

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

    12.3.4 Features and default arguments

    +

    15.3.4 Features and default arguments

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

    -

    12.3.5 Feature example

    +

    15.3.5 Feature example

    diff --git a/Doc/Manual/D.html b/Doc/Manual/D.html index 1af61afd8..f9f2d53ca 100644 --- a/Doc/Manual/D.html +++ b/Doc/Manual/D.html @@ -6,7 +6,7 @@ -

    22 SWIG and D

    +

    24 SWIG and D

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

      22.1 Introduction

      +

      24.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,10 +53,10 @@

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

      -

      22.2 Command line invocation

      +

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

      +

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

      -d2
      @@ -66,8 +66,8 @@
      -splitproxy
      -

      By default, SWIG generates two D modules: the proxy module, named like the source module (either specified via the %module directive or via the module command line switch), which contains all the proxy classes, functions, enums, etc., and the intermediary module (named like the proxy module, but suffixed with _im), which contains all the extern(C) function declarations and other private parts only used internally by the proxy module.

      -

      If the split proxy mode is enabled by passing this switch at the command line, all proxy classes and enums are emitted to their own D module instead. The main proxy module only contains free functions and constants in this case.

      +

      By default, SWIG generates two D modules: the proxy module, named like the source module (either specified via the %module directive or via the module command line option), which contains all the proxy classes, functions, enums, etc., and the intermediary module (named like the proxy module, but suffixed with _im), which contains all the extern(C) function declarations and other private parts only used internally by the proxy module.

      +

      If the split proxy mode is enabled by passing this option at the command line, all proxy classes and enums are emitted to their own D module instead. The main proxy module only contains free functions and constants in this case.

      -package <pkg>
      @@ -77,16 +77,16 @@
      -wrapperlibrary <wl>
      -

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

      +

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

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

      -

      22.3 Typemaps

      +

      24.3 Typemaps

      -

      22.3.1 C# <-> D name comparison

      +

      24.3.1 C# <-> D name comparison

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

      @@ -107,12 +107,12 @@ csimports <-> dimports csbody <-> dbody csfinalize <-> ddestructor - csdestruct <-> ddispose - csdestruct_derived <-> ddispose_derived + csdisposing <-> ddispose + csdisposing_derived <-> ddispose_derived
    -

    22.3.2 ctype, imtype, dtype

    +

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

    -

    22.3.3 in, out, directorin, directorout

    +

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

    -

    22.3.4 din, dout, ddirectorin, ddirectorout

    +

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

    22.3.5 typecheck typemaps

    +

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

    -

    22.3.6 Code injection typemaps

    +

    24.3.6 Code injection typemaps

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

    @@ -174,8 +174,11 @@

    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.

    +

    +Code can also be injected into the D proxy class using %proxycode. +

    -

    22.3.7 Special variable macros

    +

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

    @@ -277,7 +280,7 @@ class SomeClass : AnInterface, AnotherInterface { ... } -

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

    +

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

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

     %typemap(dimports) RemoteMpe %{
    @@ -296,7 +299,7 @@ $importtype(AnotherInterface)
     
     
     
    -

    22.4 D and %feature

    +

    24.4 D and %feature

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

    @@ -326,7 +329,7 @@ struct A { -

    22.5 Pragmas

    +

    24.5 Pragmas

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

    @@ -365,7 +368,7 @@ struct A { -

    22.6 D Exceptions

    +

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

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

    -

    22.7 D Directors

    +

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

    @@ -384,16 +387,16 @@ struct A {

    -

    22.8 Other features

    +

    24.8 Other features

    -

    22.8.1 Extended namespace support (nspace)

    +

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

    -

    22.8.2 Native pointer support

    +

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

    @@ -405,7 +408,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 *).

    -

    22.8.3 Operator overloading

    +

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

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

    -

    22.8.4 Running the test-suite

    +

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

    @@ -425,14 +428,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.

    -

    22.9 D Typemap examples

    +

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

    -

    22.10 Work in progress and planned features

    +

    24.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/Doxygen.html b/Doc/Manual/Doxygen.html new file mode 100644 index 000000000..53238c24d --- /dev/null +++ b/Doc/Manual/Doxygen.html @@ -0,0 +1,1750 @@ + + + +SWIG and Doxygen Translation + + + +

    18 SWIG and Doxygen Translation

    + + + + + + +

    +This chapter describes SWIG's support for translating Doxygen comments +found in interface and header files into a target language's normal +documentation language. Currently only Javadoc and Pydoc is +supported. +

    + +

    18.1 Doxygen translation overview

    + + +

    +The Doxygen Translation module of SWIG adds an extra layer of +functionality to SWIG, allowing automated translation of Doxygen formatted comments +from input files into a documentation language more suited for the +target language. Currently this module only translates into Javadoc +and Pydoc for the SWIG Java and Python modules. +Other extensions could be added at a later date. +The Doxygen Translation module originally started as +a Google Summer of +Code proposal from Summer 2008. +

    + +

    18.2 Preparations

    + + +

    +To make use of the comment translation system, your documentation +comments must be in properly formatted Doxygen. Doxygen comments can be +present in your main SWIG interface file or any header file that it +imports. You are advised to be validate that your comments compile +properly with Doxygen before you try to translate them. Doxygen +itself is a more comprehensive tool and can provide you better feedback for +correcting any syntax errors that may be present. Please look at +Doxygen's Documenting the +code for the full comment format specifications. However, SWIG's +Doxygen parser will still report many errors and warnings found +in comments (like unterminated strings or missing ending tags). +

    + +

    +Currently, the whole subset of Doxygen comment styles is supported +(See +Documenting the code). Here they are: +

    + +
    +/**
    + * Javadoc style comment, multiline
    + */
    +/*!
    + * QT-style comment, multiline
    + */
    +/**
    + Any of the above, but without intermediate *'s
    + */
    +/// Single-line comment
    +//! Another single-line comment
    +
    + +

    +Also any of the above with '<' added after comment-starting symbol, +like /**<, /*!<, ///<, or //!< will be +treated as a post-comment and will be assigned to the code before the +comment. + +Any number of '*' or '/' within a Doxygen comment is +considered to be a separator and is not included in the final comment, +so you may safely use comments like /*********/ +or //////////. +

    + +

    +Please note, as SWIG parses the input file by itself with strict grammar, +there is only a limited support for various cases of comment placement +in the file. +

    +

    +Comments can be placed before C/C++ expressions on separate lines: +

    + +
    +/**
    + * Some comment
    + */
    +void someOtherFunction();
    +/**
    + * Some comment
    + */
    +void someFunction();
    +
    +class Shape {
    +  /*
    +   * Calculate the area in cm^2
    +   */
    +  int getArea();
    +}
    +
    + +

    +After C/C++ expressions at the end of the line: +

    + +
    +int someVariable = 9; ///< This is a var holding magic number 9
    +void doNothing(); ///< This does nothing, nop
    +
    + +

    +and in some special cases, like function parameter comments: +

    + +
    +void someFunction(
    +         int a ///< Some parameter 
    +     );
    +
    + +

    +or enum element comments: +

    + +
    +enum E_NUMBERS
    +{
    +    EN_ZERO, ///< The first enum item, gets zero as it's value
    +    EN_ONE, ///< The second, EN_ONE=1
    +    EN_THREE
    +};
    +
    + +

    +Currently only comments directly before or after the code items +are supported. Doxygen also supports comments containing structural commands, +where the comments for a code item are not put directly before or after the code item. +These structural commands are stripped out by SWIG and are not assigned to anything. +

    + +

    18.2.1 Enabling Doxygen translation

    + + +

    +Doxygen comments translation is disabled by default and needs to be explicitly +enabled using the command line -doxygen option for the languages that +do support it (currently Java and Python). +

    + +

    18.2.2 Doxygen-specific %feature directives

    + + +

    +Translation of Doxygen comments is influenced by the following %feature directives: +

    + +

    18.2.2.1 doxygen:notranslate

    + + +

    +Turns off translation of Doxygen comments to the target language syntax: the +original comment will be copied to the output unchanged. This is useful if you +want to use Doxygen itself to generate documentation for the target language +instead of the corresponding language tool (javadoc, sphinx, +...). +

    + + +

    18.2.2.2 doxygen:alias:<command-name>

    + + +

    +Specify an alias for a Doxygen command with the given name. This can be useful +for custom Doxygen commands which can be defined using ALIASES option +for Doxygen itself but which are unknown to SWIG. "command-name" is the +name of the command in the Doxyfile, e.g. if it contains +

    + +
    +ALIASES = "sideeffect=\par Side Effects:\n"
    +
    + +

    +Then you could also specify the same expansion for SWIG with: +

    + +
    +%feature("doxygen:alias:sideeffect") "\par Side Effects:\n"
    +
    + +

    +Please note that command arguments are not currently supported with this +feature. +

    + +

    +Notice that it is perfectly possible and potentially useful to define the alias +expansion differently depending on the target language, e.g. with +

    + +
    +#ifdef SWIGJAVA
    +%feature("doxygen:alias:not_for_java") "This functionality is not available for Java"
    +#else
    +%feature("doxygen:alias:not_for_java") ""
    +#endif
    +
    + +

    +you could use @not_for_java in the documentation comments of all +functions which can't, for whatever reason, be currently exposed in Java +wrappers of the C++ API. +

    + + +

    18.2.2.3 doxygen:ignore:<command-name>

    + + +

    +This feature makes it possible to just ignore an unknown Doxygen command, instead of +replacing it with the predefined text that doxygen:alias does. +For example, you could use +

    + +
    +%feature("doxygen:ignore:transferfull") Fantastic();
    +/**
    +    A fantastic function.
    +
    +    @transferfull Command ignored, but anything here is still included.
    + */
    +int * Fantastic();
    +
    + +

    +if you use a custom Doxygen transferfull command to indicate that the +return value ownership is transferred to the caller, as this information doesn't +make much sense for the other languages without explicit ownership management. +

    + +

    +Doxygen syntax is rather rich and, in addition to simple commands such as +@transferfull, it is also possible to define commands with arguments. +As explained in Doxygen documentation, +the arguments can have a range of a single word, everything until the end of +line or everything until the end of the next paragraph. Currently, only the "end +of line" case is supported using the range="line" argument of the +feature directive: +

    + +
    +// Ignore occurrences of
    +//
    +//    @compileroptions Some special C++ compiler options.
    +//
    +// in Doxygen comments as C++ options are not interesting for the target language
    +// developers.
    +%feature("doxygen:ignore:compileroptions", range="line") Amazing();
    +
    +/**
    +    An amazing function.
    +
    +    @compileroptions This function must be compiled with /EHa when using MSVC.
    + */
    +void Amazing();
    +
    +
    + +

    +In addition, it is also possible to have custom pairs of begin/end tags, +similarly to the standard Doxygen @code/@endcode, for example. Such +tags can also be ignored using the special value of range starting with +end to indicate that the range is an interval, for example: +

    + +
    +%feature("doxygen:ignore:forcpponly", range="end"); // same as "end:endforcpponly"
    +/**
    +    An incredible function.
    +
    +    @forcpponly
    +    This is C++-specific.
    +    @endforcpponly
    + */
    +void Incredible();
    +
    + +

    +would ignore everything between @forcpponly and @endforcpponly +commands in Doxygen comments. By default, the name of the end command is the +same as of the start one with "end" prefix, following Doxygen conventions, but +this can be overridden by providing the end command name after the colon. +

    +

    +This example shows how custom tags can be used to bracket anything specific to +C++ and prevent it from appearing in the target language documentation. +Conversely, another pair of custom tags could be used to put target language +specific information in the C++ comments. In this case, only the custom tags +themselves should be ignored, but their contents should be parsed as usual and +contents="parse" can be used for this: +

    + +
    +%feature("doxygen:ignore:beginPythonOnly", range="end:endPythonOnly", contents="parse");
    +/**
    +    A splendid function.
    +
    +    @beginPythonOnly
    +    This is specific to @b Python.
    +    @endPythonOnly
    + */
    +void Splendid();
    +
    +
    + +

    +Putting everything together, if these directives are in effect: +

    + +
    +%feature("doxygen:ignore:transferfull");
    +%feature("doxygen:ignore:compileroptions", range="line");
    +%feature("doxygen:ignore:forcpponly", range="end");
    +%feature("doxygen:ignore:beginPythonOnly", range="end:endPythonOnly", contents="parse");
    +
    + +

    +then the following C++ Doxygen comment: +

    + +
    +/**
    +    A contrived example of ignoring too many commands in one comment.
    +
    +    @forcpponly
    +    This is C++-specific.
    +    @endforcpponly
    +
    +    @beginPythonOnly
    +    This is specific to @b Python.
    +    @endPythonOnly
    +
    +    @transferfull Command ignored, but anything here is still included.
    +
    +    @compileroptions This function must be compiled with /EHa when using MSVC.
    + */
    +int * Contrived();
    +
    + +

    +would be translated to this comment in Python: +

    + +
    +def func():
    +    r"""
    +    A contrived example of ignoring too many commands in one comment.
    +
    +    This is specific to **Python**.
    +
    +    Command ignored, but anything here is still included.
    +    """
    +    ...
    +
    + + +

    18.2.2.4 doxygen:nolinktranslate

    + + +

    +Turn off automatic link-objects translation. +This is only applicable to Java at the moment. +

    + + +

    18.2.2.5 doxygen:nostripparams

    + + +

    +Turn off stripping of @param and @tparam +Doxygen commands if the parameter is not found in the function signature. +This is only applicable to Java at the moment. +

    + + +

    18.2.3 Additional command line options

    + + +

    +ALSO TO BE ADDED (Javadoc auto brief?) +

    + +

    18.3 Doxygen to Javadoc

    + + +

    +If translation is enabled, Javadoc formatted comments should be +automatically placed in the correct locations in the resulting module +and proxy files. +

    + +

    18.3.1 Basic example

    + + +

    +Here is an example segment from an included header file +

    +
    +/*! This is describing class Shape
    + \author Bob
    + */
    +
    +class Shape {
    +public:
    +  Shape() {
    +    nshapes++;
    +  }
    +  virtual ~Shape() {
    +    nshapes--;
    +  };
    +  double  x, y; /*!< Important Variables */
    +  void    move(double dx, double dy); /*!< Moves the Shape */
    +  virtual double area(void) = 0; /*!< \return the area */
    +  virtual double perimeter(void) = 0; /*!< \return the perimeter */
    +  static  int nshapes;
    +};
    +
    + +

    +Simply running SWIG should result in the following code being present in Shapes.java +

    + +
    +
    +/**
    + * This is describing class Shape 
    + * @author Bob 
    + * 
    + */
    +
    +public class Shape {
    +
    +...
    +
    +/**
    + * Important Variables 
    + */
    +  public void setX(double value) {
    +    ShapesJNI.Shape_x_set(swigCPtr, this, value);
    +  }
    +
    +/**
    + * Important Variables 
    + */
    +  public double getX() {
    +    return ShapesJNI.Shape_x_get(swigCPtr, this);
    +  }
    +
    +/**
    + * Moves the Shape 
    + */
    +  public void move(double dx, double dy) {
    +    ShapesJNI.Shape_move(swigCPtr, this, dx, dy);
    +  }
    +
    +/**
    + * @return the area 
    + */
    +  public double area() {
    +    return ShapesJNI.Shape_area(swigCPtr, this);
    +  }
    +
    +/**
    + * @return the perimeter 
    + */
    +  public double perimeter() {
    +    return ShapesJNI.Shape_perimeter(swigCPtr, this);
    +  }
    +}
    +
    +
    + +

    +The code Java-wise should be identical to what would have been +generated without the doxygen functionality enabled. When the Doxygen Translator +module encounters a comment that contains nothing useful or a doxygen comment that it cannot +parse, it will not affect the functionality of the SWIG generated +code. +

    + +

    +The Javadoc translator will handle most of the tags conversions (see the +table below). It will also automatically translate link-objects +params, in \see and \link...\endlink commands. For example, +'someFunction(std::string)' will be converted to +'someFunction(String)'. If +you don't want such behaviour, you could turn this off by using the +'doxygen:nolinktranslate' feature. Also all '\param' and '\tparam' +commands are stripped out, if the specified parameter is not present in +the function. Use 'doxygen:nostripparams' to avoid. +

    + +

    +Javadoc translator features summary +(see %feature +directives): +

    + +

    18.3.2 Javadoc tags

    + + +

    +Here is the list of all Doxygen tags and the description of how they are translated to Javadoc +

    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Doxygen tags
    \awrapped with <i> html tag
    \argwrapped with <li> html tag
    \authortranslated to @author
    \authorstranslated to @author
    \bwrapped with <b> html tag
    \cwrapped with <code> html tag
    \citewrapped with <i> html tag
    \codetranslated to {@code ...}
    \code{<ext>}translated to {@code ...}; code language extension is ignored
    \condtranslated to 'Conditional comment: <condition>'
    \copyrightreplaced with 'Copyright:'
    \deprecatedtranslated to @deprecated
    \ewrapped with <i> html tag
    \elsereplaced with '}Else:{'
    \elseifreplaced with '}Else if: <condition>{'
    \emwrapped with <i> html tag
    \endcodesee note for \code
    \endcondreplaced with 'End of conditional comment.'
    \endifreplaced with '}'
    \endlinksee note for \link
    \endverbatimsee note for \verbatim
    \exceptiontranslated to @exception
    \f$, \f[, \f], \f{, \f}LateX formulas are left unchanged
    \ifreplaced with 'If: <condition> {'
    \ifnotreplaced with 'If not: <condition> {'
    \imagetranslated to <img/> html tag only if target=HTML
    \liwrapped with <li> html tag
    \linktranslated to {@link ...}
    \nreplaced with newline char
    \notereplaced with 'Note:'
    \overloadprints 'This is an overloaded ...' according to Doxygen docs
    \pwrapped with <code> html tag
    \parreplaced with <p alt='title'>...</p>
    \paramtranslated to @param
    \param[<dir>]translated to @param; parameter direction ('in'; 'out'; or 'in,out') is ignored
    \remarkreplaced with 'Remarks:'
    \remarksreplaced with 'Remarks:'
    \resulttranslated to @return
    \returntranslated to @return
    \returnstranslated to @return
    \satranslated to @see
    \seetranslated to @see
    \sincetranslated to @since
    \throwtranslated to @throws
    \throwstranslated to @throws
    \todoreplaced with 'TODO:'
    \tparamtranslated to @param
    \verbatimtranslated to {@literal ...}
    \versiontranslated to @version
    \warningtranslated to 'Warning:'
    \$prints $ char
    \@prints @ char
    \\prints \ char
    \&prints & char
    \~prints ~ char
    \<prints < char
    \>prints > char
    \#prints # char
    \%prints % char
    \"prints " char
    \.prints . char
    \::prints ::
    +
    + +

    18.3.3 Unsupported tags

    + + +

    +Doxygen has a wealth of tags such as @latexonly that have no +equivalent in Javadoc (all supported tags are listed in +Javadoc documentation). +As a result several tags have no +translation or particular use, such as some linking and section tags. +These are suppressed with their content just printed out (if the tag has any +sense, typically text content). +Here is the list of these tags: +

    + +
    + Unsupported Doxygen tags + +
      +
    • \addindex
    • +
    • \addtogroup
    • +
    • \anchor
    • +
    • \attention
    • +
    • \brief
    • +
    • \bug
    • +
    • \callergraph
    • +
    • \callgraph
    • +
    • \category
    • +
    • \class
    • +
    • \copybrief
    • +
    • \copydetails
    • +
    • \copydoc
    • +
    • \date
    • +
    • \def
    • +
    • \defgroup
    • +
    • \details
    • +
    • \dir
    • +
    • \dontinclude
    • +
    • \dot
    • +
    • \dotfile
    • +
    • \enddot
    • +
    • \endhtmlonly
    • +
    • \endinternal
    • +
    • \endlatexonly
    • +
    • \endmanonly
    • +
    • \endmsc
    • +
    • \endrtfonly
    • +
    • \endxmlonly
    • +
    • \enum
    • +
    • \example
    • +
    • \extends
    • +
    • \file
    • +
    • \fn
    • +
    • \headerfile
    • +
    • \hideinitializer
    • +
    • \htmlinclude
    • +
    • \htmlonly
    • +
    • \implements
    • +
    • \include
    • +
    • \includelineno
    • +
    • \ingroup
    • +
    • \interface
    • +
    • \internal
    • +
    • \invariant
    • +
    • \latexonly
    • +
    • \line
    • +
    • \mainpage
    • +
    • \manonly
    • +
    • \memberof
    • +
    • \msc
    • +
    • \mscfile
    • +
    • \name
    • +
    • \namespace
    • +
    • \nosubgrouping
    • +
    • \package
    • +
    • \page
    • +
    • \paragraph
    • +
    • \post
    • +
    • \pre
    • +
    • \private
    • +
    • \privatesection
    • +
    • \property
    • +
    • \protected
    • +
    • \protectedsection
    • +
    • \protocol
    • +
    • \public
    • +
    • \publicsection
    • +
    • \ref
    • +
    • \related
    • +
    • \relatedalso
    • +
    • \relates
    • +
    • \relatesalso
    • +
    • \retval
    • +
    • \rtfonly
    • +
    • \section
    • +
    • \short
    • +
    • \showinitializer
    • +
    • \skip
    • +
    • \skipline
    • +
    • \snippet
    • +
    • \struct
    • +
    • \subpage
    • +
    • \subsection
    • +
    • \subsubsection
    • +
    • \tableofcontents
    • +
    • \test
    • +
    • \typedef
    • +
    • \union
    • +
    • \until
    • +
    • \var
    • +
    • \verbinclude
    • +
    • \weakgroup
    • +
    • \xmlonly
    • +
    • \xrefitem
    • +
    +
    + +

    + +If one of the following Doxygen tags appears as the first tag in a +comment, the whole comment block is ignored: + + +

    + +
    + Ignored Doxygen tags + +
      +
    • \addtogroup
    • +
    • \callergraph
    • +
    • \callgraph
    • +
    • \category
    • +
    • \class
    • +
    • \def
    • +
    • \defgroup
    • +
    • \dir
    • +
    • \enum
    • +
    • \example
    • +
    • \file
    • +
    • \fn
    • +
    • \headerfile
    • +
    • \hideinitializer
    • +
    • \interface
    • +
    • \internal
    • +
    • \mainpage
    • +
    • \name
    • +
    • \namespace
    • +
    • \nosubgrouping
    • +
    • \overload
    • +
    • \package
    • +
    • \page
    • +
    • \property
    • +
    • \protocol
    • +
    • \relates
    • +
    • \relatesalso
    • +
    • \showinitializer
    • +
    • \struct
    • +
    • \typedef
    • +
    • \union
    • +
    • \var
    • +
    • \weakgroup
    • +
    +
    + + + + +

    18.3.4 Further details

    + + +

    +TO BE ADDED. +

    + +

    18.4 Doxygen to Pydoc

    + + +

    +If translation is enabled, Pydoc formatted comments should be +automatically placed in the correct locations in the resulting module +and proxy files. The problem is that Pydoc has no tag mechanism like +Doxygen or Javadoc, so most of Doxygen commands are translated by merely +copying the appropriate command text. +

    + +

    18.4.1 Basic example

    + + +

    +Here is an example segment from an included header file +

    +
    +/*! This is describing class Shape
    + \author Bob
    + */
    +
    +class Shape {
    +public:
    +  Shape() {
    +    nshapes++;
    +  }
    +  virtual ~Shape() {
    +    nshapes--;
    +  };
    +  double  x, y; /*!< Important Variables */
    +  void    move(double dx, double dy); /*!< Moves the Shape */
    +  virtual double area(void) = 0; /*!< \return the area */
    +  virtual double perimeter(void) = 0; /*!< \return the perimeter */
    +  static  int nshapes;
    +};
    +
    + +

    +Simply running SWIG should result in the following code being present in Shapes.py +

    + +
    +
    +...
    +
    +class Shape(_object):
    +    """
    +    This is describing class Shape 
    +    Authors:
    +    Bob 
    +
    +    """
    +    
    +    ...
    +    
    +    def move(self, *args):
    +        """
    +        Moves the Shape 
    +        """
    +        return _Shapes.Shape_move(self, *args)
    +
    +    def area(self):
    +        """
    +        Return:
    +        the area 
    +        """
    +        return _Shapes.Shape_area(self)
    +
    +    def perimeter(self):
    +        """
    +        Return:
    +        the perimeter 
    +        """
    +        return _Shapes.Shape_perimeter(self)
    +
    + +

    +If any parameters of a function or a method are documented in the Doxygen comment, +their description is copied into the generated output using +Sphinx documentation conventions. For example +

    +
    +/**
    +    Set a breakpoint at the given location.
    +
    +    @param filename The full path to the file.
    +    @param line_number The line number in the file.
    + */
    +bool SetBreakpoint(const char* filename, int line_number);
    +
    + +

    +would be translated to +

    + +
    +def SetBreakpoint(filename, line_number):
    +    r"""
    +    Set a breakpoint at the given location.
    +
    +    :type filename: string
    +    :param filename: The full path to the file.
    +    :type line_number: int
    +    :param line_number: The line number in the file.
    +    """
    +
    +

    +The types used for the parameter documentation come from the "doctype" typemap which +is defined for all the primitive types and a few others (e.g. std::string and +shared_ptr<T>) but for non-primitive types is taken to be just the C++ +name of the type with namespace scope delimiters (::) replaced with a dot. To +change this, you can define your own typemaps for the custom types, e.g: +

    +
    +%typemap(doctype) MyDate "datetime.date";
    +
    + +

    +Currently Doxygen comments assigned to global variables and static member variables +are not present in generated code, so they have no comment translated for them. +

    + +

    + Whitespace and tables + Whitespace is preserved when translating comments, so it makes + sense to have Doxygen comments formatted in a readable way. This + includes tables, where tags <th>, <td> and </tr>are translated + to '|'. The line after line with <th> tags contains dashes. + If we take care about whitespace, comments in Python are much more + readable. Example: + +

    +/**
    + * <table border = '1'>
    + * <caption>Animals</caption>
    + * <tr><th> Column 1 </th><th> Column 2 </th></tr>
    + * <tr><td> cow      </td><td> dog      </td></tr>
    + * <tr><td> cat      </td><td> mouse    </td></tr>
    + * <tr><td> horse    </td><td> parrot   </td></tr>
    + * </table>
    + */
    +
    +

    +translates to Python as: +

    +
    +  Animals
    +  | Column 1 | Column 2 |
    +  -----------------------
    +  | cow      | dog      |
    +  | cat      | mouse    |
    +  | horse    | parrot   |
    +
    + +

    + Overloaded functions +Since all the overloaded functions in c++ are wrapped into one Python +function, Pydoc translator will combine every comment of every +overloaded function and put it into the comment for the one wrapper function. +

    +

    +If you intend to use resulting generated Python file with the Doxygen docs +generator, rather than Pydoc, you may want to turn off translation +completely (doxygen:notranslate feature). Then SWIG will just copy +the comments to the proxy file and reformat them if needed, but all +the comment content will be left as is. As Doxygen doesn't support +special commands in Python comments +(see Doxygen +docs), you may want to use some tool like doxypy +(doxypy) +to do the work. +

    + +

    18.4.2 Pydoc translator

    + + +

    +Here is the list of all Doxygen tags and the description of how they are translated to Pydoc +

    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Doxygen tags
    \awrapped with '*'
    \argprepended with '* '
    \authorprints 'Author:'
    \authorsprints 'Authors:'
    \bwrapped with '**'
    \cwrapped with '``'
    \citewrapped with single quotes
    \codereplaced with '.. code-block:: c++'
    \code{<ext>}replaced with '.. code-block:: <lang>', where the following doxygen code languages are recognized: .c -> C, .py -> python, .java > java
    \condtranslated to 'Conditional comment: <condition>'
    \copyrightprints 'Copyright:'
    \deprecatedprints 'Deprecated:'
    \ewrapped with '*'
    \elsereplaced with '}Else:{'
    \elseifreplaced with '}Else if: <condition>{'
    \emwrapped with '*'
    \endcondreplaced with 'End of conditional comment.'
    \endifreplaced with '}'
    \examplereplaced with 'Example:'
    \exceptionreplaced with ':raises:'
    \f$rendered using ':math:``'
    \f[rendered using '.. math::'
    \f{rendered using '.. math::'
    \ifreplaced with 'If: <condition> {'
    \ifnotreplaced with 'If not: <condition> {'
    \liprepended with '* '
    \nreplaced with newline char
    \notereplaced with 'Note:'
    \overloadprints 'This is an overloaded ...' according to Doxygen docs
    \pwrapped with '``'
    \parreplaced with 'Title: ...'
    \paramadd ':type:' and ':param:' directives
    \param[<dir>]same as \param, but direction ('in'; 'out'; 'in,out') is included in ':type:' directive
    \remarkreplaced with 'Remarks:'
    \remarksreplaced with 'Remarks:'
    \resultadd ':rtype:' and ':return:' directives
    \returnadd ':rtype:' and ':return:' directives
    \returnsadd ':rtype:' and ':return:' directives
    \sareplaced with 'See also:'
    \seereplaced with 'See also:'
    \sincereplaced with 'Since:'
    \throwreplaced with ':raises:'
    \throwsreplaced wih ':raises:'
    \todoreplaced with 'TODO:'
    \tparamadd ':type:' and ':param:' directives
    \verbatimcontent copied verbatim
    \versionreplaced with 'Version:'
    \warningtranslated to 'Warning:'
    \$prints $ char
    \@prints @ char
    \\prints \ char
    \&prints & char
    \~prints ~ char
    \<prints < char
    \>prints > char
    \#prints # char
    \%prints % char
    \"prints " char
    \.prints . character
    \::prints ::
    +
    + +

    18.4.3 Unsupported tags

    + + +

    +Doxygen has a wealth of tags such as @latexonly that have no +equivalent in Pydoc. As a result several tags that have no +translation (or particular use, such as some linking and section tags) +are suppressed with their content just printed out (if it has any +sense, typically text content). +Here is the list of these tags: +

    + +
    + Unsupported Python Doxygen tags + +
      +
    • \addindex
    • +
    • \addtogroup
    • +
    • \anchor
    • +
    • \attention
    • +
    • \brief
    • +
    • \bug
    • +
    • \callergraph
    • +
    • \callgraph
    • +
    • \category
    • +
    • \class
    • +
    • \copybrief
    • +
    • \copydetails
    • +
    • \copydoc
    • +
    • \date
    • +
    • \def
    • +
    • \defgroup
    • +
    • \details
    • +
    • \dir
    • +
    • \dontinclude
    • +
    • \dot
    • +
    • \dotfile
    • +
    • \enddot
    • +
    • \endhtmlonly
    • +
    • \endinternal
    • +
    • \endlatexonly
    • +
    • \endlink
    • +
    • \endmanonly
    • +
    • \endmsc
    • +
    • \endrtfonly
    • +
    • \endxmlonly
    • +
    • \enum
    • +
    • \extends
    • +
    • \file
    • +
    • \fn
    • +
    • \headerfile
    • +
    • \hideinitializer
    • +
    • \htmlinclude
    • +
    • \htmlonly
    • +
    • \image
    • +
    • \implements
    • +
    • \include
    • +
    • \includelineno
    • +
    • \ingroup
    • +
    • \interface
    • +
    • \internal
    • +
    • \invariant
    • +
    • \latexonly
    • +
    • \line
    • +
    • \link
    • +
    • \mainpage
    • +
    • \manonly
    • +
    • \memberof
    • +
    • \msc
    • +
    • \mscfile
    • +
    • \name
    • +
    • \namespace
    • +
    • \nosubgrouping
    • +
    • \package
    • +
    • \page
    • +
    • \paragraph
    • +
    • \post
    • +
    • \pre
    • +
    • \private
    • +
    • \privatesection
    • +
    • \property
    • +
    • \protected
    • +
    • \protectedsection
    • +
    • \protocol
    • +
    • \public
    • +
    • \publicsection
    • +
    • \ref
    • +
    • \related
    • +
    • \relatedalso
    • +
    • \relates
    • +
    • \relatesalso
    • +
    • \retval
    • +
    • \rtfonly
    • +
    • \section
    • +
    • \short
    • +
    • \showinitializer
    • +
    • \skip
    • +
    • \skipline
    • +
    • \snippet
    • +
    • \struct
    • +
    • \subpage
    • +
    • \subsection
    • +
    • \subsubsection
    • +
    • \tableofcontents
    • +
    • \test
    • +
    • \typedef
    • +
    • \union
    • +
    • \until
    • +
    • \var
    • +
    • \verbinclude
    • +
    • \weakgroup
    • +
    • \xmlonly
    • +
    • \xrefitem
    • +
    +
    + +

    18.4.4 Further details

    + + +

    +TO BE ADDED. +

    + +

    18.5 Troubleshooting

    + + +

    +When running SWIG with command line option -doxygen, it may happen +that SWIG will fail to parse the code, which is valid C++ code and +is parsed without problems without the option. The problem is, +that Doxygen comments are not tokens (the C/C++ compiler actually never +sees them) and that they can appear anywhere in the code. That's why it is +practically impossible to handle all corner cases with the parser. +However, these problems can usually be avoided by minor changes in the +code or comment. Known problems and solutions are shown in this section. +

    + + +

    +Recommended approach is to first run SWIG without command line +option -doxygen. When it successfully processes the code, +include the option and fix problems with Doxygen comments. +

    + + +

    18.5.1 Problem with conditional compilation

    + + +

    + Inserting a conditional compilation preprocessor directive between a + Doxygen comment and a commented item may break parsing: +

    + + +
    +class A {
    +  /**
    +   * Some func.
    +   */
    +  #ifndef SWIG
    +  void myfunc()
    +  {
    +  }
    +  #endif
    +};
    +
    + +

    + The solution is to move the directive above the comment: +

    + +
    +class A {
    +  #ifndef SWIG
    +  /**
    +   * Some func.
    +   */
    +  void myfunc()
    +  {
    +  }
    +  #endif
    +};
    +
    + + +

    18.6 Developer information

    + + +

    +This section contains information for developers enhancing the Doxygen translator. +

    + +

    18.6.1 Doxygen translator design

    + + +

    +If this functionality is turned on, SWIG places all comments found +into the SWIG parse tree. Nodes contain an additional attribute +called doxygen when a comment is present. Individual nodes +containing Doxygen with Structural Indicators, such as @file, as their +first command, are also present in the parse tree. These individual +"blobs" of Doxygen such as : +

    +
    +/*! This is describing function Foo
    + \param x some random variable
    + \author Bob
    + \return Foo
    + */
    +
    + +

    +are passed on individually to the Doxygen Translator module. This +module builds its own private parse tree and hands it to a separate +class for translation into the target documentation language. For +example, JavaDocConverter is the Javadoc module class. +

    + +

    18.6.2 Debugging the Doxygen parser and translator

    + + +

    +There are two handy command line options, that enable lots of +detailed debug information printing. +

    + +
    +  -debug-doxygen-parser     - Display Doxygen parser module debugging information
    +  -debug-doxygen-translator - Display Doxygen translator module debugging information
    +
    + +

    18.6.3 Tests

    + + +

    +Doxygen tests have been added to the regular SWIG test-suite. +There are a number of tests beginning doxygen_ in the Examples/test-suite sub-directory. +

    + +

    +Like any other SWIG test case, the tests are included in Examples/test-suite/common.mk and can be tested with +commands like make check-test-suite or make check-python-test-suite. +To run them individually, type +make -s <testname>.cpptest in the language-specific sub-directory in +Examples/test-suite directory. For example: +

    + +
    +  Examples/test-suite/java $ make -s doxygen_parsing.cpptest
    +
    + +

    +If the test fails, both expected and translated comments are printed to +std out, but also written to files expected.txt +and got.txt. Since it is often difficult to find a single +character difference in several lines of text, we can use some diff +tool, for example: +

    + +
    +  Examples/test-suite/java $ kdiff3 expected.txt got.txt
    +
    + + +

    +Runtime tests in Java are implemented using Javadoc doclets. To make that work, you +should have tools.jar from the JDK in your classpath. Or you should have JAVA_HOME +environment variable defined and pointing to the JDK location. +

    +

    +The Java's comment parsing code (the testing part) is located in commentParser.java. +It checks the generated code. It is possible +to run this file as a stand-alone program, with java commentParser <some java package>, +and it will print the list of comments found in the specified directory (in the format it has used +in the runtime tests). So, when you want to create a new Doxygen test case, +just copy an existing one and replace the actual comment content (section of entries in +form 'wantedComments.put(...)' with the output of the above command. +

    +

    +Runtime tests in Python are just plain string comparisons of the __doc__ +properties. +

    + +

    18.7 Extending to other languages

    + + +

    +In general, an extension to another language requires a fairly deep understanding of the target language module, such as Modules/python.cxx for Python. +Searching for "doxygen" in the java.cxx module can give you a good idea of the process for placing documentation comments into the correct areas. +The basic gist is that anywhere a comment may reside on a node, there needs to be a catch for it in front of where that function, class, or other object is written out to a target language file. +The other half of extension is building a target documentation language comment generator that handles one blob at a time. +However, this is relatively simple and nowhere near as complex as the wrapper generating modules in SWIG. +See Source/Doxygen/javadoc.cxx for a good example. +The target language module passes the Doxygen Translator the blob to translate, and receives back the translated text. +

    +

    + What is given to the Doxygen Translator +

    +
    +/*! This is describing function Foo
    + \param x some random variable
    + \author Bob
    + \return Foo
    + */
    +
    +

    + What is received back by java.cxx +

    +
    +/** This is describing function Foo
    + *
    + * @param x some random variable
    + * @author Bob
    + * @return Foo
    + */
    +
    +

    Development of the comment translator itself is simplified by the fact that the Doxygen Translator module can easily include a main function and thus be developed, compiled, and tested independently of SWIG. +

    + + + diff --git a/Doc/Manual/Extending.html b/Doc/Manual/Extending.html index 80fe77d4d..7c2a6c66c 100644 --- a/Doc/Manual/Extending.html +++ b/Doc/Manual/Extending.html @@ -7,7 +7,7 @@ -

    41 Extending SWIG to support new languages

    +

    40 Extending SWIG to support new languages

  • Documentation -
  • Prerequisites for adding a new language module to the SWIG distribution
  • Coding style guidelines +
  • Target language status + +
  • Prerequisites for adding a new language module to the SWIG distribution
  • Debugging Options
  • Guide to parse tree nodes @@ -76,7 +81,7 @@ -

    41.1 Introduction

    +

    40.1 Introduction

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

    -

    41.2 Prerequisites

    +

    40.2 Prerequisites

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

    -

    41.3 The Big Picture

    +

    40.3 The Big Picture

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

    -

    41.4 Execution Model

    +

    40.4 Execution Model

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

    -

    41.4.1 Preprocessing

    +

    40.4.1 Preprocessing

    @@ -278,14 +283,14 @@ or perl5.swg.

    -As a debugging aide, the text that SWIG feeds to its C++ parser can be +As a debugging aid, the text that SWIG feeds to its C++ parser can be obtained by running swig -E interface.i. This output probably isn't too useful in general, but it will show how macros have been expanded as well as everything else that goes into the low-level construction of the wrapper code.

    -

    41.4.2 Parsing

    +

    40.4.2 Parsing

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

    -

    41.4.3 Parse Trees

    +

    40.4.3 Parse Trees

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

  • -

    41.4.4 Attribute namespaces

    +

    40.4.4 Attribute namespaces

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

    -

    41.4.5 Symbol Tables

    +

    40.4.5 Symbol Tables

    @@ -729,7 +734,7 @@ For instance, the following example uses %rename in reverse to generate

     %rename(foo) foo_i(int);
    -%rename(foo) foo_d(double;
    +%rename(foo) foo_d(double);
     
     void foo_i(int);
     void foo_d(double);
    @@ -751,7 +756,7 @@ example.i:5. Previous declaration is foo_i(int )
     
    -

    41.4.6 The %feature directive

    +

    40.4.6 The %feature directive

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

    -

    41.4.7 Code Generation

    +

    40.4.7 Code Generation

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

    -

    41.4.8 SWIG and XML

    +

    40.4.8 SWIG and XML

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

    -

    41.5 Primitive Data Structures

    +

    40.5 Primitive Data Structures

    @@ -988,7 +993,7 @@ typedef Hash Typetab; -

    41.5.1 Strings

    +

    40.5.1 Strings

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

    41.5.2 Hashes

    +

    40.5.2 Hashes

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

    41.5.3 Lists

    +

    40.5.3 Lists

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

    41.5.4 Common operations

    +

    40.5.4 Common operations

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

    41.5.5 Iterating over Lists and Hashes

    +

    40.5.5 Iterating over Lists and Hashes

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

    41.5.6 I/O

    +

    40.5.6 I/O

    Special I/O functions are used for all internal I/O. These operations @@ -1529,7 +1534,7 @@ Printf(f, "%s\n", s); Similarly, the preprocessor and parser all operate on string-files.

    -

    41.6 Navigating and manipulating parse trees

    +

    40.6 Navigating and manipulating parse trees

    Parse trees are built as collections of hash tables. Each node is a hash table in which @@ -1576,7 +1581,7 @@ return the node for the first class member.
    Returns the last child node. You might use this if you wanted to append a new -node to the of a class. +node to the children of a class.

    @@ -1663,7 +1668,7 @@ Deletes a node from the parse tree. Deletion reconnects siblings and properly u the parent so that sibling nodes are unaffected. -

    41.7 Working with attributes

    +

    40.7 Working with attributes

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

    41.8 Type system

    +

    40.8 Type system

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

    -

    41.8.1 String encoding of types

    +

    40.8.1 String encoding of types

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

    -

    41.8.2 Type construction

    +

    40.8.2 Type construction

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

    41.8.3 Type tests

    +

    40.8.3 Type tests

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

    41.8.4 Typedef and inheritance

    +

    40.8.4 Typedef and inheritance

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

    41.8.5 Lvalues

    +

    40.8.5 Lvalues

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

    41.8.6 Output functions

    +

    40.8.6 Output functions

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

    41.9 Parameters

    +

    40.9 Parameters

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

    41.10 Writing a Language Module

    +

    40.10 Writing a Language Module

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

    -

    41.10.1 Execution model

    +

    40.10.1 Execution model

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

    -

    41.10.2 Starting out

    +

    40.10.2 Starting out

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

    -

    41.10.3 Command line options

    +

    40.10.3 Command line options

    @@ -2592,36 +2597,36 @@ command line options, simply use code similar to this:

     void Language::main(int argc, char *argv[]) {
       for (int i = 1; i < argc; i++) {
    -      if (argv[i]) {
    -          if (strcmp(argv[i], "-interface") == 0) {
    -            if (argv[i+1]) {
    -              interface = NewString(argv[i+1]);
    -              Swig_mark_arg(i);
    -              Swig_mark_arg(i+1);
    -              i++;
    -            } else {
    -              Swig_arg_error();
    -            }
    -          } else if (strcmp(argv[i], "-globals") == 0) {
    -            if (argv[i+1]) {
    -              global_name = NewString(argv[i+1]);
    -              Swig_mark_arg(i);
    -              Swig_mark_arg(i+1);
    -              i++;
    -            } else {
    -              Swig_arg_error();
    -            }
    -          } else if ((strcmp(argv[i], "-proxy") == 0)) {
    -            proxy_flag = 1;
    -            Swig_mark_arg(i);
    -          } else if (strcmp(argv[i], "-keyword") == 0) {
    -            use_kw = 1;
    -            Swig_mark_arg(i);
    -          } else if (strcmp(argv[i], "-help") == 0) {
    -            fputs(usage, stderr);
    -          }
    -          ...
    +    if (argv[i]) {
    +      if (strcmp(argv[i], "-interface") == 0) {
    +        if (argv[i+1]) {
    +          interface = NewString(argv[i+1]);
    +          Swig_mark_arg(i);
    +          Swig_mark_arg(i+1);
    +          i++;
    +        } else {
    +          Swig_arg_error();
    +        }
    +      } else if (strcmp(argv[i], "-globals") == 0) {
    +        if (argv[i+1]) {
    +          global_name = NewString(argv[i+1]);
    +          Swig_mark_arg(i);
    +          Swig_mark_arg(i+1);
    +          i++;
    +        } else {
    +          Swig_arg_error();
    +        }
    +      } else if ((strcmp(argv[i], "-proxy") == 0)) {
    +        proxy_flag = 1;
    +        Swig_mark_arg(i);
    +      } else if (strcmp(argv[i], "-keyword") == 0) {
    +        use_kw = 1;
    +        Swig_mark_arg(i);
    +      } else if (strcmp(argv[i], "-help") == 0) {
    +        fputs(usage, stderr);
           }
    +      ...
    +    }
       }
     }
     
    @@ -2638,7 +2643,7 @@ to mark the option as valid. If you forget to do this, SWIG will terminate wit unrecognized command line option error.

    -

    41.10.4 Configuration and preprocessing

    +

    40.10.4 Configuration and preprocessing

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

    -

    41.10.5 Entry point to code generation

    +

    40.10.5 Entry point to code generation

    @@ -2745,7 +2750,7 @@ int Python::top(Node *n) { -

    41.10.6 Module I/O and wrapper skeleton

    +

    40.10.6 Module I/O and wrapper skeleton

    @@ -2893,7 +2898,7 @@ functionWrapper : void Shape_y_set(Shape *self, double y) -

    41.10.7 Low-level code generators

    +

    40.10.7 Low-level code generators

    @@ -3026,7 +3031,7 @@ virtual int functionWrapper(Node *n) { /* Close the function(error) */ Printv(wrapper->code, "return ERROR;\n", "}\n", NIL); - /* final substititions if applicable */ + /* final substitutions if applicable */ ... /* Dump the function out */ @@ -3047,7 +3052,7 @@ but without the typemaps, there is still work to do.

    -

    41.10.8 Configuration files

    +

    40.10.8 Configuration files

    @@ -3164,7 +3169,7 @@ these kinds of problems.

    Examples/Makefile.in -
    Nothing special here; see comments at top the of this file +
    Nothing special here; see comments at the top of this file and look to the existing languages for examples.
    Examples/qux99/check.list @@ -3191,7 +3196,7 @@ politely displays the ignoring language message. -

    41.10.9 Runtime support

    +

    40.10.9 Runtime support

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

    -

    41.10.10 Standard library files

    +

    40.10.10 Standard library files

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

    -

    41.10.11 User examples

    +

    40.10.11 User examples

    @@ -3248,7 +3253,7 @@ during this process, see the section on .

    -

    41.10.12 Test driven development and the test-suite

    +

    40.10.12 Test driven development and the test-suite

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

    -

    41.10.12.1 Running the test-suite

    +

    40.10.12.1 Running the test-suite

    @@ -3499,7 +3504,7 @@ It can be run in the same way as the other language test-suites, replacing [lang The test cases used and the way it works is described in Examples/test-suite/errors/Makefile.in.

    -

    41.10.13 Documentation

    +

    40.10.13 Documentation

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

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

    - - -

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

    - -
      -
    1. - Demonstrate basic C code working by porting the "simple" example including - a runtime test, see for example Examples/python/simple. -
    2. -
    3. - Demonstrate basic C++ code working by porting the "class" example including - a runtime test, see for example Examples/python/class. -
    4. -
    5. - 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. -
    6. -
    7. - Get the test-suite running for the new language (make check-[lang]-test-suite). - While the test-suite tests many corner cases, - we'd expect the majority of it to work by compiling the generated code - correctly as most of the corner cases are covered in the SWIG core. Get - at least one C and one C++ runtime test running in the test-suite. -
    8. -
    9. - Provide a chapter in the html documentation on the basics of using - the language module. -
    10. -
    11. - Ensure your source code is formatted according to the coding style guidelines. -
    12. -
    13. - Finally, email the SWIG developers with a patch and a demonstration of - commitment to maintaining the language module, - certainly in the short term and ideally long term. -
    14. -
    - -

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

    - -

    41.10.15 Coding style guidelines

    +

    40.10.14 Coding style guidelines

    @@ -3612,7 +3560,193 @@ 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.

    -

    41.11 Debugging Options

    + +

    40.10.15 Target language status

    + + +

    +Target languages are given a status of either 'Supported' or 'Experimental' depending on their maturity as broadly outlined in +the Target language introduction. +This section provides more details on how this status is given. +

    + +

    40.10.15.1 Supported status

    + + +

    +A target language is given the 'Supported' status when +

    + +
      +
    • + It is in a mature, well functioning state. +
    • +
    • + It has its own comprehensive chapter in the documentation. + The level of documentation should be comprehensive and match the standard of the other mature modules. + Python and Java are good references.
    • +
    • + It passes all of the main SWIG test-suite. + The main test-suite is defined by the tests in the C_TEST_CASES, CPP_TEST_CASES and MULTI_CPP_TEST_CASES lists in Examples/test-suite/common.mk. + The tests in CPP11_TEST_CASES will also be required in the near future. +
    • +
    • + The test-suite must also include at least twenty wide-ranging runtime tests. + The most mature languages have a few hundred runtime tests. + Note that porting runtime tests from another language module is a quick and easy way to achieve this. +
    • +
    • + It supports the vast majority of SWIG features. + Some more advanced features, such as, directors, full nested class support and target language namespaces (nspace) may be unimplemented. + A few support libraries may be missing, for example, a small number of STL libraries.
    • +
    • + It provides strong backwards compatibility between releases. + Each point release must aim to be fully backwards compatible. + A point release version is the 3rd version digit, so each of the x.y.* versions should be backwards compatible. + Backwards compatibility breakages can occur in a new major or minor version if absolutely necessary and if documented. + A major or minor version is the first or second digit in the three digit version. +
    • +
    • + Fixing unintended regressions in the Supported languages will be given higher priority over experimental languages by the core SWIG developers. +
    • +
    • + Examples must be available and run successfully. +
    • +
    • + The examples and test-suite must be fully functioning on the Travis Continuous Integration platform. +
    • +
    + +

    40.10.15.2 Experimental status

    + + +

    +A target language is given the 'Experimental' status when +

    + +
      +
    • + It is of sub-standard quality, failing to meet the above 'Supported' status. +
    • +
    • + It is somewhere between the mid to mature stage of development. +
    • +
    • + It is in need of help to finish development. +
    • +
    + +

    +Some minimum requirements and notes about languages with the 'Experimental' status: +

    + +
      +
    • + Will at least implement basic functionality - support wrapping C functions and simple C++ classes and templates. +
    • +
    • + Have its own documentation chapter containing a reasonable level of detail. + The documentation must provide enough basic functionality for a user to get started. +
    • +
    • + Have fully functional examples of basic functionality (the simple and class examples). +
    • +
    • + The test-suite must be implemented and include a few runtime tests for both C and C++ test cases. +
    • +
    • + Failing tests must be put into one of the FAILING_CPP_TESTS or FAILING_C_TESTS lists in the test-suite. + This will ensure the test-suite can be superficially made to pass by ignoring failing tests. + The number of tests in these lists should be no greater than half of the number of tests in the full test-suite. +
    • +
    • + The examples and test-suite must also be fully functioning on the Travis Continuous Integration platform. + However, experimental languages will be set as 'allow_failures'. + This means that pull requests and normal development commits will not break the entire Travis build should an experimental language fail. +
    • +
    • + Any new failed tests will be fixed on a 'best effort' basis by core developers with no promises made. +
    • +
    • + If a language module has an official maintainer, then the maintainer will be requested to focus on fixing test-suite regressions and commit to migrating the module to become a 'Supported' module. +
    • +
    • + If a module does not have an official maintainer, then, as maintenance will be on a 'best efforts' basis by the core maintainers, no guarantees will be provided from one release to the next and regressions may creep in. +
    • +
    • + Experimental target languages will have a (suppressible) warning explaining the Experimental sub-standard status and encourage users to help improve it. +
    • +
    • + No backwards compatibility is guaranteed as the module is effectively 'in development'. + If a language module has an official maintainer, then a backwards compatibility guarantee may be provided at the maintainer's discretion and should be documented as such. +
    • +
    + +

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

    + + +

    +New target language modules can be included in SWIG and contributions are encouraged for popular languages. +In order to be considered for inclusion, a language must at a minimum fit the 'Experimental' status described above. +

    + +

    +Below are some practical steps that should help meet these requirements. +

    + +
      +
    1. + The "simple" example needs to be working to demonstrate basic C code wrappers. + Port the example from another language, such as from Examples/python/simple. +
    2. +
    3. + The "class" example needs to be working to demonstrate basic C++ code wrappers. + Port the example from another language, such as from Examples/python/class. +
    4. +
    5. + 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. +
    6. +
    7. + Copying an existing language module and adapting the source for it is likely to be the most efficient + approach to fully developing a new module as a number of corner cases are covered in the existing implementations. + The most advanced scripting languages are Python and Ruby. + The most advanced compiled target languages are Java and C#. +
    8. +
    9. + Get the test-suite running for the new language (make check-[lang]-test-suite). + While the test-suite tests many corner cases, + we'd expect the majority of it to work without much effort once the generated code is compiling + correctly for basic functionality as most of the corner cases are covered in the SWIG core. Aim to first get + one C and one C++ runtime test running in the test-suite. + Adding further runtime tests should be a lot easier afterwards by porting existing runtime tests from another language module. +
    10. +
    11. + The structure and contents of the html documentation chapter can be copied and adapted from one of the other language modules. +
    12. +
    13. + Source code can be formatted correctly using the info in the coding style guidelines section. +
    14. +
    15. + When ready, post a patch on Github, join the swig-devel mailing list and email the SWIG developers with a demonstration of + commitment to maintaining the language module, + certainly in the short term and ideally long term. +
    16. +
    + +

    +Once accepted into the official Git repository, development efforts should concentrate on +getting the entire test-suite to work +in order to migrate the language module to the 'Supported' status. +Runtime tests should be added for existing testcases and new test cases +can be added should there be an area not already covered by +the existing tests. +

    + + +

    40.11 Debugging Options

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

    -

    41.12 Guide to parse tree nodes

    +

    40.12 Guide to parse tree nodes

    @@ -4047,7 +4181,7 @@ extern "X" { ... } declaration. -

    41.13 Further Development Information

    +

    40.13 Further Development Information

    diff --git a/Doc/Manual/Go.html b/Doc/Manual/Go.html index f25e9850b..1a5bb08c7 100644 --- a/Doc/Manual/Go.html +++ b/Doc/Manual/Go.html @@ -6,7 +6,7 @@ -

    23 SWIG and Go

    +

    25 SWIG and Go

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

      -

      23.1 Overview

      +

      25.1 Overview

      @@ -86,7 +86,7 @@ type-safe as well. In case of type issues the build will fail and hence SWIG's are not used.

      -

      23.2 Examples

      +

      25.2 Examples

      @@ -101,7 +101,7 @@ SWIG interface file extension for backwards compatibility with Go 1.

      -

      23.3 Running SWIG with Go

      +

      25.3 Running SWIG with Go

      @@ -125,16 +125,15 @@ Go distribution. To generate code for gccgo, you should also use the

      -When using the -cgo option, SWIG will generate files that can be used -directly by go build. Starting with the Go 1.5 distribution the --cgo option has to be given. Put your SWIG interface file in a -directory under GOPATH/src, and give it a name that does not end in the -.swig or .swigcxx extension. Typically the SWIG interface file extension is .i -in this case. +By default SWIG will generate files that can be used directly +by go build. This requires Go 1.2 or later. Put your SWIG +interface file in a directory under GOPATH/src, and give it a name +that does not end in the .swig or .swigcxx extension. +Typically the SWIG interface file extension is .i in this case.

      -% swig -go -cgo example.i
      +% swig -go example.i
       % go install
       
      @@ -144,15 +143,16 @@ usual.

      -To use SWIG without the -cgo option, more steps are required. Recall -that this only works with Go versions before 1.5. When using Go version 1.2 or -later, or when using gccgo, the code generated by SWIG can be linked directly -into the Go program. A typical command sequence when using the Go compiler of -the Go distribution would look like this: +SWIG can be used without cgo, via the -no-cgo option, but +more steps are required. This only works with Go versions before 1.5. +When using Go version 1.2 or later, or when using gccgo, the code +generated by SWIG can be linked directly into the Go program. A +typical command sequence when using the Go compiler of the Go +distribution would look like this:

      -% swig -go example.i
      +% swig -go -no-cgo example.i
       % gcc -c code.c    # The C library being wrapped.
       % gcc -c example_wrap.c
       % go tool 6g example.go
      @@ -169,7 +169,7 @@ sequence for this approach would look like this:
       

      -% swig -go -use-shlib example.i
      +% swig -go -no-cgo -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
      @@ -181,7 +181,7 @@ sequence for this approach would look like this:
       
      -

      23.3.1 Go-specific Commandline Options

      +

      25.3.1 Go-specific Commandline Options

      @@ -200,10 +200,15 @@ swig -go -help -cgo -Generate files to be used as input for the Go cgo tool. This - option is required for Go 1.5 and later, and works for Go 1.2 and - later. In the future this option will likely become the - default. +Generate files to be used as input for the Go cgo tool. This is + the default. + + + +-no-cgo +Generate files that can be used directly, rather than via the Go + cgo tool. This option does not work with Go 1.5 or later. It is + required for versions of Go before 1.2. @@ -261,18 +266,25 @@ swig -go -help ignored. + +-import-prefix <prefix> +A prefix to add when turning a %import prefix in the SWIG + interface file into an import statement in the Go file. For + example, with -import-prefix mymodule, a SWIG + interface file %import mypackage will become a Go + import statement import "mymodule/mypackage". -

      23.3.2 Generated Wrapper Files

      +

      25.3.2 Generated Wrapper Files

      There are two different approaches to generating wrapper files, - controlled by SWIG's -cgo option. The -cgo option - works with Go version 1.2 or later. It is required when using Go - version 1.5 or later.

      + controlled by SWIG's -no-cgo option. The -no-cgo + option only works with version of Go before 1.5. It is required + when using versions of Go before 1.2.

      -

      With or without the -cgo option, SWIG will generate the +

      With or without the -no-cgo option, SWIG will generate the following files when generating wrapper code:

        @@ -296,8 +308,8 @@ or C++ compiler.
      -

      When neither the -cgo nor the -gccgo option is - used, SWIG will also generate an additional file:

      +

      When the -no-cgo option is used, and the -gccgo + option is not used, SWIG will also generate an additional file:

      • @@ -308,7 +320,7 @@ combined with the compiled MODULE.go using go tool pack.
      -

      23.4 A tour of basic C/C++ wrapping

      +

      25.4 A tour of basic C/C++ wrapping

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

      -

      23.4.1 Go Package Name

      +

      25.4.1 Go Package Name

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

      -

      23.4.2 Go Names

      +

      25.4.2 Go Names

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

      -

      23.4.3 Go Constants

      +

      25.4.3 Go Constants

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

      23.4.4 Go Enumerations

      +

      25.4.4 Go Enumerations

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

      -

      23.4.5 Go Classes

      +

      25.4.5 Go Classes

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

      -

      23.4.5.1 Go Class Memory Management

      +

      25.4.5.1 Go Class Memory Management

      @@ -471,7 +483,7 @@ The most Go idiomatic way to manage the memory for some C++ class is to call defer of the DeleteClassName call. Using defer ensures that the memory of the C++ object is freed as soon as the function containing the defer -statement returns. Furthemore defer works great for short-lived +statement returns. Furthermore defer works great for short-lived objects and fits nicely C++'s RAII idiom. Example:

      @@ -512,7 +524,7 @@ func main() {

      Using defer has limitations though, especially when it comes to -long-lived C++ objects whichs lifetimes are hard to predict. For such C++ +long-lived C++ objects whose lifetimes are hard to predict. For such C++ objects a common technique is to store the C++ object into a Go object, and to use the Go function runtime.SetFinalizer to add a finalizer which frees the C++ object when the Go object is freed. It is strongly recommended to read @@ -578,7 +590,7 @@ func (o *GoClassName) Close() {

      -

      23.4.5.2 Go Class Inheritance

      +

      25.4.5.2 Go Class Inheritance

      @@ -590,16 +602,16 @@ Doing the reverse will require an explicit type assertion, which will be checked dynamically.

      -

      23.4.6 Go Templates

      +

      25.4.6 Go Templates

      In order to use C++ templates in Go, you must tell SWIG to create -wrappers for a particular template instantation. To do this, use +wrappers for a particular template instantiation. To do this, use the %template directive. -

      23.4.7 Go Director Classes

      +

      25.4.7 Go Director Classes

      @@ -611,13 +623,13 @@ work is necessary.

      -This subchapter gives a step by step guide how to properly sublass a C++ class +This subchapter gives a step by step guide how to properly subclass a C++ class with a Go type. In general it is strongly recommended to follow this guide completely to avoid common pitfalls with directors in Go.

      -

      23.4.7.1 Example C++ code

      +

      25.4.7.1 Example C++ code

      @@ -639,12 +651,12 @@ public: virtual ~FooBarAbstract() {}; std::string FooBar() { - return this->Foo() + ", " + this->Bar(); + return this->Foo() + ", " + this->Bar(); }; protected: virtual std::string Foo() { - return "Foo"; + return "Foo"; }; virtual std::string Bar() = 0; @@ -689,7 +701,7 @@ be found in the end of the guide.

      -

      23.4.7.2 Enable director feature

      +

      25.4.7.2 Enable director feature

      @@ -724,7 +736,7 @@ documentation on directors.

      -

      23.4.7.3 Constructor and destructor

      +

      25.4.7.3 Constructor and destructor

      @@ -777,7 +789,7 @@ embedding.

      -

      23.4.7.4 Override virtual methods

      +

      25.4.7.4 Override virtual methods

      @@ -785,10 +797,12 @@ In order to override virtual methods on a C++ class with Go methods the NewDirectorClassName constructor functions receives a DirectorInterface argument. The methods in the DirectorInterface are a subset of the public and protected virtual methods -of the C++ class. If the DirectorInterface contains a method with a +of the C++ class. +Virtual methods that have a final specifier are unsurprisingly excluded. +If the DirectorInterface contains a method with a matching signature to a virtual method of the C++ class then the virtual C++ method will be overwritten with the Go method. As Go doesn't support protected -methods all overriden protected virtual C++ methods will be public in Go. +methods all overridden protected virtual C++ methods will be public in Go.

      @@ -843,7 +857,7 @@ the Go methods.

      -

      23.4.7.5 Call base methods

      +

      25.4.7.5 Call base methods

      @@ -880,7 +894,7 @@ be found in the end of the guide.

      -

      23.4.7.6 Subclass via embedding

      +

      25.4.7.6 Subclass via embedding

      @@ -941,14 +955,14 @@ methods of the FooBarAbstract C++ class by means of embedding. The public FooBarGo interface type includes the FooBarAbstract interface and hence FooBarGo can be used as a drop in replacement for FooBarAbstract while the reverse isn't possible and would raise a -compile time error. Furthemore the constructor and destructor functions +compile time error. Furthermore the constructor and destructor functions NewFooBarGo and DeleteFooBarGo take care of all the director specifics and to the user the class appears as any other SWIG wrapped C++ class.

      -

      23.4.7.7 Memory management with runtime.SetFinalizer

      +

      25.4.7.7 Memory management with runtime.SetFinalizer

      @@ -1013,7 +1027,7 @@ before using runtime.SetFinalizer to know all of its gotchas.

      -

      23.4.7.8 Complete FooBarGo example class

      +

      25.4.7.8 Complete FooBarGo example class

      @@ -1054,7 +1068,7 @@ type overwrittenMethodsOnFooBarAbstract struct { fb FooBarAbstract // If additional constructor arguments have been given they are typically - // stored here so that the overriden methods can use them. + // stored here so that the overridden methods can use them. } func (om *overwrittenMethodsOnFooBarAbstract) Foo() string { @@ -1081,7 +1095,7 @@ func NewFooBarGo() FooBarGo { // The memory of the FooBarAbstract director object instance can be // automatically freed once the FooBarGo instance is garbage collected by // uncommenting the following line. Please make sure to understand the - // runtime.SetFinalizer specific gotchas before doing this. Furthemore + // runtime.SetFinalizer specific gotchas before doing this. Furthermore // DeleteFooBarGo should be deleted if a finalizer is in use or the fooBarGo // struct needs additional data to prevent double deletion. // runtime.SetFinalizer(fbgs, FooBarGo.deleteFooBarAbstract) @@ -1142,7 +1156,7 @@ SWIG/Examples/go/director/.

      -

      23.4.8 Default Go primitive type mappings

      +

      25.4.8 Default Go primitive type mappings

      @@ -1249,7 +1263,7 @@ that typemap, or add new values, to control how C/C++ types are mapped into Go types.

      -

      23.4.9 Output arguments

      +

      25.4.9 Output arguments

      Because of limitations in the way output arguments are processed in swig, @@ -1289,7 +1303,7 @@ fraction := modulename.Modf(5.0, ptr)

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

    There are no char *OUTPUT typemaps. However you can @@ -1302,7 +1316,7 @@ void f(char *output); -

    23.4.10 Adding additional go code

    +

    25.4.10 Adding additional go code

    Often the APIs generated by swig are not very natural in go, especially if @@ -1397,7 +1411,7 @@ func bar() { -

    23.4.11 Go typemaps

    +

    25.4.11 Go typemaps

    diff --git a/Doc/Manual/Guile.html b/Doc/Manual/Guile.html index 6acdd2dc3..9d55b632b 100644 --- a/Doc/Manual/Guile.html +++ b/Doc/Manual/Guile.html @@ -8,7 +8,7 @@ -

    24 SWIG and Guile

    +

    26 SWIG and Guile

      @@ -48,7 +48,7 @@

      This section details guile-specific support in SWIG. -

      24.1 Supported Guile Versions

      +

      26.1 Supported Guile Versions

      @@ -62,7 +62,7 @@ improved performance. This is currently not tested with swig so your mileage may vary. To be safe set environment variable GUILE_AUTO_COMPILE to 0 when using swig generated guile code. -

      24.2 Meaning of "Module"

      +

      26.2 Meaning of "Module"

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

      24.3 Old GH Guile API

      +

      26.3 Old GH Guile API

      Guile 1.8 and older could be interfaced using two different api's, the SCM @@ -81,7 +81,7 @@ or the GH API. The GH interface to guile is deprecated. Read more about why in version of SWIG that can still generate guile GH wrapper code is 2.0.9. Please use that version if you really need the GH wrapper code. -

      24.4 Linkage

      +

      26.4 Linkage

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

      24.4.1 Simple Linkage

      +

      26.4.1 Simple Linkage

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

      24.4.2 Passive Linkage

      +

      26.4.2 Passive Linkage

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

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

      24.4.3 Native Guile Module Linkage

      +

      26.4.3 Native Guile Module Linkage

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

    -

    24.4.4 Old Auto-Loading Guile Module Linkage

    +

    26.4.4 Old Auto-Loading Guile Module Linkage

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

    24.4.5 Hobbit4D Linkage

    +

    26.4.5 Hobbit4D Linkage

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

    -

    24.5 Underscore Folding

    +

    26.5 Underscore Folding

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

    24.6 Typemaps

    +

    26.6 Typemaps

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

    -

    24.7 Representation of pointers as smobs

    +

    26.7 Representation of pointers as smobs

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

    24.7.1 Smobs

    +

    26.7.1 Smobs

    @@ -440,7 +440,7 @@ structure describing this type. If a generated GOOPS module has been loaded, sm the corresponding GOOPS class.

    -

    24.7.2 Garbage Collection

    +

    26.7.2 Garbage Collection

    Garbage collection is a feature of Guile since version 1.6. As SWIG now requires Guile > 1.8, @@ -454,14 +454,14 @@ is exactly like described in 24.8 Native Guile pointers +

    26.8 Native Guile pointers

    In addition to SWIG smob pointers, Guile's native pointer type are accepted as arguments to wrapped SWIG functions. This can be useful for passing pointers to bytevector data to wrapped functions.

    -

    24.9 Exception Handling

    +

    26.9 Exception Handling

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

    24.10 Procedure documentation

    +

    26.10 Procedure documentation

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

    24.11 Procedures with setters

    +

    26.11 Procedures with setters

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

    24.12 GOOPS Proxy Classes

    +

    26.12 GOOPS Proxy Classes

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

    -

    24.12.1 Naming Issues

    +

    26.12.1 Naming Issues

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

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

    24.12.2 Linking

    +

    26.12.2 Linking

    The guile-modules generated above all need to be linked together. GOOPS support requires diff --git a/Doc/Manual/Introduction.html b/Doc/Manual/Introduction.html index 0140bfa57..facfc7dd1 100644 --- a/Doc/Manual/Introduction.html +++ b/Doc/Manual/Introduction.html @@ -13,6 +13,11 @@

    • What is SWIG?
    • Why use SWIG? +
    • Target languages +
    • A SWIG example
      • SWIG interface file @@ -144,7 +149,79 @@ it provides a wide variety of customization features that let you change almost every aspect of the language bindings. This is the main reason why SWIG has such a large user manual ;-). -

        2.3 A SWIG example

        +

        2.3 Target languages

        + + +

        +SWIG in essence is a tool to generate code for making C/C++ code available to various other programming languages. +These higher level programming languages are the target languages for the SWIG code generator and C or C++ are the input languages. +A single target language must be specified when SWIG is run. +This results in generating code for C/C++ and the specified target language to interface with each other. +SWIG can be invoked multiple times, but with a different target language specified on each invocation. +This ability to interface C/C++ to many different target languages is one of SWIG's core strengths and features. +

        + +

        +SWIG is very broadly composed of two components. +A core component creates a parse tree from the input ISO C/C++ and SWIG directives (extensions to the C/C++ standards). +The parse tree is then passed to a second component, one of the target language modules for generating code specific to a higher level language. +SWIG supports many different target languages. +These target languages are given a status of either Supported or Experimental. +This status is provided to indicate the level of maturity to expect when using a particular target language as not all target languages are fully developed. +

        + +

        +The second part of the SWIG documentation contains a chapter for each target level language. +Each chapter will state the status (Supported or Experimental) for that language. +

        + +

        2.3.1 Supported status

        + + +

        +A target language is given the 'Supported' status when +

        + +
          +
        • It is in a mature, well functioning state.
        • +
        • It has its own comprehensive chapter in the documentation.
        • +
        • It passes all of the main SWIG test-suite and has a range of working examples.
        • +
        • It supports the vast majority of SWIG features.
        • +
        • It provides strong backwards compatibility between releases.
        • +
        + +

        +The above is a short summary and further details are outlined in the Supported status section in the Extending chapter. +The good news is that all the well-known and most popular languages have this status. +

        + +

        2.3.2 Experimental status

        + + +

        +A target language is given the 'Experimental' status when +

        + +
          +
        • It is of sub-standard quality, failing to meet the above 'Supported' status.
        • +
        • It is somewhere between the mid to mature stage of development.
        • +
        • It does not guarantee any backwards compatibility between releases.
        • +
        • It is in need of help to finish development.
        • +
        + +

        +Anyone using an experimental target language is strongly urged to assist with development of the target language module if they wish to use it. +

        +

        +SWIG displays a warning when an experimental target language is used in order to set expectations and emphasize the experimental status of the target language. +The usual warning suppression techniques can be used if required. +

        + +

        +The above is a short summary and further details are outlined in the Experimental status section in the Extending chapter. +

        + +

        2.4 A SWIG example

        @@ -155,7 +232,7 @@ following C code:

         /* File : example.c */
         
        -double  My_variable  = 3.0;
        +double My_variable = 3.0;
         
         /* Compute factorial of n */
         int fact(int n) {
        @@ -177,7 +254,7 @@ variable My_variable from Tcl.  You start by making a SWIG
         interface file as shown below (by convention, these files carry a .i
         suffix) :
         
        -

        2.3.1 SWIG interface file

        +

        2.4.1 SWIG interface file

        @@ -196,13 +273,13 @@ extern int    my_mod(int n, int m);
         

        -The interface file contains ANSI C function prototypes and variable +The interface file contains ISO C function prototypes and variable declarations. The %module directive defines the name of the module that will be created by SWIG. The %{ %} block provides a location for inserting additional code, such as C header files or additional C declarations, into the generated C wrapper code. -

        2.3.2 The swig command

        +

        2.4.2 The swig command

        @@ -235,7 +312,7 @@ and variables declared in the SWIG interface. A look at the file example_wrap.c reveals a hideous mess. However, you almost never need to worry about it. -

        2.3.3 Building a Perl5 module

        +

        2.4.3 Building a Perl5 module

        @@ -261,7 +338,7 @@ unix >

        -

        2.3.4 Building a Python module

        +

        2.4.4 Building a Python module

        @@ -285,7 +362,7 @@ Type "copyright", "credits" or "license" for more information. 7.5 -

        2.3.5 Shortcuts

        +

        2.4.5 Shortcuts

        @@ -311,7 +388,7 @@ print $example::My_variable + 4.5, "\n"; 7.5 -

        2.4 Supported C/C++ language features

        +

        2.5 Supported C/C++ language features

        @@ -323,7 +400,7 @@ major features include:

        • Full C99 preprocessing. -
        • All ANSI C and C++ datatypes. +
        • All ISO C and C++ datatypes.
        • Functions, variables, and constants.
        • Classes.
        • Single and multiple inheritance. @@ -336,7 +413,10 @@ major features include:

        -Most of C++11 is also supported. Details are in the C++11 section. +Most of C++11 is also supported. Details are in the C++11 chapter. +C++14 support is covered in the C++14 chapter. +C++17 support is covered in the C++17 chapter. +C++20 support is covered in the C++20 chapter.

        @@ -350,7 +430,7 @@ wrapping simple C++ code. In fact, SWIG is able to handle C++ code that stresses the very limits of many C++ compilers. -

        2.5 Non-intrusive interface building

        +

        2.6 Non-intrusive interface building

        @@ -362,7 +442,7 @@ interface and reuse the code in other applications. It is also possible to support different types of interfaces depending on the application.

        -

        2.6 Incorporating SWIG into a build system

        +

        2.7 Incorporating SWIG into a build system

        @@ -385,13 +465,13 @@ for further information on this and other Autoconf macros.

        -There is growing support for SWIG in some build tools, for example CMake +There is growing support for SWIG in some build tools, for example CMake is a cross-platform, open-source build manager with built in support for SWIG. CMake can detect the SWIG executable and many of the target language libraries for linking against. CMake knows how to build shared libraries and loadable modules on many different operating systems. This allows easy cross platform SWIG development. It can also generate the custom commands necessary for driving SWIG from IDEs and makefiles. All of this can be done from a single cross platform input file. -The following example is a CMake input file for creating a python wrapper for the SWIG interface file, example.i: +The following example is a CMake input file for creating a Python wrapper for the SWIG interface file, example.i:

        @@ -420,7 +500,7 @@ which will invoke SWIG and compile the generated C++ files into _example.so (UNI
         For other target languages on Windows a dll, instead of a .pyd file, is usually generated.
         

        -

        2.7 Hands off code generation

        +

        2.8 Hands off code generation

        @@ -433,7 +513,7 @@ it allows others to forget about the low-level implementation details.

        -

        2.8 SWIG and freedom

        +

        2.9 SWIG and freedom

        @@ -452,7 +532,7 @@ to work with complicated and unusual C/C++ applications. Ironically, the freedom that SWIG provides is countered by an extremely conservative approach to code generation. At its core, SWIG tries to distill even the most advanced C++ code down to a small -well-defined set of interface building techniques based on ANSI C +well-defined set of interface building techniques based on ISO C programming. Because of this, you will find that SWIG interfaces can be easily compiled by virtually every C/C++ compiler and that they can be used on any platform. Again, this is an important part of staying out diff --git a/Doc/Manual/Java.html b/Doc/Manual/Java.html index bff0b186b..dc403a98c 100644 --- a/Doc/Manual/Java.html +++ b/Doc/Manual/Java.html @@ -6,7 +6,7 @@ -

        25 SWIG and Java

        +

        27 SWIG and Java

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

        -

        25.1 Overview

        +

        27.1 Overview

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

        -

        25.2 Preliminaries

        +

        27.2 Preliminaries

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

        -

        25.2.1 Running SWIG

        +

        27.2.1 Running SWIG

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

        -

        25.2.2 Additional Commandline Options

        +

        27.2.2 Additional Commandline Options

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

        -

        25.2.3 Getting the right header files

        +

        27.2.3 Getting the right header files

        @@ -329,7 +333,7 @@ They are usually in directories like this:

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

        -

        25.2.4 Compiling a dynamic module

        +

        27.2.4 Compiling a dynamic module

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

        -

        25.2.5 Using your module

        +

        27.2.5 Using your module

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

        -

        25.2.6 Dynamic linking problems

        +

        27.2.6 Dynamic linking problems

        @@ -473,7 +477,7 @@ Exception in thread "main" java.lang.UnsatisfiedLinkError: exampleJNI.gcd(II)I

        where gcd is the missing JNI function that SWIG generated into the wrapper file. Also make sure you pass all of the required libraries to the linker. -The java -verbose:jni commandline switch is also a great way to get more information on unresolved symbols. +The java -verbose:jni commandline option is also a great way to get more information on unresolved symbols. One last piece of advice is to beware of the common faux pas of having more than one native library version in your path.

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

        -

        25.2.7 Compilation problems and compiling with C++

        +

        27.2.7 Compilation problems and compiling with C++

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

        -

        25.2.8 Building on Windows

        +

        27.2.8 Building on Windows

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

        -

        25.2.8.1 Running SWIG from Visual Studio

        +

        27.2.8.1 Running SWIG from Visual Studio

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

        -

        25.2.8.2 Using NMAKE

        +

        27.2.8.2 Using NMAKE

        @@ -641,11 +645,11 @@ java::

        To build the DLL and compile the java code, run NMAKE (you may need to run vcvars32 first). This is a pretty simplistic Makefile, but hopefully its enough to get you started. -Of course you may want to make changes for it to work for C++ by adding in the -c++ command line switch for swig and replacing .c with .cxx. +Of course you may want to make changes for it to work for C++ by adding in the -c++ command line option for swig and replacing .c with .cxx.

        -

        25.3 A tour of basic C/C++ wrapping

        +

        27.3 A tour of basic C/C++ wrapping

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

        -

        25.3.1 Modules, packages and generated Java classes

        +

        27.3.1 Modules, packages and generated Java classes

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

        -

        25.3.2 Functions

        +

        27.3.2 Functions

        @@ -725,7 +729,7 @@ System.out.println(example.fact(4));

      • -

        25.3.3 Global variables

        +

        27.3.3 Global variables

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

        25.3.4 Constants

        +

        27.3.4 Constants

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

        -

        25.3.5 Enumerations

        +

        27.3.5 Enumerations

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

        -

        25.3.5.1 Anonymous enums

        +

        27.3.5.1 Anonymous enums

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

        -

        25.3.5.2 Typesafe enums

        +

        27.3.5.2 Typesafe enums

        @@ -1109,11 +1113,10 @@ Typesafe enums have their advantages over using plain integers in that they can However, there are limitations. For example, they cannot be used in switch statements and serialization is an issue. Please look at the following references for further information: -http://java.sun.com/developer/Books/shiftintojava/page1.html#replaceenums Replace Enums with Classes in Effective Java Programming on the Sun website, -Create enumerated constants in Java JavaWorld article, -Java Tip 133: More on typesafe enums and -Java Tip 122: Beware of Java typesafe enumerations JavaWorld tips. +Create enumerated constants in Java JavaWorld article, +Java Tip 133: More on typesafe enums and +Java Tip 122: Beware of Java typesafe enumerations JavaWorld tips.

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

        -

        25.3.5.3 Proper Java enums

        +

        27.3.5.3 Proper Java enums

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

        -

        25.3.5.4 Type unsafe enums

        +

        27.3.5.4 Type unsafe enums

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

        -

        25.3.5.5 Simple enums

        +

        27.3.5.5 Simple enums

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

        -

        25.3.6 Pointers

        +

        27.3.6 Pointers

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

        -

        25.3.7 Structures

        +

        27.3.7 Structures

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

        25.3.8 C++ classes

        +

        27.3.8 C++ classes

        @@ -1562,7 +1565,7 @@ int bar = Spam.getBar(); -

        25.3.9 C++ inheritance

        +

        27.3.9 C++ inheritance

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

        -

        25.3.10 Pointers, references, arrays and pass by value

        +

        27.3.10 Pointers, references, arrays and pass by value

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

        -

        25.3.10.1 Null pointers

        +

        27.3.10.1 Null pointers

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

        -

        25.3.11 C++ overloaded functions

        +

        27.3.11 C++ overloaded functions

        @@ -1817,7 +1820,7 @@ void spam(unsigned short); // Ignored -

        25.3.12 C++ default arguments

        +

        27.3.12 C++ default arguments

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

        -

        25.3.13 C++ namespaces

        +

        27.3.13 C++ namespaces

        @@ -1950,7 +1953,7 @@ If the resulting use of the nspace feature and hence packages results in a proxy you will need to open up the visibility for the pointer constructor and getCPtr method from the default 'protected' to 'public' with the SWIG_JAVABODY_PROXY macro. See Java code typemaps.

        -

        25.3.14 C++ templates

        +

        27.3.14 C++ templates

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

        -

        25.3.15 C++ Smart Pointers

        +

        27.3.15 C++ Smart Pointers

        -

        25.3.15.1 The shared_ptr Smart Pointer

        +

        27.3.15.1 The shared_ptr Smart Pointer

        @@ -2013,7 +2016,7 @@ in the shared_ptr smart pointer -

        25.3.15.2 Generic Smart Pointers

        +

        27.3.15.2 Generic Smart Pointers

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

        25.4 Further details on the generated Java classes

        +

        27.4 Further details on the generated Java classes

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

        -

        25.4.1 The intermediary JNI class

        +

        27.4.1 The intermediary JNI class

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

        -

        25.4.1.1 The intermediary JNI class pragmas

        +

        27.4.1.1 The intermediary JNI class pragmas

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

        -

        25.4.2 The Java module class

        +

        27.4.2 The Java module class

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

        -

        25.4.2.1 The Java module class pragmas

        +

        27.4.2.1 The Java module class pragmas

        @@ -2396,7 +2399,7 @@ See The intermediary JNI class pragmas secti

        -

        25.4.3 Java proxy classes

        +

        27.4.3 Java proxy classes

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

        25.4.3.1 Memory management

        +

        27.4.3.1 Memory management

        @@ -2634,7 +2637,7 @@ and

        -

        25.4.3.2 Inheritance

        +

        27.4.3.2 Inheritance

        @@ -2750,7 +2753,7 @@ However, true cross language polymorphism can be achieved using the 25.4.3.3 Proxy classes and garbage collection +

        27.4.3.3 Proxy classes and garbage collection

        @@ -2759,7 +2762,7 @@ The finalize() method calls delete() which frees any malloc'd The idea is for delete() to be called when you have finished with the C/C++ object. Ideally you need not call delete(), but rather leave it to the garbage collector to call it from the finalizer. When a program exits, the garbage collector does not guarantee to call all finalizers. -An insight into the reasoning behind this can be obtained from Hans Boehm's Destructors, Finalizers, and Synchronization paper. +An insight into the reasoning behind this can be obtained from Hans Boehm's Destructors, Finalizers, and Synchronization paper. Depending on what the finalizers do and which operating system you use, this may or may not be a problem.

        @@ -2783,7 +2786,7 @@ Call the System.runFinalizersOnExit(true) or Runtime.getRuntime().r This method is inherently unsafe. It may result in finalizers being called on live objects while other threads are concurrently manipulating those objects, resulting in erratic behavior or deadlock.

        In many cases you will be lucky and find that it works, but it is not to be advocated. -Have a look at Java web site and search for runFinalizersOnExit. +Have a look at Java web site and search for runFinalizersOnExit.

      • @@ -2833,7 +2836,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.

        -

        25.4.3.4 The premature garbage collection prevention parameter for proxy class marshalling

        +

        27.4.3.4 The premature garbage collection prevention parameter for proxy class marshalling

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

        -

        25.4.3.5 Single threaded applications and thread safety

        +

        27.4.3.5 Single threaded applications and thread safety

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

        25.4.4 Type wrapper classes

        +

        27.4.4 Type wrapper classes

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

        25.4.5 Enum classes

        +

        27.4.5 Enum classes

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

        -

        25.4.5.1 Typesafe enum classes

        +

        27.4.5.1 Typesafe enum classes

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

        -

        25.4.5.2 Proper Java enum classes

        +

        27.4.5.2 Proper Java enum classes

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

        -

        25.4.5.3 Type unsafe enum classes

        +

        27.4.5.3 Type unsafe enum classes

        @@ -3332,7 +3335,7 @@ public final class Beverage { -

        25.4.6 Interfaces

        +

        27.4.6 Interfaces

        @@ -3577,7 +3580,7 @@ typemap which is only used when a class is marked with the interface fe See Java code typemaps for details.

        -

        25.5 Cross language polymorphism using directors

        +

        27.5 Cross language polymorphism using directors

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

        -

        25.5.1 Enabling directors

        +

        27.5.1 Enabling directors

        @@ -3625,7 +3628,7 @@ The %feature directive can be applied globally, to specific classes, and to spec // generate directors for all classes that have virtual methods %feature("director"); -// generate directors for all virtual methods in class Foo +// generate directors for the virtual methods in class Foo %feature("director") Foo; @@ -3643,7 +3646,7 @@ So for example,

        -will generate directors for all virtual methods of class Foo except bar(). +will generate directors for the virtual methods of class Foo except bar().

        @@ -3667,7 +3670,7 @@ public: -

        25.5.2 Director classes

        +

        27.5.2 Director classes

        @@ -3679,7 +3682,8 @@ The director classes store a pointer to their underlying Java proxy classes.

        For simplicity let's ignore the Swig::Director class and refer to the original C++ class as the director's base class. By default, a director class extends all virtual methods in the inheritance chain of its base class (see the preceding section for how to modify this behavior). -Thus all virtual method calls, whether they originate in C++ or in Java via proxy classes, eventually end up in at the implementation in the director class. +Virtual methods that have a final specifier are unsurprisingly excluded. +Thus the virtual method calls, whether they originate in C++ or in Java via proxy classes, eventually end up in at the implementation in the director class. The job of the director methods is to route these method calls to the appropriate place in the inheritance chain. By "appropriate place" we mean the method that would have been called if the C++ base class and its Java derived classes were seamlessly integrated. That seamless integration is exactly what the director classes provide, transparently skipping over all the messy JNI glue code that binds the two languages together. @@ -3694,7 +3698,7 @@ If the correct implementation is in Java, the Java API is used to call the metho

        -

        25.5.3 Overhead and code bloat

        +

        27.5.3 Overhead and code bloat

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

        -

        25.5.4 Simple directors example

        +

        27.5.4 Simple directors example

        @@ -3745,12 +3749,10 @@ Naturally, the SWIG generated C++ code and the generated Java intermediary class

        -public class DirectorDerived extends DirectorBase {
        -  public DirectorDerived() {
        -  }
        -
        +class DirectorDerived extends DirectorBase {
        +  @Override
           public void upcall_method() {
        -    System.out.println("DirectorDerived::upcall_method() invoked.");
        +    System.out.println("DirectorDerived.upcall_method() invoked.");
           }
         }
         
        @@ -3773,11 +3775,11 @@ will result in the following being output:
        -DirectorDerived::upcall_method() invoked.
        +DirectorDerived.upcall_method() invoked.
         
        -

        25.5.5 Director threading issues

        +

        27.5.5 Director threading issues

        @@ -3797,7 +3799,7 @@ Macros can be defined on the commandline when compiling your C++ code, or altern

        -

        25.5.6 Director performance tuning

        +

        27.5.6 Director performance tuning

        @@ -3818,51 +3820,192 @@ However, if all director methods are expected to usually be overridden by Java s The disadvantage is that invocation of director methods from C++ when Java doesn't actually override the method will require an additional call up into Java and back to C++. As such, this option is only useful when overrides are extremely common and instantiation is frequent enough that its performance is critical.

        -

        25.5.7 Java exceptions from directors

        +

        27.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++. +The default behavior for Java exceptions thrown in a director method overridden in Java is +to store the thrown Java exception into a SWIG defined +Swig::DirectorException C++ class exception in the C++ layer and then throw this C++ exception.

        -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. +Of course, should this exception be thrown, your C++ code must catch it and handle it before returning back to Java. +The default generated code does not attempt to handle the C++ exception, but there is a simple way +to make this all work by catching the C++ exception and extracting the original Java exception by using %catches for Swig::DirectorException. +Consider the example shown earlier with a modification to the upcall_method Java method to throw a Java exception:

        -%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 DirectorDerived extends DirectorBase {
        +  @Override
        +  public void upcall_method() {
        +    System.out.println("DirectorDerived.upcall_method() invoked.");
        +    throw new RuntimeException("There was a problem!");
           }
         }
        -
        -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 +Now, by default, the JVM will abort when example.callup(director) is called as the C++ +Swig::DirectorException (storing the Java exception) is thrown and not handled by the callup method. +Needless to say this is not very user friendly and so the recommendation is to add the following +simple %catches directive before SWIG parses the callup function: +

        + +
        +
        +%catches(Swig::DirectorException) callup;
        +
        +
        + +

        +Or target all wrapped methods using: +

        + +
        +
        +%catches(Swig::DirectorException);
        +
        +
        + +

        +This tells SWIG to generate a C++ catch handler using some code from the throws typemap for Swig::DirectorException that SWIG supplies by default, see Exception handling with %catches. +This typemap code is written to simply catch the C++ Swig::DirectorException class and immediately +return to Java throwing the original Java exception that it has stored. +The net result is a stack trace containing the original Java exception including the location that the exception was thrown from. +

        + +
        +
        +DirectorDerived.upcall_method() invoked.
        +Exception in thread "main" java.lang.RuntimeException: There was a problem!
        +    at DirectorDerived.upcall_method(runme.java:4)
        +    at exampleJNI.SwigDirector_DirectorBase_upcall_method(exampleJNI.java:20)
        +    at exampleJNI.callup(Native Method)
        +    at example.callup(example.java:12)
        +    at runme.main(runme.java:21)
        +
        +
        + +

        +More on the Swig::DirectorException class can be found in the next section which details how to customize the handling of director exceptions. +

        + +

        27.5.7.1 Customizing director exceptions

        + + +

        +This section is for advanced customization of director exceptions. +The recommendation for most users is to use the simple %catches directive described above as it should be sufficient for most users needs. +

        + +

        +The conversion of Java exceptions into C++ exceptions can be customized in two different ways using +the director:except feature. +In the first approach, a code block is attached to each director method to +handle the mapping of Java exceptions into C++ exceptions. +The code block is generated just after the call up from the C++ director method into the overloaded method in Java. Its primary function is to check if a Java exception has been thrown and then handle it in C++. +The example below converts a +java.lang.IndexOutOfBoundsException into a C++ std::out_of_range exception and converts a +user's Java MyJavaException into a C++ MyCppException exception. +If the Java exception doesn't match either of these, a fallback std::runtime_error C++ exception is thrown. +

        + +
        +
        +%feature("director:except") MyClass::dirmethod(int x) {
        +  jthrowable $error = jenv->ExceptionOccurred();
        +  if ($error) {
        +    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::dirmethod");
        +  }
        +}
        +
        +class MyClass {
        +public:
        +  /** Throws either a std::out_of_range or MyCppException on error */
        +  virtual void dirmethod(int x);
        +  virtual ~MyClass();
        +};
        +
        +
        + +

        +A few special variables are expanded within the director:except feature. +

        +
          +
        • The special variable $error is expanded into a unique variable name (swigerror) + and should be used for the assignment of the jthrowable exception that occurred.
        • +
        • The special variable $packagepath is + replaced by the outer package provided for SWIG generation by the -package option.
        • +
        • The special variable $directorthrowshandlers is not shown above, but is replaced + by applicable "directorthrows" typemap contents (covered later in this section).
        • +
        • The special variable $null is not shown above, but is replaced + by a suitable default constructed object for returning from the director method (or nothing if + the director method has a void return). +
        • +
        + +

        +Utility functions/classes in director.swg are provided to aid the exception conversion as follows: +

        + +
        +
        +namespace Swig {
        +
        +  // Helper method to determine if a Java throwable matches a particular Java class type
        +  // Note side effect of clearing any pending exceptions
        +  bool ExceptionMatches(JNIEnv *jenv, jthrowable throwable, const char *classname);
        +
        +  // Helper class to extract the exception message from a Java throwable
        +  class JavaExceptionMessage {
        +  public:
        +    JavaExceptionMessage(JNIEnv *jenv, jthrowable throwable);
        +
        +    // Return a C string of the exception message in the jthrowable passed in the constructor
        +    // If no message is available, null_string is return instead
        +    const char *message(const char *null_string = 
        +                        "Could not get exception message in JavaExceptionMessage") const;
        +  };
        +
        +  // C++ Exception class for handling Java exceptions thrown during a director method Java upcall
        +  class DirectorException : public std::exception {
        +  public:
        +
        +    // Construct exception from a Java throwable
        +    DirectorException(JNIEnv *jenv, jthrowable throwable);
        +
        +    // More general constructor for handling as a java.lang.RuntimeException
        +    DirectorException(const char *msg);
        +
        +    // Return exception message extracted from the Java throwable
        +    const char *what() const throw();
        +
        +    // Reconstruct and raise/throw the Java Exception that caused the DirectorException
        +    // Note that any error in the JNI exception handling results in a Java RuntimeException
        +    void throwException(JNIEnv *jenv) const;
        +
        +    // Create and throw the DirectorException
        +    static void raise(JNIEnv *jenv, jthrowable throwable) {
        +      throw DirectorException(jenv, throwable);
        +    }
        +  };
        +
        +}
        +
        +
        + +

        +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 @@ -3870,13 +4013,10 @@ function Swig::ExceptionMatches matches the type of the 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 +generated proxy class will have an 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 + feature. +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 @@ -3884,20 +4024,27 @@ needs to copy it, for example into a std::string or a newly constructed C++ exce

        -Using the above approach to +Using the first approach above 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++ +repetitive duplication of the director:except feature code +for each director method. +To mitigate this, a second approach is provided via typemaps in a +fashion analogous to +the "throws" typemap. +The "throws" typemap provides a way to 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. +Only use this typemap if you wish to write custom conversions of Java exceptions into C++ exceptions +and apply them to many different methods. +The default handling which uses the Swig::DirectorException class should otherwise meet your needs. +

        + +

        The example below converts a Java java.lang.IndexOutOfBoundsException exception -to the typemap's type, that is std::out_of_range: +to the typemap's type, that is a std::out_of_range C++ exception:

        @@ -3912,7 +4059,7 @@ to the typemap's type, that is std::out_of_range:
         

        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: +is used in the code block. Consider the following, which also happens to be the default:

        @@ -3920,31 +4067,41 @@ is used in the feature code. Consider the following, which also happens to be th %feature("director:except") %{ jthrowable $error = jenv->ExceptionOccurred(); if ($error) { - jenv->ExceptionClear(); $directorthrowshandlers - throw Swig::DirectorException(jenv, $error); + Swig::DirectorException::raise(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 +

        +where Swig::DirectorException::raise is the helper method to throw a C++ Swig::DirectorException, see above. +The code generated from the director:except feature +has the $directorthrowshandlers special variable replaced with the code in +the relevant "directorthrows" typemaps, for each and every exception defined for the method. +The relevant exceptions can be defined either with a C++ exception specification or %catches as described for the -"throws" typemap. +"throws" typemap.

        -Consider the following director method: +Let's try and put all this together by considering the following director method:

        -  ...
        +struct X {
           virtual void doSomething(int index) throw (std::out_of_range);
           ...
        +};
        +
        +OR
        +
        +%catches(std::out_of_range) X::doSomething;
        +struct X {
        +  virtual void doSomething(int index);
        +  ...
        +};
         
        @@ -3957,12 +4114,10 @@ the resulting code generated in the director method after calling up to Java wil
         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);
        +  Swig::DirectorException::raise(jenv, swigerror);
         }
         
        @@ -3970,7 +4125,7 @@ if (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 +director method throws an exception that is not specified in the exception specifications list 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. @@ -3978,8 +4133,9 @@ 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: +specifications may cause program termination as this exception class won't be in the exception specifications list. +You can avoid throwing Swig::DirectorException by changing the default handling for all methods by adding a director:except feature without any method name. +For example, you can just ignore them:

        @@ -3987,8 +4143,8 @@ unexpected exceptions, the default handling can be changed with: %feature("director:except") %{ jthrowable $error = jenv->ExceptionOccurred(); if ($error) { - jenv->ExceptionClear(); $directorthrowshandlers + jenv->ExceptionClear(); return $null; // exception is ignored } %} @@ -3998,7 +4154,7 @@ unexpected exceptions, the default handling can be changed with:

        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: +the return $null line above could be changed to:

        @@ -4008,125 +4164,297 @@ the return $null; could be changed to:

        In more complex situations, a separate director:except feature -may need to be attached to specific methods. +may need to be attached to specific methods by providing a method name to the director:except feature.

        -

        Below is a complete example demonstrating the use -of the "directorthrows" typemaps. In this example, a -generic "directorthrows" typemap is appropriate for all three exceptions - all -take single string constructors. If the exceptions had different constructors, -it would be necessary to have separate typemaps for each exception type. +

        This is all no doubt quite hard to follow without seeing a full example and some code. +Below is a complete example demonstrating the use +of most of the exception customizations one can use, that is, +"directorthrows" and "throws" typemaps, %exception and %catches. +See the Exception handling with %exception and %javaexception +section for more on converting C++ exceptions to Java exceptions. +The example also has a user defined C++ exception class called MyNS::MyException and this is wrapped as a Java exception. +The director class being wrapped is MyClass and the director method is called MyClass::dirmethod. +A number of std::cout calls have been added to help understand code flow. +You can copy the code below into an interface file and run SWIG on it and examine the generated code. -

         %module(directors="1") example
         
         %{
        -  #include <string>
           #include <stdexcept>
        +  #include <iostream>
         %}
         
        -// 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) {} };
        +// Generic catch handler for all wrapped methods
        +%exception %{
        +  try {
        +    $action
        +  } catch (const std::exception &e) {
        +    std::cout << "Generic std::exception catch handler" << std::endl;
        +    jclass clazz = jenv->FindClass("java/lang/RuntimeException");
        +    jenv->ThrowNew(clazz, e.what()); 
        +    return $null;
           }
         %}
        -%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;
        +// Expose C++ exception as a Java Exception by changing the Java base class and providing a getMessage()
        +%typemap(javabase) MyNS::MyException "java.lang.RuntimeException";
        +%rename(getMessage) MyNS::MyException::whatsup;
        +
        +%inline %{
         namespace MyNS {
        -  struct NAME {
        -    NAME(const std::string& what);
        -    const char * what();
        +  class MyException {
        +    std::string msg;
        +  public:
        +    MyException(const char *msg) : msg(msg) {}
        +    const char * whatsup() const { return msg.c_str(); }
           };
         }
        -%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)
        +%typemap(directorthrows) MyNS::MyException %{
        +  if (Swig::ExceptionMatches(jenv, $error, "$packagepath/MyException")) {
        +    std::cout << "$1_type exception matched (directorthrows typemap)" << std::endl;
        +    throw $1_type(Swig::JavaExceptionMessage(jenv, $error).message());
        +  }
        +%}
         
        -%catches(MyNS::ExceptionA, MyNS::ExceptionB, MyNS::Unexpected) MyClass::meth2();
        +%typemap(throws) MyNS::MyException %{
        +  std::cout << "$1_type caught (throws typemap)" << std::endl;
        +  jclass excep = jenv->FindClass("MyException");
        +  if (excep) {
        +    std::cout << "$1_type class found (throws typemap)" << std::endl;
        +    jenv->ThrowNew(excep, $1.whatsup());
        +  }
        +  return $null;
        +%}
         
        -%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() {}
        -  };
        +// These are the exceptions that the director method MyClass::dirmethod will have catch handlers for.
        +// Note that this is also a virtual method / director method and the C++ exceptions listed can be
        +// thrown after converting them from Java exceptions.
        +%catches(MyNS::MyException, Swig::DirectorException) MyClass::dirmethod;
        +
        +// These are the exceptions that call_dirmethod C++ wrapper will have catch handlers for.
        +// Note that this is not a virtual method, hence not a director method.
        +%catches(MyNS::MyException, Swig::DirectorException) call_dirmethod;
        +
        +%feature("director") MyClass;
        +
        +%feature("director:except") MyClass::dirmethod(int x) {
        +  jthrowable $error = jenv->ExceptionOccurred();
        +  if ($error) {
        +    std::cout << "Upcall finished, an exception was thrown in Java" << std::endl;
        +    $directorthrowshandlers
        +    std::cout << "Upcall finished, no exception conversion, throwing DirectorException" << std::endl;
        +    Swig::DirectorException::raise(jenv, $error);
        +  }
         }
        +
        +%inline %{
        +class MyClass {
        +public:
        +  /** Throws either a std::out_of_range or MyException on error */
        +  virtual void dirmethod(int x) {
        +    if (x <= 0)
        +      throw std::out_of_range("MyClass::dirmethod index is out of range");
        +    else if (x == 1)
        +      throw MyNS::MyException("MyClass::dirmethod some problem!");
        +  }
        +  virtual ~MyClass() {}
        +  static void call_dirmethod(MyClass& c, int x) {
        +    return c.dirmethod(x);
        +  }
        +};
        +%}
         

        -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: +The generated code for the call_dirmethod wrapper contains the various exception handlers. +The outer exception handler is from the %exception directive and the others +are from the "throws" typemaps.

        -%javaexception("Exception") MyClass::myMethod %{
        +SWIGEXPORT void JNICALL Java_exampleJNI_MyClass_1call_1dirmethod(JNIEnv *jenv, jclass jcls, jlong jarg1, jobject jarg1_, jint jarg2) {
        +  ...
           try {
        -    $action
        -  } catch (Swig::DirectorException &e) {
        -    // raise/throw the Java exception that originally caused the DirectorException
        -    e.raiseJavaException(jenv);
        -    return $null;
        +    try {
        +      MyClass::call_dirmethod(*arg1,arg2);
        +    } catch(MyNS::MyException &_e) {
        +      std::cout << "MyNS::MyException caught (throws typemap)" << std::endl;
        +      jclass excep = jenv->FindClass("MyException");
        +      if (excep) {
        +        std::cout << "MyNS::MyException class found (throws typemap)" << std::endl;
        +        jenv->ThrowNew(excep, (&_e)->whatsup());
        +      }
        +      return ;
        +      
        +    } catch(Swig::DirectorException &_e) {
        +      (&_e)->throwException(jenv);
        +      return ; 
        +    }
        +  } catch (const std::exception &e) {
        +    std::cout << "Generic std::exception catch handler" << std::endl;
        +    jclass clazz = jenv->FindClass("java/lang/RuntimeException");
        +    jenv->ThrowNew(clazz, e.what()); 
        +    return ;
           }
        -%}
         

        -See the Exception handling with %exception and %javaexception -section for more on converting C++ exceptions to Java exceptions. +The director method calling up to Java contains the exception handling code from the "directorthrows" typemaps and director:except feature.

        -

        25.6 Accessing protected members

        +
        +
        +void SwigDirector_MyClass::dirmethod(int x) {
        +      ... [call up to Java using CallStaticVoidMethod]
        +      jthrowable swigerror = jenv->ExceptionOccurred();
        +      if (swigerror) {
        +        std::cout << "Upcall finished, an exception was thrown in Java" << std::endl;
        +        
        +        if (Swig::ExceptionMatches(jenv, swigerror, "MyException")) {
        +          std::cout << "MyNS::MyException exception matched (directorthrows typemap)" << std::endl;
        +          throw MyNS::MyException(Swig::JavaExceptionMessage(jenv, swigerror).message());
        +        }
        +        
        +        std::cout << "Upcall finished, no exception conversion, throwing DirectorException" << std::endl;
        +        Swig::DirectorException::raise(jenv, swigerror);
        +      }
        +
        +
        + +

        +Let's use the following Java class to override the director method. +

        + +
        +
        +class DerivedClass extends MyClass {
        +  @Override
        +  public void dirmethod(int x) {
        +    if (x < 0)
        +      throw new IndexOutOfBoundsException("Index is negative");
        +    else if (x == 0)
        +      throw new MyException("MyException: bad dirmethod");
        +  }
        +}
        +public class runme {
        +  public static void main(String argv[]) {
        +    System.loadLibrary("example");
        +    ... code snippets shown below ...
        +  }
        +}
        +
        +
        + +

        +Consider the output using the Java code in the four slightly different scenarios below. +

        + +

        +1. Non-director C++ class is used, thus, no upcall to a Java director method is made. +A std::out_of_range exception is thrown, which is derived from std::exception, +and hence caught by the generic exception handler in the call_dirmethod wrapper. +The Java code snippet and resulting output is: +

        + + +
        +
        +MyClass.call_dirmethod(new MyClass(), 0);
        +
        +
        + +
        +
        +Generic std::exception catch handler
        +Exception in thread "main" java.lang.RuntimeException: MyClass::dirmethod index is out of range
        +        at exampleJNI.MyClass_call_dirmethod(Native Method)
        +        at MyClass.call_dirmethod(MyClass.java:57)
        +        at runme.main(runme.java:14)
        +
        +
        + +

        +2. Non-director C++ class again but this time the MyNS::MyException class is thrown and caught: +

        + +
        +
        +MyClass.call_dirmethod(new MyClass(), 1);
        +
        +
        + +
        +
        +MyNS::MyException caught (throws typemap)
        +MyNS::MyException class found (throws typemap)
        +Exception in thread "main" MyException: MyClass::dirmethod some problem!
        +        at exampleJNI.MyClass_call_dirmethod(Native Method)
        +        at MyClass.call_dirmethod(MyClass.java:57)
        +        at runme.main(runme.java:15)
        +
        +
        + +

        +3. The DerivedClass director class is used so the upcall to Java occurs, but it throws +a Java MyException, which gets converted into a C++ MyNS::MyException, then caught and converted back +into a Java MyException: +

        + +
        +
        +MyClass.call_dirmethod(new DerivedClass(), 0);
        +
        +
        + +
        +
        +Upcall finished, an exception was thrown in Java
        +MyNS::MyException exception matched (directorthrows typemap)
        +MyNS::MyException caught (throws typemap)
        +MyNS::MyException class found (throws typemap)
        +Exception in thread "main" MyException: MyException: bad dirmethod
        +        at exampleJNI.MyClass_call_dirmethod(Native Method)
        +        at MyClass.call_dirmethod(MyClass.java:57)
        +        at runme.main(runme.java:16)
        +
        +
        + +

        +4. The director class is used again, but this time the director method throws a Java IndexOutOfBoundsException exception which is converted into a C++ Swig::DirectorException, thrown and caught again. +This time the original Java exception is extracted from the Swig::DirectorException and rethrown. +Note that this approach keeps the stack trace information of the original exception, so it has the exact location of where the IndexOutOfBoundsException exception was thrown. +This is arguably an improvement over the approach above that converts from a Java excepton to C++ exception and then back to a new Java exception, losing the location of the original exception. +

        + +
        +
        +MyClass.call_dirmethod(new DerivedClass(), -1);
        +
        +
        + +
        +
        +Upcall finished, an exception was thrown in Java
        +Upcall finished, no exception conversion, throwing DirectorException
        +Exception in thread "main" java.lang.IndexOutOfBoundsException: Index is negative
        +        at DerivedClass.dirmethod(runme.java:5)
        +        at exampleJNI.SwigDirector_MyClass_dirmethod(exampleJNI.java:23)
        +        at exampleJNI.MyClass_call_dirmethod(Native Method)
        +        at MyClass.call_dirmethod(MyClass.java:57)
        +        at runme.main(runme.java:17)
        +
        +
        + +

        27.6 Accessing protected members

        @@ -4222,7 +4550,7 @@ class MyProtectedBase extends ProtectedBase -

        25.7 Common customization features

        +

        27.7 Common customization features

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

        -

        25.7.1 C/C++ helper functions

        +

        27.7.1 C/C++ helper functions

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

        -

        25.7.2 Class extension with %extend

        +

        27.7.2 Class extension with %extend

        @@ -4322,16 +4650,16 @@ struct Vector { %extend Vector { char *toString() { - static char tmp[1024]; - sprintf(tmp, "Vector(%g, %g, %g)", $self->x, $self->y, $self->z); - return tmp; + static char tmp[1024]; + sprintf(tmp, "Vector(%g, %g, %g)", $self->x, $self->y, $self->z); + return tmp; } Vector(double x, double y, double z) { - Vector *v = (Vector *) malloc(sizeof(Vector)); - v->x = x; - v->y = y; - v->z = z; - return v; + Vector *v = (Vector *) malloc(sizeof(Vector)); + v->x = x; + v->y = y; + v->z = z; + return v; } }; @@ -4363,7 +4691,144 @@ Vector(2, 3, 4) in any way---the extensions only show up in the Java interface.

        -

        25.7.3 Exception handling with %exception and %javaexception

        +

        27.7.3 Class extension with %proxycode

        + + +

        +The previous section described how to extend a wrapped class with C or C++ code. +This section describes how to extend a wrapped class with Java code instead of C/C++ code. +The %proxycode directive is used and is just a macro for %insert("proxycode"). +The Code insertion block section describes the %insert directive. +The section of code for insertion is "proxycode", that is, the Java proxy class. +This directive must hence only be used within the scope of a class, otherwise it is silently ignored. +There are two common ways to get the scope correct. +

        + +

        +The first is to use %proxycode inside a class that SWIG parses, for example a toString() method can be added to a C++ class using pure Java code. +A C++ header file can mix C++ and Java code inside the C++ class as follows: +

        + +
        +
        +// flag.h header file
        +class Flag {
        +  bool flag;
        +public:
        +  Flag(bool flag) : flag(flag) {}
        +  bool FetchFlag() { return flag; }
        +#if defined(SWIG)
        +%proxycode %{
        +  public String toString() {
        +    boolean flag = FetchFlag();
        +    return Boolean.toString(flag);
        +  }
        +%}
        +#endif
        +};
        +
        +
        + +

        +and wrapped using: +

        + +
        +
        +%{
        +#include "flag.h"
        +%}
        +%include "flag.h"
        +
        +
        + +

        +The second is to use %proxycode within %extend as everything within a %extend block is effectively within the scope of the class, for example: +

        + +
        +
        +// flag.h header file
        +class Flag {
        +  bool flag;
        +public:
        +  Flag(bool flag) : flag(flag) {}
        +  bool FetchFlag() { return flag; }
        +};
        +
        +
        + +

        +and wrapped using: +

        + +
        +
        +%{
        +#include "flag.h"
        +%}
        +%include "flag.h"
        +
        +%extend Flag {
        +#if defined(SWIG)
        +%proxycode %{
        +  public String toString() {
        +    boolean flag = FetchFlag();
        +    return Boolean.toString(flag);
        +  }
        +%}
        +#endif
        +}
        +
        +
        + +

        +There is some very limited support of typemaps within a %proxycode block. +A useful trick is to obtain the Java type for a given C/C++ type using the $typemap special macro. +The following C++ template demonstrates this: +

        + +
        +
        +%inline %{
        +template<typename T> struct Value {
        +  T value;
        +  Value(const T& val) : value(val) {}
        +};
        +%}
        +
        +%extend Value {
        +%proxycode %{
        +  public String toString() {
        +    // Note template type expansion is supported, so T is expanded to 'unsigned int' in this example
        +    // and $typemap(jstype, unsigned int) in turn is expanded to 'long'
        +    $typemap(jstype, T) val = getValue();
        +    return "$javaclassname value: " + val + " Java type: $typemap(jstype, T) JNI type: $typemap(jni, T)";
        +  }
        +%}
        +}
        +%template(ValueUnsignedInt) Value<unsigned int>;
        +
        +
        + +

        +The generated Java contains the expanded special variable and macro resulting in Java proxy code: +

        + +
        +
        +public class ValueUnsignedInt {
        +  ...
        +  public String toString() {
        +    long val = getValue();
        +    return "ValueUnsignedInt value: " + val + " Java type: long JNI type: jlong";
        +  }
        +
        +}
        +
        +
        + +

        27.7.4 Exception handling with %exception and %javaexception

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

        -

        25.7.4 Method access with %javamethodmodifiers

        +

        27.7.5 Method access with %javamethodmodifiers

        @@ -4548,7 +5013,7 @@ protected static void protect_me() {

        -

        25.8 Tips and techniques

        +

        27.8 Tips and techniques

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

        -

        25.8.1 Input and output parameters using primitive pointers and references

        +

        27.8.1 Input and output parameters using primitive pointers and references

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

        -

        25.8.2 Simple pointers

        +

        27.8.2 Simple pointers

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

        -

        25.8.3 Wrapping C arrays with Java arrays

        +

        27.8.3 Wrapping C arrays with Java arrays

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

        -

        25.8.4 Unbounded C Arrays

        +

        27.8.4 Unbounded C Arrays

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

        -

        25.8.5 Binary data vs Strings

        +

        27.8.5 Binary data vs Strings

        @@ -5054,7 +5519,7 @@ len: 5 data: 68 69 0 6a 6b -

        25.8.6 Overriding new and delete to allocate from Java heap

        +

        27.8.6 Overriding new and delete to allocate from Java heap

        @@ -5128,7 +5593,7 @@ void * operator new(size_t t) { throw bad_alloc(); pJalloc->ref = 0; return static_cast<void *>( - static_cast<char *>(static_cast<void *>(pJalloc)) + sizeof(Jalloc)); + static_cast<char *>(static_cast<void *>(pJalloc)) + sizeof(Jalloc)); } } @@ -5171,7 +5636,7 @@ model and use these functions in place of malloc and free in your own code.

        -

        25.9 Java typemaps

        +

        27.9 Java typemaps

        @@ -5179,7 +5644,7 @@ This section describes how you can modify SWIG's default wrapping behavior for various C/C++ datatypes using the %typemap directive. You are advised to be familiar with the material in the "Typemaps" chapter. While not absolutely essential knowledge, this section assumes some familiarity with the Java Native Interface (JNI). -JNI documentation can be consulted either online at Sun's Java web site or from a good JNI book. +JNI documentation can be consulted either online at the Java web site or from a good JNI book. The following two books are recommended:

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

          25.9.1 Default primitive type mappings

          +

          27.9.1 Default primitive type mappings

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

          -

          25.9.2 Default typemaps for non-primitive types

          +

          27.9.2 Default typemaps for non-primitive types

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

          -

          25.9.3 Sixty four bit JVMs

          +

          27.9.3 Sixty four bit JVMs

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

          -

          25.9.4 What is a typemap?

          +

          27.9.4 What is a typemap?

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

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

          +

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

          @@ -5543,6 +6008,17 @@ The most important of these implement the mapping of C/C++ types to Java types: In other words the typemap provides the conversion from the native method call return type. + +jboxtype +Java boxed type. + These are Java code typemaps to provide the Java boxed type, such as, Integer for C type int. + As autoboxing is only relevant to the Java primitive types, these are only provided for the + C types that map to Java primitive types. + This typemap is usually only used by C++ STL container wrappers that are wrapped by Java generic + types as the boxed type must be used instead of the unboxed/primitive type when declaring a Java generic type. + + + javadirectorin Conversion from jtype to jstype for director methods. @@ -5764,7 +6240,7 @@ These are listed below: -

          25.9.6 Java typemap attributes

          +

          27.9.6 Java typemap attributes

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

          -

          25.9.7 Java special variables

          +

          27.9.7 Java special variables

          @@ -5992,7 +6468,7 @@ in that it is not fully qualified with the package name when using the nspace feature.

          -

          25.9.8 Typemaps for both C and C++ compilation

          +

          27.9.8 Typemaps for both C and C++ compilation

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

          -

          25.9.9 Java code typemaps

          +

          27.9.9 Java code typemaps

          @@ -6070,9 +6546,12 @@ class modifiers for the Java class: default is "public class"

          %typemap(javacode)

          Java code is copied verbatim to the Java class: empty default +As there can only be one "javacode" typemap per class, also consider using the +%proxycode directive which can be used multiple times per class +and offers nearly identical functionality.
          -

          %typemap(javadestruct, methodname="delete", methodmodifiers="public synchronized")

          +

          %typemap(javadestruct, methodname="delete", methodmodifiers="public synchronized", parameters="")

          destructor wrapper - the delete() method (proxy classes only), used for all proxy classes except those which have a base class @@ -6081,9 +6560,12 @@ used for all proxy classes except those which have a base class
          Note that the delete() method name is configurable and is specified by the methodname attribute. The method modifiers are also configurable via the methodmodifiers attribute. +If a %javamethodmodifiers is attached to the class' destructor, +it will be used in preference to the methodmodifiers typemap attribute for the class. +The delete method's parameters declaration can be provided in the optional parameters typemap attribute.
          -

          %typemap(javadestruct_derived, methodname="delete", methodmodifiers="public synchronized")

          +

          %typemap(javadestruct_derived, methodname="delete", methodmodifiers="public synchronized", parameters="")

          destructor wrapper - the delete() method (proxy classes only), same as "javadestruct" but only used for derived proxy classes @@ -6092,6 +6574,9 @@ same as "javadestruct" but only used for derived proxy classes
          Note that the delete() method name is configurable and is specified by the methodname attribute. The method modifiers are also configurable via the methodmodifiers attribute. +If a %javamethodmodifiers is attached to the class' destructor, +it will be used in preference to the methodmodifiers typemap attribute for the class. +The delete method's parameters declaration can be provided in the optional parameters typemap attribute.

          %typemap(javaimports)

          @@ -6125,6 +6610,15 @@ Below shows an example modifying the finalizer, assuming the delete met +

          %typemap(javainterfacemodifiers)

          +
          +Interface modifiers for the Java interface generated when using the interface feature, see Java interfaces section. The default is "public interface". +

          +Compatibility note: This typemap was added in SWIG-4.1.0. +

          + +
          +

          %typemap(javainterfacecode, declaration="...", cptrmethod="...")

          @@ -6224,7 +6718,7 @@ The "javaimports" typemap is ignored if the enum class is wrapped by an inner Ja

           [ javaimports typemap ]
          -public interface [ javainterfacename ] {
          +[ javainterfacemodifiers typemap ] [ javainterfacename ] {
           [ javainterfacecode:cptrmethod typemap attribute ]
           ... interface declarations ...
           }
          @@ -6318,7 +6812,7 @@ to make the method and constructor public:
           
          -

          25.9.10 Director specific typemaps

          +

          27.9.10 Director specific typemaps

          @@ -6350,14 +6844,14 @@ A typemap for C character strings is:

          -%typemap(directorin, descriptor="Ljava/lang/String;", noblock=1) char * %{
          +%typemap(directorin, descriptor="Ljava/lang/String;", noblock=1) char * {
             $input = 0;
             if ($1) {
               $input = JCALL1(NewStringUTF, jenv, (const char *)$1);
               if (!$input) return $null;
             }
             Swig::LocalRefGuard $1_refguard(jenv, $input);
          -%}
          +}
           
          @@ -6595,7 +7089,7 @@ The basic strategy here is to provide a default package typemap for the majority
          -

          25.10 Typemap Examples

          +

          27.10 Typemap Examples

          @@ -6605,7 +7099,7 @@ the SWIG library.

          -

          25.10.1 Simpler Java enums for enums without initializers

          +

          27.10.1 Simpler Java enums for enums without initializers

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

          -

          25.10.2 Handling C++ exception specifications as Java exceptions

          +

          27.10.2 Handling C++ exception specifications as Java exceptions

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

          -

          25.10.3 NaN Exception - exception handling for a particular type

          +

          27.10.3 NaN Exception - exception handling for a particular type

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

          -

          25.10.4 Converting Java String arrays to char **

          +

          27.10.4 Converting Java String arrays to char **

          @@ -7076,7 +7570,7 @@ public class runme { example.print_args(animals); String args[] = example.get_args(); for (int i=0; i<args.length; i++) - System.out.println(i + ":" + args[i]); + System.out.println(i + ":" + args[i]); } } @@ -7108,7 +7602,7 @@ Lastly the "jni", "jtype" and "jstype" typemaps are also required to specify what Java types to use.

          -

          25.10.5 Expanding a Java object to multiple arguments

          +

          27.10.5 Expanding a Java object to multiple arguments

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

          25.10.6 Using typemaps to return arguments

          +

          27.10.6 Using typemaps to return arguments

          @@ -7308,7 +7802,7 @@ $ java runme 1 12.0 340.0 -

          25.10.7 Adding Java downcasts to polymorphic return types

          +

          27.10.7 Adding Java downcasts to polymorphic return types

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

          -

          25.10.8 Adding an equals method to the Java classes

          +

          27.10.8 Adding an equals method to the Java classes

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

          25.10.9 Void pointers and a common Java base class

          +

          27.10.9 Void pointers and a common Java base class

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

        25.10.10 Struct pointer to pointer

        +

        27.10.10 Struct pointer to pointer

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

        -

        25.10.11 Memory management when returning references to member variables

        +

        27.10.11 Memory management when returning references to member variables

        @@ -7812,7 +8306,7 @@ Consider the following C++ code:

         struct Wheel {
           int size;
        -  Wheel(int sz) : size(sz) {}
        +  Wheel(int sz = 0) : size(sz) {}
         };
         
         class Bike {
        @@ -7920,7 +8414,7 @@ public class Bike {
         Note the addReference call.
         

        -

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

        +

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

        @@ -7972,7 +8466,7 @@ System.out.println("element value: " + container.getElement().getValue());

        The C++ code will always print out 20, but the value printed out may not be this in the Java equivalent code. -In order to understand why, consider a garbage collection occuring... +In order to understand why, consider a garbage collection occurring...

        @@ -8001,42 +8495,54 @@ public class Container { // Ensure that the GC doesn't collect any Element set from Java // as the underlying C++ class stores a shallow copy private Element elementReference; - private long getCPtrAndAddReference(Element element) { - elementReference = element; - return Element.getCPtr(element); - } public void setElement(Element e) { - exampleJNI.Container_setElement(swigCPtr, this, getCPtrAndAddReference(e), e); + exampleJNI.Container_setElement(swigCPtr, this, Element.getCPtr(e), e); + elementReference = e; } }

        -The following typemaps will generate the desired code. -The 'javain' typemap matches the input parameter type for the setElement method. -The 'javacode' typemap simply adds in the specified code into the Java proxy class. +The following typemaps can be used to generate this code:

        -%typemap(javain) Element *e "getCPtrAndAddReference($javainput)"
        -
         %typemap(javacode) Container %{
           // Ensure that the GC doesn't collect any element set from Java
           // as the underlying C++ class stores a shallow copy
           private Element elementReference;
        -  private long getCPtrAndAddReference(Element element) {
        -    elementReference = element;
        -    return Element.getCPtr(element);
        -  }
         %}
        +
        +%typemap(javain, 
        +         post="      elementReference = $javainput;"
        +         ) Element *e "Element.getCPtr($javainput)"
         
        +

        +The 'javacode' typemap simply adds in the specified code into the Java proxy class. +The 'javain' typemap matches the input parameter type and name for the setElement method and +the 'post' typemap attribute allows adding code after the JNI call. +The 'post' code is generated into a finally block after the JNI call so the resulting code isn't quite +as mentioned earlier, setElement is actually: +

        -

        25.10.13 Date marshalling using the javain typemap and associated attributes

        +
        +
        +  public void setElement(Element e) {
        +    try {
        +      exampleJNI.Container_setElement(swigCPtr, this, Element.getCPtr(e), e);
        +    } finally {
        +      elementReference = e;
        +    }
        +  }
        +
        +
        + +

        27.10.13 Date marshalling using the javain typemap and associated attributes

        @@ -8102,7 +8608,7 @@ The CDate & and const CDate & Java code is generated f

        where '$javaclassname' is translated into the proxy class name, CDate and '$javainput' is translated into the name of the parameter, eg dateIn. -From Java, the intention is then to call into a modifed API with something like: +From Java, the intention is then to call into a modified API with something like:

        @@ -8213,7 +8719,7 @@ A few things to note: -

        25.11 Living with Java Directors

        +

        27.11 Living with Java Directors

        @@ -8392,10 +8898,10 @@ public abstract class UserVisibleFoo extends Foo {

      • -

        25.12 Odds and ends

        +

        27.12 Odds and ends

        -

        25.12.1 JavaDoc comments

        +

        27.12.1 JavaDoc comments

        @@ -8451,7 +8957,7 @@ public class Barmy { -

        25.12.2 Functional interface without proxy classes

        +

        27.12.2 Functional interface without proxy classes

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

        25.12.3 Using your own JNI functions

        +

        27.12.3 Using your own JNI functions

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

        -

        25.12.4 Performance concerns and hints

        +

        27.12.4 Performance concerns and hints

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

        -

        25.12.5 Debugging

        +

        27.12.5 Debugging

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

        -

        25.13 Java Examples

        +

        27.13 Java Examples

        diff --git a/Doc/Manual/Javascript.html b/Doc/Manual/Javascript.html index b1ec37055..cce5b5e2e 100644 --- a/Doc/Manual/Javascript.html +++ b/Doc/Manual/Javascript.html @@ -1,13 +1,13 @@ - + -

        26 SWIG and Javascript

        +

        28 SWIG and Javascript

          @@ -52,21 +52,21 @@

          This chapter describes SWIG's support of Javascript. It does not cover SWIG basics, but only information that is specific to this module.

          -

          26.1 Overview

          +

          28.1 Overview

          Javascript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions. Its arguably the most popular language for web development. -Javascript has gone beyond being a browser-based scripting language and with node.js, it is also used as a backend development language.

          +Javascript has gone beyond being a browser-based scripting language and with node.js, it is also used as a backend development language.

          Native Javascript extensions can be used for applications that embed a web-browser view or that embed a Javascript engine (such as node.js). Extending a general purpose web-browser is not possible as this would be a severe security issue.

          -

          SWIG Javascript currently supports JavascriptCore, the Javascript engine used by Safari/Webkit, and v8, which is used by Chromium and node.js.

          -

          WebKit is a modern browser implementation available as open-source which can be embedded into an application. +

          SWIG Javascript currently supports JavascriptCore, the Javascript engine used by Safari/Webkit, and v8, which is used by Chromium and node.js.

          +

          WebKit is a modern browser implementation available as open-source which can be embedded into an application. With node-webkit there is a platform which uses Google's Chromium as Web-Browser widget and node.js for javascript extensions.

          -

          26.2 Preliminaries

          +

          28.2 Preliminaries

          -

          26.2.1 Running SWIG

          +

          28.2.1 Running SWIG

          Suppose that you defined a SWIG module such as the following:

          @@ -101,7 +101,7 @@ that era had a component > 99. For example:

           $ swig -c++ -javascript -v8 -DV8_VERSION=0x032530 example.i
        -

        If you're targetting V8 >= 4.3.0, you would just run swig like so:

        +

        If you're targeting V8 >= 4.3.0, you would just run swig like so:

         $ swig -c++ -javascript -v8 example.i
        @@ -121,7 +121,7 @@ void example_initialize(v8::Handle<v8::Object> exports) Note: be aware that v8 has a C++ API, and thus, the generated modules must be compiled as C++.

        -

        26.2.2 Running Tests and Examples

        +

        28.2.2 Running Tests and Examples

        The configuration for tests and examples currently supports Linux and Mac only and not MinGW (Windows) yet.

        @@ -153,7 +153,7 @@ $ make check-javascript-test-suite ENGINE=jsc $ make check-javascript-examples V8_VERSION=0x032530 ENGINE=v8
        -

        26.2.3 Known Issues

        +

        28.2.3 Known Issues

        At the moment, the Javascript generators pass all tests syntactically, i.e., the generated source code compiles. However, there are still remaining runtime issues.

        @@ -161,21 +161,20 @@ $ make check-javascript-examples V8_VERSION=0x032530 ENGINE=v8
        • Default optional arguments do not work for all targeted interpreters

        • Multiple output arguments do not work for JSC

        • -
        • C89 incompatibily: the JSC generator might still generate C89 violating code

        • +
        • C89 incompatibility: the JSC generator might still generate C89 violating code

        • long long is not supported

        • -
        • %native is not supported

        • Javascript callbacks are not supported

        • instanceOf does not work under JSC

        The primary development environment has been Linux (Ubuntu 12.04). Windows and Mac OS X have been tested sporadically. Therefore, the generators might have more issues on those platforms. Please report back any problem you observe to help us improving this module quickly.

        -

        26.3 Integration

        +

        28.3 Integration

        This chapter gives a short introduction how to use a native Javascript extension: as a node.js module, and as an extension for an embedded Webkit.

        -

        26.3.1 Creating node.js Extensions

        +

        28.3.1 Creating node.js Extensions

        To install node.js you can download an installer from their web-site for Mac OS X and Windows. For Linux you can either build the source yourself and run sudo checkinstall or keep to the (probably stone-age) packaged version. For Ubuntu there is a PPA available.

        @@ -221,7 +220,7 @@ require("./build/Release/example")

        A more detailed explanation is given in the Examples section.

        -

        26.3.1.1 Troubleshooting

        +

        28.3.1.1 Troubleshooting

          @@ -233,12 +232,12 @@ require("./build/Release/example") $ sudo apt-get remove gyp -

          26.3.2 Embedded Webkit

          +

          28.3.2 Embedded Webkit

          Webkit is pre-installed on Mac OS X and available as a library for GTK.

          -

          26.3.2.1 Mac OS X

          +

          28.3.2.1 Mac OS X

          There is general information about programming with WebKit on Apple Developer Documentation. Details about Cocoa programming are not covered here.

          @@ -286,10 +285,10 @@ extern bool example_initialize(JSGlobalContextRef context, JSObjectRef* exports) @end -

          26.3.2.2 GTK

          +

          28.3.2.2 GTK

          -

          There is general information about programming GTK at GTK documentation and in the GTK tutorial, and for Webkit there is a Webkit GTK+ API Reference.

          +

          There is general information about programming GTK at GTK documentation and in the GTK tutorial, and for Webkit there is a Webkit GTK+ API Reference.

          An integration of a native extension 'example' would look like this:

          @@ -331,7 +330,7 @@ int main(int argc, char* argv[])
           }
          -

          26.3.3 Creating Applications with node-webkit

          +

          28.3.3 Creating Applications with node-webkit

          To get started with node-webkit there is a very informative set of wiki pages.

          @@ -422,12 +421,12 @@ open new windows, and many more things. }; -

          26.4 Examples

          +

          28.4 Examples

          Some basic examples are shown here in more detail.

          -

          26.4.1 Simple

          +

          28.4.1 Simple

          The common example simple looks like this:

          @@ -477,7 +476,7 @@ example.Foo = 3.1415926;

          Note: ECMAScript 5, the currently implemented Javascript standard, does not have modules. node.js and other implementations provide this mechanism defined by the CommonJS group. For browsers this is provided by Browserify, for instance.

          -

          26.4.2 Class

          +

          28.4.2 Class

          The common example class defines three classes, Shape, Circle, and Square:

          @@ -604,15 +603,15 @@ at ReadStream.EventEmitter.emit (events.js:98:17) at emitKey (readline.js:1095:12)

          -Note: In ECMAScript 5 there is no concept for classes. Instead each function can be used as a constructor function which is executed by the 'new' operator. Furthermore, during construction the key property prototype of the constructor function is used to attach a prototype instance to the created object. A prototype is essentially an object itself that is the first-class delegate of a class used whenever the access to a property of an object fails. The very same prototype instance is shared among all instances of one type. Prototypal inheritance is explained in more detail on in Inheritance and the prototype chain, for instance. +Note: In ECMAScript 5 there is no concept for classes. Instead each function can be used as a constructor function which is executed by the 'new' operator. Furthermore, during construction the key property prototype of the constructor function is used to attach a prototype instance to the created object. A prototype is essentially an object itself that is the first-class delegate of a class used whenever the access to a property of an object fails. The very same prototype instance is shared among all instances of one type. Prototypal inheritance is explained in more detail on in Inheritance and the prototype chain, for instance.

          -

          26.5 Implementation

          +

          28.5 Implementation

          The Javascript Module implementation has taken a very different approach compared to other language modules in order to support different Javascript interpreters.

          -

          26.5.1 Source Code

          +

          28.5.1 Source Code

          The Javascript module is implemented in Source/Modules/javascript.cxx. It dispatches the code generation to a JSEmitter instance, V8Emitter or JSCEmitter. Additionally there are some helpers: Template, for templated code generation, and JSEmitterState, which is used to manage state information during AST traversal. This rough map shall make it easier to find a way through this huge source file:

          @@ -713,7 +712,7 @@ Template::Template(const String *code_) { ... } ... -

          26.5.2 Code Templates

          +

          28.5.2 Code Templates

          All generated code is created on the basis of code templates. The templates for JavascriptCore can be found in Lib/javascript/jsc/javascriptcode.swg, for v8 in Lib/javascript/v8/javascriptcode.swg.

          @@ -752,7 +751,7 @@ t_register.replace("$jsparent", state.clazz(NAME_MANGLED))

          Template creates a copy of that string and Template::replace uses Swig's Replaceall to replace variables in the template. Template::trim can be used to eliminate leading and trailing whitespaces. Template::print is used to write the final template string to a Swig DOH (based on Printv). All methods allow chaining.

          -

          26.5.3 Emitter

          +

          28.5.3 Emitter

          The Javascript module delegates code generation to a JSEmitter instance. The following extract shows the essential interface:

          @@ -871,7 +870,7 @@ int JAVASCRIPT::classHandler(Node *n) {

          In enterClass the emitter stores state information that is necessary when processing class members. In exitClass the wrapper code for the whole class is generated.

          -

          26.5.4 Emitter states

          +

          28.5.4 Emitter states

          For storing information during the AST traversal the emitter provides a JSEmitterState with different slots to store data representing the scopes global, class, function, and variable.

          @@ -915,7 +914,7 @@ state.clazz(NAME, Getattr(n, "sym:name"));

          State information can be retrieved using state.clazz(NAME) or with Getattr on state.clazz() which actually returns a Hash instance.

          -

          26.5.5 Handling Exceptions in JavascriptCore

          +

          28.5.5 Handling Exceptions in JavascriptCore

          Applications with an embedded JavascriptCore should be able to present detailed exception messages that occur in the Javascript engine. Below is an example derived from code provided by Brian Barnes on how these exception details can be extracted.

          diff --git a/Doc/Manual/Library.html b/Doc/Manual/Library.html index 4bad9a03e..5f72b557d 100644 --- a/Doc/Manual/Library.html +++ b/Doc/Manual/Library.html @@ -7,31 +7,38 @@ -

          9 SWIG library

          +

          12 SWIG library

          -

          9.4 STL/C++ Library

          +

          12.4 STL/C++ library

          @@ -1385,16 +1393,24 @@ The following table shows which C++ classes are supported and the equivalent SWI SWIG Interface library file + std::array (C++11) array std_array.i std::auto_ptr memory std_auto_ptr.i + std::complex complex std_complex.i std::deque deque std_deque.i std::list list std_list.i std::map map std_map.i + std::multimap (C++11) multimap std_multimap.i + std::multiset (C++11) multiset std_multiset.i std::pair utility std_pair.i std::set set std_set.i std::string string std_string.i + std::unordered_map (C++11) unordered_map std_unordered_map.i + std::unordered_multimap (C++11) unordered_multimap std_unordered_multimap.i + std::unordered_multiset (C++11) unordered_multiset std_unordered_multiset.i + std::unordered_set (C++11) unordered_set std_unordered_set.i std::vector vector std_vector.i - std::array array (C++11) std_array.i - std::shared_ptr shared_ptr (C++11) std_shared_ptr.i + std::wstring wstring std_wstring.i + std::shared_ptr (C++11) shared_ptr std_shared_ptr.i @@ -1404,7 +1420,7 @@ Please look for the library files in the appropriate language library directory.

          -

          9.4.1 std::string

          +

          12.4.1 std::string

          @@ -1460,7 +1476,7 @@ In the target language:

           x = my_struct();
          -x.foo="Hello World";      # assign with string
          +x.foo = "Hello World";    # assign with string
           print x.foo;              # print as string
           
          @@ -1488,7 +1504,7 @@ void foo(string s, const String &t); // std_string typemaps still applie
          -

          9.4.2 std::vector

          +

          12.4.2 std::vector

          @@ -1565,8 +1581,8 @@ std::vector<double> half(const std::vector<double>& v) { } void halve_in_place(std::vector<double>& v) { - std::transform(v.begin(), v.end(), v.begin(), - std::bind2nd(std::divides<double>(), 2.0)); + for (std::vector<double>::iterator it = v.begin(); it != v.end(); ++it) + *it /= 2.0; } @@ -1667,7 +1683,7 @@ if you want to make their head explode. details and the public API exposed to the interpreter vary.

          -

          9.4.3 STL exceptions

          +

          12.4.3 STL exceptions

          @@ -1717,7 +1733,10 @@ 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.

          -

          9.4.4 shared_ptr smart pointer

          +

          12.4.4 shared_ptr smart pointer

          + + +

          12.4.4.1 shared_ptr basics

          @@ -1813,8 +1832,11 @@ System.out.println(val1 + " " + val2); +

          12.4.4.2 shared_ptr and inheritance

          + +

          -This shared_ptr library works quite differently to SWIG's normal, but somewhat limited, +The shared_ptr library works quite differently to SWIG's normal, but somewhat limited, smart pointer handling. The shared_ptr library does not generate extra wrappers, just for smart pointer handling, in addition to the proxy class. The normal proxy class including inheritance relationships is generated as usual. @@ -1892,7 +1914,7 @@ Adding the missing %shared_ptr macros will fix this:

          -%include "boost_shared_ptr.i"
          +%include <boost_shared_ptr.i>
           %shared_ptr(GrandParent);
           %shared_ptr(Parent);
           %shared_ptr(Child);
          @@ -1901,14 +1923,79 @@ Adding the missing %shared_ptr macros will fix this:
           
          +

          12.4.4.3 shared_ptr and method overloading

          + +

          -Note: There is somewhat limited support for %shared_ptr and the director feature -and the degrees of success varies among the different target languages. -Please help to improve this support by providing patches with improvements. +A C++ compiler can disambiguate a method overloaded by a shared_ptr and one using the raw underlying type. +For example, either one of these methods can be called in C++: +

          + +
          +
          +int age(std::shared_ptr<GrandParent> num);
          +int age(GrandParent& num);
          +
          +
          + +

          +When wrapped by SWIG, disambiguation is not possible using the overloaded names as there is just one equivalent type (GrandParent) in the target language. +SWIG will choose to wrap just the first method by default. +Ambiguity in overloading discusses ways to control which method(s) gets wrapped using %ignore or %rename. +For the interested reader, SWIG detects that they are equivalent types via the typecheck typemaps in the shared_ptr library. +

          + +

          12.4.4.4 shared_ptr and templates

          + + +

          +The %shared_ptr macro should be used for all the required instantiations +of the template before each of the %template instantiations. +For example, consider number.h containing the following illustrative template: +

          + +
          +
          +#include <memory>
          +
          +template<int N> struct Number {
          +  int num;
          +  Number() : num(N) {}
          +  static std::shared_ptr<Number<N>> make() { return std::make_shared<Number<N>>(); }
          +};
          +
          +
          + +

          +The SWIG code below shows the required ordering: +

          + +
          +
          +%include <std_shared_ptr.i>
          +
          +%shared_ptr(Number<10>);
          +%shared_ptr(Number<42>);
          +
          +%{
          +  #include "number.h"
          +%}
          +%include "number.h"
          +
          +%template(Number10) Number<10>;
          +%template(Number42) Number<42>;
          +
          +
          + +

          12.4.4.5 shared_ptr and directors

          + + +

          +The languages that support shared_ptr also have support for using shared_ptr with directors.

          -

          9.4.5 auto_ptr smart pointer

          +

          12.4.5 auto_ptr smart pointer

          @@ -1957,10 +2044,10 @@ int value = k.getValue(); -

          9.5 Utility Libraries

          +

          12.5 Utility Libraries

          -

          9.5.1 exception.i

          +

          12.5.1 exception.i

          diff --git a/Doc/Manual/Lisp.html b/Doc/Manual/Lisp.html index ba42f735c..6eb448a12 100644 --- a/Doc/Manual/Lisp.html +++ b/Doc/Manual/Lisp.html @@ -7,11 +7,10 @@ -

          27 SWIG and Common Lisp

          +

          29 SWIG and Common Lisp

          @@ -38,26 +34,17 @@ finance, and also common in computer science education. There are more than 9 different implementations of common lisp which are available, all have different foreign function - interfaces. SWIG currently supports only the Allegro Common - Lisp, Common Foreign Function Interface(CFFI), CLisp and UFFI - foreign function interfaces. -

          -

          27.1 Allegro Common Lisp

          - - -

          - Allegro Common Lisp support in SWIG has been updated to include - support for both C and C++. You can read about the interface - here + interfaces. SWIG currently supports the + Common Foreign Function Interface(CFFI).

          -

          27.2 Common Foreign Function Interface(CFFI)

          +

          29.2 Common Foreign Function Interface(CFFI)

          CFFI, the Common Foreign Function Interface, is a portable foreign - function interface for ANSI Common Lisp systems, similar in - spirit to UFFI. Unlike UFFI, CFFI requires only a small set of + function interface for ANSI Common Lisp systems. + CFFI requires only a small set of low-level functionality from the Lisp implementation, such as calling a foreign function by name, allocating foreign memory, and dereferencing pointers. @@ -78,18 +65,9 @@ swig -cffi -module module-name file-name files and the various things which you can do with them.

          -

          27.2.1 Additional Commandline Options

          +

          29.2.1 Additional Commandline Options

          -

          -The following table list the additional commandline options available for the CLISP module. They can also be seen by using: -

          - -
          -swig -cffi -help 
          -
          -
          - @@ -119,12 +97,15 @@ swig -cffi -help
          CFFI specific options
          -

          27.2.2 Generating CFFI bindings

          +

          29.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, let's assume that we have a file named test.h with the following C code: +

           #define y 5
          @@ -155,7 +136,10 @@ void lispsort_double (int n, double * array);
           enum color { RED, BLUE, GREEN};
           
          +

          Corresponding to this we will write a simple interface file: +

          +
           %module test
           
          @@ -163,7 +147,9 @@ Corresponding to this we will write a simple interface file:
           
           
          +

          The generated SWIG Code will be: +

           ;;;SWIG wrapper code starts here
          @@ -395,7 +381,7 @@ The feature intern_function ensures that all C names are
           
           
          -

          27.2.3 Generating CFFI bindings for C++ code

          +

          29.2.3 Generating CFFI bindings for C++ code

          This feature to SWIG (for CFFI) is very new and still far from @@ -430,8 +416,10 @@ Also, while parsing the C++ file and generating C wrapper code SWIG %include "target/header.h" +

          Various features which were available for C headers can also be used here. The target header which we are going to use here is: +

           namespace OpenDemo {
             class Test
          @@ -478,8 +466,10 @@ namespace OpenDemo {
           %include "test.cpp"
           
          +

          SWIG generates 3 files, the first one is a C wrap which we don't show, the second is the plain CFFI wrapper which is as shown below: +

           (cffi:defcfun ("_wrap_Test_x_set" Test_x_set) :void
             (self :pointer)
          @@ -528,11 +518,13 @@ SWIG generates 3 files, the first one is a C wrap which we don't show,
           (cffi:defcfun ("_wrap_RandomUnitVectorOnXZPlane" RandomUnitVectorOnXZPlane) :pointer)
           
          +

          The output is pretty good but it fails in disambiguating overloaded functions such as the constructor, in this case. One way of resolving this problem is to make the interface use the rename directiv, but hopefully there are better solutions. In addition SWIG also generates, a CLOS file +

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

          27.2.4 Inserting user code into generated files

          +

          29.2.4 Inserting user code into generated files

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

          -

          27.3 CLISP

          - - -

          -CLISP is a feature-loaded - implementation of common lisp which is portable across most of the - operating system environments and hardware. CLISP includes an - interpreter, a compiler, a debugger, CLOS, MOP, a foreign - language interface, i18n, regular expressions, a socket - interface, and more. An X11 interface is available through CLX, - Garnet and CLUE/CLIO. Command line editing is provided by - readline. CLISP runs Maxima, ACL2 and many other Common Lisp - packages. -

          -

          - To run the clisp module of SWIG requires very little effort, you - just need to execute: -

          -
          -swig -clisp -module module-name   file-name 
          -
          -
          - -

          - Because of the high level nature of the CLISP FFI, the bindings - generated by SWIG may not be absolutely correct, and you may need - to modify them. The good thing is that you don't need to complex - interface file for the CLISP module. The CLISP module tries to - produce code which is both human readable and easily modifyable. -

          -

          27.3.1 Additional Commandline Options

          - - -

          -The following table list the additional commandline options available for the CLISP module. They can also be seen by using: -

          - -
          -swig -clisp -help 
          -
          -
          - - - - - - - - - - - - - - - -
          CLISP specific options
          -extern-allIf this option is given then clisp definitions for all the functions
          -and global variables will be created otherwise only definitions for
          -externed functions and variables are created. -
          -generate-typedefIf this option is given then def-c-type will be used to generate
          -shortcuts according to the typedefs in the input. -
          - -

          27.3.2 Details on CLISP bindings

          - - -

          -As mentioned earlier the CLISP bindings generated by SWIG may need -some modifications. The clisp module creates a lisp file with -the same name as the module name. This -lisp file contains a 'defpackage' declaration, with the -package name same as the module name. This package uses the -'common-lisp' and 'ffi' packages. Also, package exports all -the functions, structures and variables for which an ffi -binding was generated.
          -After generating the defpackage statement, the clisp module also -sets the default language. - -

          -(defpackage :test
          -    (:use :common-lisp :ffi)
          -  (:export
          -   :make-bar
          -   :bar-x
          -   :bar-y
          -   :bar-a
          -   :bar-b
          -   :bar-z
          -   :bar-n
          -   :pointer_func
          -   :func123
          -   :make-cfunr
          -   :lispsort_double
          -   :test123))
          -
          -(in-package :test)
          -
          -(default-foreign-language :stdc)
          -
          -

          -The ffi wrappers for functions and variables are generated as shown - below. When functions have arguments of type "double * array", - SWIG doesn't knows whether it is an 'out' argument or it is - an array which will be passed, so SWIG plays it safe by - declaring it as an '(array (ffi:c-ptr DOUBLE-FLOAT))'. For - arguments of type "int **z[100]" where SWIG has more - information, i.e., it knows that 'z' is an array of pointers to - pointers of integers, SWIG defines it to be '(z (ffi:c-ptr - (ffi:c-array (ffi:c-ptr (ffi:c-ptr ffi:int)) 100)))' -

          -
          -extern "C" {
          -int pointer_func(void (*ClosureFun)( void* _fun, void* _data, void* _evt ), int y);
          -
          -int func123(div_t * x, int **z[100], int y[][1000][10]);
          -
          -void lispsort_double (int n, double * array);
          -
          -void test123(float x , double y);
          -
          -}
          -
          -
          -(ffi:def-call-out pointer_func
          -    (:name "pointer_func")
          -  (:arguments (ClosureFun (ffi:c-function (:arguments (arg0 (ffi:c-pointer NIL))
          -                                                      (arg1 (ffi:c-pointer NIL))
          -                                                      (arg2 (ffi:c-pointer NIL)))
          -                                          (:return-type NIL)))
          -              (y ffi:int))
          -  (:return-type ffi:int)
          -  (:library +library-name+))
          -
          -(ffi:def-call-out func123
          -    (:name "func123")
          -  (:arguments (x (ffi:c-pointer div_t))
          -              (z (ffi:c-ptr (ffi:c-array (ffi:c-ptr (ffi:c-ptr ffi:int)) 100)))
          -              (y (ffi:c-ptr (ffi:c-ptr (ffi:c-array ffi:int (1000 10))))))
          -  (:return-type ffi:int)
          -  (:library +library-name+))
          -
          -
          -(ffi:def-call-out lispsort_double
          -    (:name "lispsort_double")
          -  (:arguments (n ffi:int)
          -              (array (ffi:c-ptr DOUBLE-FLOAT)))
          -  (:return-type NIL)
          -  (:library +library-name+))
          -
          -(ffi:def-call-out test123
          -    (:name "test")
          -  (:arguments (x SINGLE-FLOAT)
          -              (y DOUBLE-FLOAT))
          -  (:return-type NIL)
          -  (:library +library-name+))
          -
          -
          - -

          -The module also handles strutcures and #define constants as shown - below. SWIG automatically adds the constructors and accessors - created for the struct to the list of symbols exported by the - package. -

          -
          -struct bar {
          -  short x, y;
          -  char a, b;
          -  int *z[1000];
          -  struct bar * n;
          -};
          -
          -#define max 1000
          -
          -
          -(ffi:def-c-struct bar
          -    (x :type ffi:short)
          -  (y :type ffi:short)
          -  (a :type character)
          -  (b :type character)
          -  (z :type (ffi:c-array (ffi:c-ptr ffi:int) 1000))
          -  (n :type (ffi:c-pointer bar)))
          -
          -(defconstant max 1000)
          -
          -
          - -

          27.4 UFFI

          - - diff --git a/Doc/Manual/Lua.html b/Doc/Manual/Lua.html index c94fe31dc..80807baf4 100644 --- a/Doc/Manual/Lua.html +++ b/Doc/Manual/Lua.html @@ -7,7 +7,7 @@ -

          28 SWIG and Lua

          +

          29 SWIG and Lua

            @@ -77,20 +77,20 @@

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

            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

            -

            28.1 Preliminaries

            +

            29.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 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'.

            -

            28.2 Running SWIG

            +

            29.2 Running SWIG

            @@ -138,14 +138,14 @@ $ 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.

            -

            28.2.1 Additional command line options

            +

            29.2.1 Additional command line options

            The following table list the additional commandline options available for the Lua module. They can also be seen by using:

            -
            +
             swig -lua -help 
             
            @@ -179,7 +179,7 @@ swig -lua -help -

            28.2.2 Compiling and Linking and Interpreter

            +

            29.2.2 Compiling and Linking and Interpreter

            @@ -250,7 +250,7 @@ LUALIB_API int ( luaopen_mod )(lua_State *L ); More information on building and configuring eLua can be found here: http://www.eluaproject.net/doc/v0.8/en_building.html

            -

            28.2.3 Compiling a dynamic module

            +

            29.2.3 Compiling a dynamic module

            @@ -318,7 +318,7 @@ Is quite obvious (Go back and consult the Lua documents on how to enable loadlib -

            28.2.4 Using your module

            +

            29.2.4 Using your module

            @@ -336,19 +336,19 @@ $ ./my_lua >

            -

            28.3 A tour of basic C/C++ wrapping

            +

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

            -

            28.3.1 Modules

            +

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

            -

            28.3.2 Functions

            +

            29.3.2 Functions

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

          -

          28.3.3 Global variables

          +

          29.3.3 Global variables

          @@ -477,7 +477,7 @@ If you have used the -eluac option for your eLua module, you will have In general, functions of the form "variable_get()" and "variable_set()" are automatically generated by SWIG for use with -eluac.

          -

          28.3.4 Constants and enums

          +

          29.3.4 Constants and enums

          @@ -512,7 +512,7 @@ If you're using eLua and have used -elua or -eluac to generate Hello World -

          28.3.4.1 Constants/enums and classes/structures

          +

          29.3.4.1 Constants/enums and classes/structures

          @@ -568,7 +568,7 @@ If the -no-old-metatable-bindings option is used, then these old-style It is worth mentioning, that example.Test.TEST1 and example.Test_TEST1 are different entities and changing one does not change the other. Given the fact that these are constantes and they are not supposed to be changed, it is up to you to avoid such issues.

          -

          28.3.5 Pointers

          +

          29.3.5 Pointers

          @@ -606,7 +606,7 @@ Lua enforces the integrity of its userdata, so it is virtually impossible to cor nil -

          28.3.6 Structures

          +

          29.3.6 Structures

          @@ -710,7 +710,7 @@ For eLua with the -eluac option, structure manipulation has to be perfo In general, functions of the form "new_struct()", "struct_member_get()", "struct_member_set()" and "free_struct()" are automatically generated by SWIG for each structure defined in C. (Please note: This doesn't apply for modules generated with the -elua option)

          -

          28.3.7 C++ classes

          +

          29.3.7 C++ classes

          @@ -747,7 +747,8 @@ Stout

          Class data members are accessed in the same manner as C structures. Static class members present a special problem for Lua, as Lua doesn't have support for such features. Therefore, SWIG generates wrappers that try to work around some of these issues. To illustrate, suppose you have a class like this:

          -
          class Spam {
          +
          +class Spam {
           public:
             static void foo();
             static int bar;
          @@ -756,7 +757,7 @@ public:
           

          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
          @@ -774,7 +775,7 @@ It is not (currently) possible to access static members of an instance:
           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
          @@ -785,7 +786,7 @@ 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.
           

          -

          28.3.8 C++ inheritance

          +

          29.3.8 C++ inheritance

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

          It is safe to use multiple inheritance with SWIG.

          -

          28.3.9 Pointers, references, values, and arrays

          +

          29.3.9 Pointers, references, values, and arrays

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

          -

          28.3.10 C++ overloaded functions

          +

          29.3.10 C++ overloaded functions

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

          -

          28.3.11 C++ operators

          +

          29.3.11 C++ operators

          @@ -964,7 +965,8 @@ When wrapped, it works like you expect:

          One restriction with operator overloading support is that SWIG is not able to fully handle operators that aren't defined as part of the class. For example, if you had code like this

          -
          class Complex {
          +
          +class Complex {
           ...
           friend Complex operator+(double, const Complex &c);
           ...
          @@ -973,7 +975,8 @@ friend Complex operator+(double, const Complex &c);
           

          then SWIG doesn't know what to do with the friend function--in fact, it simply ignores it and issues a warning. You can still wrap the operator, but you may have to encapsulate it in a special function. For example:

          -
          %rename(Complex_add_dc) operator+(double, const Complex &);
          +
          +%rename(Complex_add_dc) operator+(double, const Complex &);
           ...
           Complex operator+(double, const Complex &c);
           
          @@ -984,7 +987,7 @@ There are ways to make this operator appear as part of the class using the % Also, be aware that certain operators don't map cleanly to Lua, and some Lua operators don't map cleanly to C++ operators. For instance, overloaded assignment operators don't map to Lua semantics and will be ignored, and C++ doesn't support Lua's concatenation operator (..).

          -In order to keep maximum compatibility within the different languages in SWIG, the Lua bindings uses the same set of operator names as python. Although internally it renames the functions to something else (on order to work with Lua). +In order to keep maximum compatibility within the different languages in SWIG, the Lua bindings uses the same set of operator names as Python. Although internally it renames the functions to something else (on order to work with Lua).

          The current list of operators which can be overloaded (and the alternative function names) are:

          • __add__ operator+ @@ -1008,11 +1011,10 @@ The following operators cannot be overloaded (mainly because they are not suppor

            SWIG also accepts the __str__() member function which converts an object to a string. This function should return a const char*, preferably to static memory. This will be used for the print() and tostring() functions in Lua. Assuming the complex class has a function

            -
            const char* __str__()
            -{
            -        static char buffer[255];
            -        sprintf(buffer, "Complex(%g, %g)", this->re(), this->im());
            -        return buffer;
            +
            const char* __str__() {
            +  static char buffer[255];
            +  sprintf(buffer, "Complex(%g, %g)", this->re(), this->im());
            +  return buffer;
             }
             

            @@ -1031,11 +1033,10 @@ Complex(10, 12)

            It is also possible to overload the operator[], but currently this cannot be automatically performed. To overload the operator[] you need to provide two functions, __getitem__() and __setitem__()

            -
            class Complex
            -{
            -        //....
            -        double __getitem__(int i)const; // i is the index, returns the data
            -        void __setitem__(int i, double d); // i is the index, d is the data
            +
            class Complex {
            +  //....
            +  double __getitem__(int i)const; // i is the index, returns the data
            +  void __setitem__(int i, double d); // i is the index, d is the data
             };
             

            @@ -1061,7 +1062,7 @@ operators and pseudo-operators):

          No other lua metafunction is inherited. For example, __gc is not inherited and must be redefined in every class. __tostring is subject to a special handling. If absent in class and in class bases, a default one will be provided by SWIG.

          -

          28.3.12 Class extension with %extend

          +

          29.3.12 Class extension with %extend

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

          -

          28.3.13 Using %newobject to release memory

          +

          29.3.13 Using %newobject to release memory

          If you have a function that allocates memory like this,

          @@ -1142,7 +1143,7 @@ char *foo();

          This will release the allocated memory.

          -

          28.3.14 C++ templates

          +

          29.3.14 C++ templates

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

          -

          28.3.15 C++ Smart Pointers

          +

          29.3.15 C++ Smart Pointers

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

          -

          28.3.16 C++ Exceptions

          +

          29.3.16 C++ Exceptions

          @@ -1372,7 +1373,7 @@ and the "Exception handling add exception specification to functions or globally (respectively).

          -

          28.3.17 Namespaces

          +

          29.3.17 Namespaces

          @@ -1423,7 +1424,7 @@ Now, from Lua usage is as follows: 19 >

          -

          28.3.17.1 Compatibility Note

          +

          29.3.17.1 Compatibility Note

          @@ -1439,7 +1440,7 @@ If SWIG is running in a backwards compatible way, i.e. without the -no-old-m

          -

          28.3.17.2 Names

          +

          29.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 @@ -1448,6 +1449,7 @@ Those names are in a form $classname_$symbolname and are added to the s 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 {
          @@ -1483,11 +1485,12 @@ surrounding scope without any prefixing. Pretending that Test2 is a struct, not
           >
           
          -

          28.3.17.3 Inheritance

          +

          29.3.17.3 Inheritance

          The internal organization of inheritance has changed. Consider the following C++ code:

          +
          %module example
           class Base {
             public:
          @@ -1504,6 +1507,7 @@ were squashed and added to corresponding derived class ST: Everything f
           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()
          @@ -1518,18 +1522,20 @@ 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
           >
           
          -

          28.4 Typemaps

          +

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

          -

          28.4.1 What is a typemap?

          +

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

          @@ -1557,7 +1563,7 @@ Received an integer : 6 720
          -

          28.4.2 Using typemaps

          +

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

          @@ -1610,7 +1616,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).

          -

          28.4.3 Typemaps and arrays

          +

          29.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 @@ -1674,7 +1680,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.

          -

          28.4.4 Typemaps and pointer-pointer functions

          +

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

          @@ -1708,7 +1714,7 @@ int Create_Math(iMath** pptr); // its creator (assume it mallocs) ptr=nil -- the iMath* will be GC'ed as normal
          -

          28.5 Writing typemaps

          +

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

          @@ -1717,7 +1723,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).

          -

          28.5.1 Typemaps you can write

          +

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

          @@ -1730,7 +1736,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).
        -

        28.5.2 SWIG's Lua-C API

        +

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

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

        28.6 Customization of your Bindings

        +

        29.6 Customization of your Bindings

        @@ -1788,7 +1794,7 @@ This section covers adding of some small extra bits to your module to add the la -

        28.6.1 Writing your own custom wrappers

        +

        29.6.1 Writing your own custom wrappers

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

        -

        28.6.2 Adding additional Lua code

        +

        29.6.2 Adding additional Lua code

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

        -

        28.7 Details on the Lua binding

        +

        29.7 Details on the Lua binding

        @@ -1856,7 +1862,7 @@ See Examples/lua/arrays for an example of this code.

        -

        28.7.1 Binding global data into the module.

        +

        29.7.1 Binding global data into the module.

        @@ -1916,7 +1922,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)'.

        -

        28.7.2 Userdata and Metatables

        +

        29.7.2 Userdata and Metatables

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

        -

        28.7.3 Memory management

        +

        29.7.3 Memory management

        diff --git a/Doc/Manual/Makefile b/Doc/Manual/Makefile index ee9a0af34..9505adb91 100644 --- a/Doc/Manual/Makefile +++ b/Doc/Manual/Makefile @@ -89,3 +89,9 @@ linkchecker2: cp *.png linkchecker-tmp (cd linkchecker-tmp && linkchecker --config=../linkchecker.config -F text --no-warnings SWIGDocumentation.html) +# Simple check for relative links (there shouldn't be any), they don't translate properly creating the .pdf doc +# with wkhtmltopdf. For example, href="SWIG.html" needs to be href="SWIG.html#SWIG" +linkchecker3: + @echo "The following list should just contain SWIGDocumentation.html and SWIGDocumentation.pdf," + @echo "as all links should have an anchor (with a #) or be a full url beginning http." + grep 'href="' *.html | sed -e 's/.*href="\(.*\)">.*$$/\1/' | grep -v "#" | grep -v "^http" | grep -v "^style.css" diff --git a/Doc/Manual/Modula3.html b/Doc/Manual/Modula3.html index 75f3f80ff..fc4ffa03c 100644 --- a/Doc/Manual/Modula3.html +++ b/Doc/Manual/Modula3.html @@ -6,7 +6,7 @@ -

        29 SWIG and Modula-3

        +

        31 SWIG and Modula-3

        -

        29.4.5 Exceptions

        +

        31.4.5 Exceptions

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

        -

        29.4.6 Example

        +

        31.4.6 Example

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

        29.5 More hints to the generator

        +

        31.5 More hints to the generator

        -

        29.5.1 Features

        +

        31.5.1 Features

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

        29.5.2 Pragmas

        +

        31.5.2 Pragmas

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

        29.6 Remarks

        +

        31.6 Remarks

        +
      • Documentation Features +
      @@ -84,11 +88,11 @@ If you're not familiar with the Objective Caml language, you can visit The Ocaml Website.

      -

      31.1 Preliminaries

      +

      39.1 Preliminaries

      -SWIG 3.0 works with Ocaml 3.08.3 and above. Given the choice, +SWIG is compatible with OCaml 3.12.0 and above. Given the choice, you should use the latest stable release. The SWIG Ocaml module has been tested on Linux (x86, PPC, Sparc) and Cygwin on Windows. The best way to determine whether your system will work is to compile the @@ -102,7 +106,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.

      -

      31.1.1 Running SWIG

      +

      39.1.1 Running SWIG

      @@ -125,7 +129,7 @@ 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).

      -

      31.1.2 Compiling the code

      +

      39.1.2 Compiling the code

      @@ -142,7 +146,7 @@ Use ocamlc or ocamlopt to compile your SWIG interface like:

      -% swig -ocaml -co swig.mli ; swig -ocaml co swig.ml
      +% swig -ocaml -co swig.mli ; swig -ocaml -co swig.ml
       % ocamlc -c swig.mli ; ocamlc -c swig.ml
       % ocamlc -c -ccopt "-I/usr/include/foo" example_wrap.c
       % ocamlc -c example.mli
      @@ -162,7 +166,7 @@ in C++ mode, you must:

      -

      31.1.3 The camlp4 module

      +

      39.1.3 The camlp4 module

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

      31.1.4 Using your module

      +

      39.1.4 Using your module

      @@ -252,7 +256,7 @@ option to build your functions into the primitive list. This option is not needed when you build native code.

      -

      31.1.5 Compilation problems and compiling with C++

      +

      39.1.5 Compilation problems and compiling with C++

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

      -

      31.2 The low-level Ocaml/C interface

      +

      39.2 The low-level Ocaml/C interface

      @@ -336,7 +340,7 @@ appended. Upon return to caml space, the fnhelper function beautifies the result. A list containing a single item degrades to only that item (i.e. [ C_int 3 ] -> C_int 3), and a list containing more than one item is wrapped in C_list (i.e. [ C_char -'a' ; C_char 'b' -> C_list [ C_char 'a' ; C_char b +'a' ; C_char 'b' ] -> C_list [ C_char 'a' ; C_char 'b' ]). This is in order to make return values easier to handle when functions have only one return value, such as constructors, and operators. In addition, string, pointer, and object @@ -363,7 +367,7 @@ value items pass through directly, but you must make your own type signature for a function that uses value in this way.

      -

      31.2.1 The generated module

      +

      39.2.1 The generated module

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

      31.2.2 Enums

      +

      39.2.2 Enums

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

      31.2.2.1 Enum typing in Ocaml

      +

      39.2.2.1 Enum typing in Ocaml

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

      -

      31.2.3 Arrays

      +

      39.2.3 Arrays

      -

      31.2.3.1 Simple types of bounded arrays

      +

      39.2.3.1 Simple types of bounded arrays

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

      -

      31.2.3.2 Complex and unbounded arrays

      +

      39.2.3.2 Complex and unbounded arrays

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

      -

      31.2.3.3 Using an object

      +

      39.2.3.3 Using an object

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

      -

      31.2.3.4 Example typemap for a function taking float * and int

      +

      39.2.3.4 Example typemap for a function taking float * and int

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

      31.2.4 C++ Classes

      +

      39.2.4 C++ Classes

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

      -

      31.2.4.1 STL vector and string Example

      +

      39.2.4.1 STL vector and string Example

      @@ -660,7 +664,7 @@ module.

      -bash-2.05a$ ./example_top
      +bash-2.05a$ ./runme_top
               Objective Caml version 3.06
       
               Camlp4 Parsing version 3.06
      @@ -698,7 +702,7 @@ baz
       #
       
      -

      31.2.4.2 C++ Class Example

      +

      39.2.4.2 C++ Class Example

      @@ -728,7 +732,7 @@ public: }; -

      31.2.4.3 Compiling the example

      +

      39.2.4.3 Compiling the example

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

      31.2.4.4 Sample Session

      +

      39.2.4.4 Sample Session

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

      -

      31.2.5 Director Classes

      +

      39.2.5 Director Classes

      -

      31.2.5.1 Director Introduction

      +

      39.2.5.1 Director Introduction

      @@ -803,7 +807,7 @@ class foo { };

      -

      31.2.5.2 Overriding Methods in Ocaml

      +

      39.2.5.2 Overriding Methods in Ocaml

      @@ -831,11 +835,11 @@ In this example, I'll examine the objective caml code involved in providing an overloaded class. This example is contained in Examples/ocaml/shapes.

      -

      31.2.5.3 Director Usage Example

      +

      39.2.5.3 Director Usage Example

      -
      example_prog.ml
      +
      runme.ml
       open Swig
      @@ -854,13 +858,15 @@ let triangle_class pts ob meth args =
                  | _ -> raise (Failure "cover needs two double arguments."))
           | _ -> (invoke ob) meth args ;;
       
      +...
      +
       let triangle =
         new_derived_object
           new_shape
      -    (triangle_class ((0.0, 0.0), (0.5, 1.0), (1.0, 0.0)))
      +    (triangle_class ((0.0, 0.0), (0.5, 1.0), (1.0, 0.6)))
           '() ;;
       
      -let _ = _draw_shape_coverage '(triangle, C_int 60, C_int 20) ;;
      +let _ = _draw_shape_coverage '(triangle, 60, 20) ;;
       
      @@ -890,7 +896,7 @@ in a more effortless style in ocaml, while leaving the "engine" part of the program in C++.

      -

      31.2.5.4 Creating director objects

      +

      39.2.5.4 Creating director objects

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

      -

      31.2.5.5 Typemaps for directors, directorin, directorout, directorargout

      +

      39.2.5.5 Typemaps for directors, directorin, directorout, directorargout

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

      -

      31.2.5.6 typemap

      +

      39.2.5.6 directorin typemap

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

      -

      31.2.5.7 directorout typemap

      +

      39.2.5.7 directorout typemap

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

      -

      31.2.5.8 directorargout typemap

      +

      39.2.5.8 directorargout typemap

      @@ -981,14 +987,134 @@ 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.

      -

      31.2.6 Exceptions

      +

      39.2.6 Exceptions

      -Catching exceptions is now supported using SWIG's %exception feature. A simple -but not too useful example is provided by the throw_exception testcase in -Examples/test-suite. You can provide your own exceptions, too. +If an error occurs in a C or C++ function, you may want to convert that error into an OCaml +exception. To do this, you can use the %exception directive. The %exception +directive simply lets you rewrite part of the generated wrapper code to include an error check. +It is detailed in full in the Exception handling with %exception section.

      +

      +In C, a function often indicates an error by returning a status code (e.g. a negative number +or a NULL pointer). Here is a simple example of how you might handle that: +

      + +
      +
      +%exception malloc {
      +  $action
      +  if (result == NULL) {
      +    caml_failwith("Not enough memory");
      +  }
      +}
      +void *malloc(size_t nbytes);
      +
      +
      + +

      +In OCaml: +

      + +
      +
      +# let a = _malloc (C_int 20000000000);;
      +Exception: Failure "Not enough memory".
      +#
      +
      +
      + +

      +If a library provides some kind of general error handling framework, you can also use +that. For example: +

      + +
      +
      +%exception {
      +  $action
      +  if (err_occurred()) {
      +    caml_failwith(err_message());
      +  }
      +}
      +
      +
      + +

      +If no declaration name is given to %exception, it is applied to all wrapper functions. +$action is a SWIG special variable and is replaced by the C/C++ function call being wrapped. +

      + +

      +C++ exceptions are also easy to handle. We can catch a C++ exception and rethrow it as +an OCaml exception like this: +

      + +
      +
      +%exception getitem {
      +  try {
      +    $action
      +  } catch (std::out_of_range &e) {
      +    caml_failwith(e.what());
      +  }
      +}
      +
      +class FooClass {
      +  public:
      +    int getitem(int index);      // Exception handling added
      +    ...
      +};
      +
      +
      + +

      +The language-independent exception.i library file can also be used +to raise exceptions. See the SWIG Library chapter. +

      + +

      39.3 Documentation Features

      + + +

      +The features described in this section can be used to generate documentation +comments (colloquially referred to as "docstrings") that can be read by +OCamldoc. +

      + +

      39.3.1 Module docstring

      + + +

      +The first documentation comment of an mli file is the comment +associated with 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
      +
      +
      + +

      +When you have more than just a line or so, you can retain the +readability of the %module directive by using a macro. For +example: +

      + +
      +
      +%define DOCSTRING
      +"The `XmlResource` class allows program resources defining menus,
      +controls on a panel, etc. to be loaded from an XML file."
      +%enddef
      +
      +%module(docstring=DOCSTRING) xrc
      +
      +
      + diff --git a/Doc/Manual/Octave.html b/Doc/Manual/Octave.html index 4245d8a8e..bdef5db7c 100644 --- a/Doc/Manual/Octave.html +++ b/Doc/Manual/Octave.html @@ -9,7 +9,7 @@ -

      32 SWIG and Octave

      +

      30 SWIG and Octave

        @@ -60,16 +60,23 @@ This chapter is intended to give an introduction to using the module. You should 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).

        -

        32.1 Preliminaries

        +

        30.1 Preliminaries

        -As of SWIG 3.0.7, the Octave module is regularly tested with Octave versions 3.2.4, 3.8.1, and 4.0.0. -Use of older Octave versions is not recommended, as these versions are no longer tested with SWIG. +SWIG is regularly tested against the following versions of Octave: 3.8, 4.0, 4.2. +

        + +

        +Every effort is made to maintain backward compatibility with older versions of Octave. +This cannot be guaranteed however, as in recent times new Octave releases have required nontrivial updates to SWIG, which may break backward compatibility for older Octave versions against which SWIG is not regularly tested. +

        + +

        The SWIG runtime exports the function swig_octave_prereq() for checking the version of Octave.

        -

        32.2 Running SWIG

        +

        30.2 Running SWIG

        @@ -101,7 +108,7 @@ The -c++ option is also required when wrapping C++ code: This creates a C++ source file "example_wrap.cpp". A C++ file is generated even when wrapping C code as Octave is itself written in C++ and requires wrapper code to be in the same language. The generated C++ source file contains the low-level wrappers that need to be compiled and linked with the rest of your C/C++ application (in this case, the gcd implementation) to create an extension module.

        -

        32.2.1 Command-line options

        +

        30.2.1 Command-line options

        @@ -124,7 +131,7 @@ The special name "." loads C global variables into the module namespace, i.e. al The -opprefix options sets the prefix of the names of global/friend operator functions.

        -

        32.2.2 Compiling a dynamic module

        +

        30.2.2 Compiling a dynamic module

        @@ -151,7 +158,7 @@ $ mkoctfile example_wrap.cpp example.c

        octave:1> swigexample
        -

        32.2.3 Using your module

        +

        30.2.3 Using your module

        @@ -169,10 +176,10 @@ octave:4> swigexample.cvar.Foo=4; octave:5> swigexample.cvar.Foo ans = 4

      -

      32.3 A tour of basic C/C++ wrapping

      +

      30.3 A tour of basic C/C++ wrapping

      -

      32.3.1 Modules

      +

      30.3.1 Modules

      @@ -217,7 +224,7 @@ octave:4> swigexample.gcd(4, 6) ans = 2 -

      32.3.2 Functions

      +

      30.3.2 Functions

      @@ -234,7 +241,7 @@ int fact(int n);

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

      32.3.3 Global variables

      +

      30.3.3 Global variables

      @@ -287,7 +294,7 @@ octave:2> swigexample.PI=3.142; octave:3> swigexample.PI ans = 3.1420 -

      32.3.4 Constants and enums

      +

      30.3.4 Constants and enums

      @@ -309,7 +316,7 @@ swigexample.SCONST="Hello World" swigexample.SUNDAY=0 .... -

      32.3.5 Pointers

      +

      30.3.5 Pointers

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

      32.3.6 Structures and C++ classes

      +

      30.3.6 Structures and C++ classes

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

      -

      32.3.7 C++ inheritance

      +

      30.3.7 C++ inheritance

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

      -

      32.3.8 C++ overloaded functions

      +

      30.3.8 C++ overloaded functions

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

      -

      32.3.9 C++ operators

      +

      30.3.9 C++ operators

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

      -

      32.3.10 Class extension with %extend

      +

      30.3.10 Class extension with %extend

      @@ -653,7 +660,7 @@ Similarly, Octave can use the __float__ method to convert an object to Octave 3.8.0 and later versions will also map unary functions X() to the corresponding __X__ method, where X includes: abs(), acos(), acosh(), angle(), arg(), asin(), asinh(), atan(), atanh(), cbrt(), ceil(), conj(), cos(), cosh(), dawson(), erf(), erfc(), erfcinv(), erfcx(), erfi(), erfinv(), exp(), expm1(), finite(), fix(), floor(), gamma(), imag(), isalnum(), isalpha(), isascii(), iscntrl(), isdigit(), isgraph(), isinf(), islower(), isna(), isnan(), isprint(), ispunct(), isspace(), isupper(), isxdigit(), lgamma(), log(), log10(), log1p(), log2(), real(), round(), roundb(), signbit(), signum(), sin(), sinh(), sqrt(), tan(), tanh(), toascii(), tolower(), toupper()

      -

      32.3.11 C++ templates

      +

      30.3.11 C++ templates

      @@ -730,10 +737,10 @@ ans = -

      32.3.12 C++ Smart Pointers

      +

      30.3.12 C++ Smart Pointers

      -

      32.3.12.1 The shared_ptr Smart Pointer

      +

      30.3.12.1 The shared_ptr Smart Pointer

      @@ -744,14 +751,14 @@ in the shared_ptr smart pointer -

      32.3.12.2 Generic Smart Pointers

      +

      30.3.12.2 Generic Smart Pointers

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

      -

      32.3.13 Directors (calling Octave from C++ code)

      +

      30.3.13 Directors (calling Octave from C++ code)

      @@ -832,14 +839,14 @@ c-side routine called octave-side routine called -

      32.3.14 Threads

      +

      30.3.14 Threads

      The use of threads in wrapped Director code is not supported; i.e., an Octave-side implementation of a C++ class must be called from the Octave interpreter's thread. Anything fancier (apartment/queue model, whatever) is left to the user. Without anything fancier, this amounts to the limitation that Octave must drive the module... like, for example, an optimization package that calls Octave to evaluate an objective function.

      -

      32.3.15 Memory management

      +

      30.3.15 Memory management

      @@ -873,14 +880,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).

      -

      32.3.16 STL support

      +

      30.3.16 STL support

      Various STL library files are provided for wrapping STL containers.

      -

      32.3.17 Matrix typemaps

      +

      30.3.17 Matrix typemaps

      diff --git a/Doc/Manual/Perl5.html b/Doc/Manual/Perl5.html index 96e9f7517..1e7bd9f86 100644 --- a/Doc/Manual/Perl5.html +++ b/Doc/Manual/Perl5.html @@ -7,7 +7,7 @@ -

      33 SWIG and Perl5

      +

      31 SWIG and Perl5

        @@ -97,7 +97,7 @@ later. We're no longer testing regularly with older versions, but Perl 5.6 seems to mostly work, while older versions don't.

        -

        33.1 Overview

        +

        31.1 Overview

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

        -

        33.2 Preliminaries

        +

        31.2 Preliminaries

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

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

        -

        33.2.1 Getting the right header files

        +

        31.2.1 Getting the right header files

        @@ -175,7 +175,7 @@ $ perl -e 'use Config; print "$Config{archlib}\n";'

      -

      33.2.2 Compiling a dynamic module

      +

      31.2.2 Compiling a dynamic module

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

      -

      33.2.3 Building a dynamic module with MakeMaker

      +

      31.2.3 Building a dynamic module with MakeMaker

      @@ -242,7 +242,7 @@ the preferred approach to compilation. More information about MakeMaker can be found in "Programming Perl, 2nd ed." by Larry Wall, Tom Christiansen, and Randal Schwartz.

      -

      33.2.4 Building a static version of Perl

      +

      31.2.4 Building a static version of Perl

      @@ -311,7 +311,7 @@ added to it. Depending on your machine, you may need to link with additional libraries such as -lsocket, -lnsl, -ldl, etc.

      -

      33.2.5 Using the module

      +

      31.2.5 Using the module

      @@ -464,7 +464,7 @@ system configuration (this requires root access and you will need to read the man pages).

      -

      33.2.6 Compilation problems and compiling with C++

      +

      31.2.6 Compilation problems and compiling with C++

      @@ -607,7 +607,7 @@ have to find the macro that conflicts and add an #undef into the .i file. Pleas any conflicting macros you find to swig-user mailing list.

      -

      33.2.7 Compiling for 64-bit platforms

      +

      31.2.7 Compiling for 64-bit platforms

      @@ -634,7 +634,7 @@ also introduce problems on platforms that support more than one linking standard (e.g., -o32 and -n32 on Irix).

      -

      33.3 Building Perl Extensions under Windows

      +

      31.3 Building Perl Extensions under Windows

      @@ -645,7 +645,7 @@ section assumes you are using SWIG with Microsoft Visual C++ although the procedure may be similar with other compilers.

      -

      33.3.1 Running SWIG from Developer Studio

      +

      31.3.1 Running SWIG from Developer Studio

      @@ -708,7 +708,7 @@ print "$a\n"; -

      33.3.2 Using other compilers

      +

      31.3.2 Using other compilers

      @@ -716,7 +716,7 @@ SWIG is known to work with Cygwin and may work with other compilers on Windows. For general hints and suggestions refer to the Windows chapter.

      -

      33.4 The low-level interface

      +

      31.4 The low-level interface

      @@ -726,7 +726,7 @@ can be used to control your application. However, it is also used to construct more user-friendly proxy classes as described in the next section.

      -

      33.4.1 Functions

      +

      31.4.1 Functions

      @@ -749,7 +749,7 @@ use example; $a = &example::fact(2); -

      33.4.2 Global variables

      +

      31.4.2 Global variables

      @@ -819,7 +819,7 @@ extern char *path; // Declared later in the input -

      33.4.3 Constants

      +

      31.4.3 Constants

      @@ -859,7 +859,7 @@ print example::FOO, "\n"; -

      33.4.4 Pointers

      +

      31.4.4 Pointers

      @@ -949,7 +949,7 @@ Foo *BarToFoo(Bar *b) { } Foo *IncrFoo(Foo *f, int i) { - return f+i; + return f+i; } %} @@ -968,7 +968,7 @@ as XS and xsubpp. Given the advancement of the SWIG typesystem and the SWIG and XS, this is no longer supported.

      -

      33.4.5 Structures

      +

      31.4.5 Structures

      @@ -1057,7 +1057,7 @@ produces a single accessor function like this:

       int *Foo_x_get(Foo *self) {
      -    return self->x;
      +  return self->x;
       };
       
      @@ -1092,17 +1092,17 @@ generates accessor functions such as this:
       Foo *Bar_f_get(Bar *b) {
      -    return &b->f;
      +  return &b->f;
       }
       
       void Bar_f_set(Bar *b, Foo *val) {
      -    b->f = *val;
      +  b->f = *val;
       }
       
      -

      33.4.6 C++ classes

      +

      31.4.6 C++ classes

      @@ -1167,7 +1167,7 @@ provides direct access to C++ objects. A higher level interface using Perl prox can be built using these low-level accessors. This is described shortly.

      -

      33.4.7 C++ classes and type-checking

      +

      31.4.7 C++ classes and type-checking

      @@ -1203,7 +1203,7 @@ If necessary, the type-checker also adjusts the value of the pointer (as is nece multiple inheritance is used).

      -

      33.4.8 C++ overloaded functions

      +

      31.4.8 C++ overloaded functions

      @@ -1247,7 +1247,7 @@ example::Spam_foo_d($s, 3.14); Please refer to the "SWIG Basics" chapter for more information.

      -

      33.4.9 Operators

      +

      31.4.9 Operators

      @@ -1274,7 +1274,7 @@ The following C++ operators are currently supported by the Perl module:

    • operator or
    -

    33.4.10 Modules and packages

    +

    31.4.10 Modules and packages

    @@ -1369,7 +1369,7 @@ print Foo::fact(4), "\n"; # Call a function in package FooBar --> -

    33.5 Input and output parameters

    +

    31.5 Input and output parameters

    @@ -1588,7 +1588,7 @@ print "$c\n"; Note: The REFERENCE feature is only currently supported for numeric types (integers and floating point).

    -

    33.6 Exception handling

    +

    31.6 Exception handling

    @@ -1633,9 +1633,8 @@ class DoubleArray { void setitem(int i, double val) { if ((i >= 0) && (i < n)) ptr[i] = val; - else { + else throw RangeError(); - } } }; @@ -1753,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.

    -

    33.7 Remapping datatypes with typemaps

    +

    31.7 Remapping datatypes with typemaps

    @@ -1770,7 +1769,7 @@ Typemaps are only used if you want to change some aspect of the primitive C-Perl interface.

    -

    33.7.1 A simple typemap example

    +

    31.7.1 A simple typemap example

    @@ -1874,7 +1873,7 @@ example::count("e", "Hello World"); -

    33.7.2 Perl5 typemaps

    +

    31.7.2 Perl5 typemaps

    @@ -1888,9 +1887,9 @@ like this:

     %typemap(out) int {
    -    $result = sv_newmortal();
    -    set_setiv($result, (IV) $1);
    -    argvi++;
    +  $result = sv_newmortal();
    +  sv_setiv($result, (IV) $1);
    +  argvi++;
     }
     
    @@ -1979,7 +1978,7 @@ Return of C++ member data (all languages). Check value of input parameter. -

    33.7.3 Typemap variables

    +

    31.7.3 Typemap variables

    @@ -2050,7 +2049,7 @@ properly assigned. The Perl name of the wrapper function being created. -

    33.7.4 Useful functions

    +

    31.7.4 Useful functions

    @@ -2119,7 +2118,7 @@ int sv_isa(SV *, char *0; -

    33.8 Typemap Examples

    +

    31.8 Typemap Examples

    @@ -2128,7 +2127,7 @@ might look at the files "perl5.swg" and "typemaps.i" in the SWIG library.

    -

    33.8.1 Converting a Perl5 array to a char **

    +

    31.8.1 Converting a Perl5 array to a char **

    @@ -2220,7 +2219,7 @@ print @$b, "\n"; # Print it out -

    33.8.2 Return values

    +

    31.8.2 Return values

    @@ -2249,7 +2248,7 @@ can be done using the EXTEND() macro as in: } -

    33.8.3 Returning values from arguments

    +

    31.8.3 Returning values from arguments

    @@ -2303,7 +2302,7 @@ print "multout(7, 13) = @r\n"; ($x, $y) = multout(7, 13); -

    33.8.4 Accessing array structure members

    +

    31.8.4 Accessing array structure members

    @@ -2313,8 +2312,8 @@ Consider the following data structure:

     #define SIZE  8
     typedef struct {
    -    int   values[SIZE];
    -    ...
    +  int   values[SIZE];
    +  ...
     } Foo;
     
     
    @@ -2328,10 +2327,10 @@ To make the member writable, a "memberin" typemap can be used.
     %typemap(memberin) int [SIZE] {
    -    int i;
    -    for (i = 0; i < SIZE; i++) {
    -        $1[i] = $input[i];
    -    }
    +  int i;
    +  for (i = 0; i < SIZE; i++) {
    +    $1[i] = $input[i];
    +  }
     }
     
     
    @@ -2366,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.

    -

    33.8.5 Turning Perl references into C pointers

    +

    31.8.5 Turning Perl references into C pointers

    @@ -2431,7 +2430,7 @@ print "$c\n"; -

    33.8.6 Pointer handling

    +

    31.8.6 Pointer handling

    @@ -2516,7 +2515,7 @@ For example: -

    33.9 Proxy classes

    +

    31.9 Proxy classes

    @@ -2532,7 +2531,7 @@ to the underlying code. This section describes the implementation details of the proxy interface.

    -

    33.9.1 Preliminaries

    +

    31.9.1 Preliminaries

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

    -

    33.9.2 Structure and class wrappers

    +

    31.9.2 Structure and class wrappers

    @@ -2600,48 +2599,48 @@ package example::Vector; %BLESSEDMEMBERS = (); sub new () { - my $self = shift; - my @args = @_; - $self = vectorc::new_Vector(@args); - return undef if (!defined($self)); - bless $self, "example::Vector"; - $OWNER{$self} = 1; - my %retval; - tie %retval, "example::Vector", $self; - return bless \%retval, "Vector"; + my $self = shift; + my @args = @_; + $self = vectorc::new_Vector(@args); + return undef if (!defined($self)); + bless $self, "example::Vector"; + $OWNER{$self} = 1; + my %retval; + tie %retval, "example::Vector", $self; + return bless \%retval, "Vector"; } sub DESTROY { - return unless $_[0]->isa('HASH'); - my $self = tied(%{$_[0]}); - delete $ITERATORS{$self}; - if (exists $OWNER{$self}) { - examplec::delete_Vector($self)); - delete $OWNER{$self}; - } + return unless $_[0]->isa('HASH'); + my $self = tied(%{$_[0]}); + delete $ITERATORS{$self}; + if (exists $OWNER{$self}) { + examplec::delete_Vector($self)); + delete $OWNER{$self}; + } } sub FETCH { - my ($self, $field) = @_; - my $member_func = "vectorc::Vector_${field}_get"; - my $val = &$member_func($self); - if (exists $BLESSEDMEMBERS{$field}) { - return undef if (!defined($val)); - my %retval; - tie %retval, $BLESSEDMEMBERS{$field}, $val; - return bless \%retval, $BLESSEDMEMBERS{$field}; - } - return $val; + my ($self, $field) = @_; + my $member_func = "vectorc::Vector_${field}_get"; + my $val = &$member_func($self); + if (exists $BLESSEDMEMBERS{$field}) { + return undef if (!defined($val)); + my %retval; + tie %retval, $BLESSEDMEMBERS{$field}, $val; + return bless \%retval, $BLESSEDMEMBERS{$field}; + } + return $val; } sub STORE { - my ($self, $field, $newval) = @_; - my $member_func = "vectorc::Vector_${field}_set"; - if (exists $BLESSEDMEMBERS{$field}) { - &$member_func($self, tied(%{$newval})); - } else { - &$member_func($self, $newval); - } + my ($self, $field, $newval) = @_; + my $member_func = "vectorc::Vector_${field}_set"; + if (exists $BLESSEDMEMBERS{$field}) { + &$member_func($self, tied(%{$newval})); + } else { + &$member_func($self, $newval); + } } @@ -2681,7 +2680,7 @@ $v->DESTROY(); -

    33.9.3 Object Ownership

    +

    31.9.3 Object Ownership

    @@ -2768,7 +2767,7 @@ counting, garbage collection, or advanced features one might find in sophisticated languages.

    -

    33.9.4 Nested Objects

    +

    31.9.4 Nested Objects

    @@ -2821,7 +2820,7 @@ $p->{f}->{x} = 0.0; %${$p->{v}} = ( x=>0, y=>0, z=>0); -

    33.9.5 Proxy Functions

    +

    31.9.5 Proxy Functions

    @@ -2842,11 +2841,11 @@ this:

     sub dot_product {
    -    my @args = @_;
    -    $args[0] = tied(%{$args[0]});         # Get the real pointer values
    -    $args[1] = tied(%{$args[1]});
    -    my $result = vectorc::dot_product(@args);
    -    return $result;
    +  my @args = @_;
    +  $args[0] = tied(%{$args[0]});         # Get the real pointer values
    +  $args[1] = tied(%{$args[1]});
    +  my $result = vectorc::dot_product(@args);
    +  return $result;
     }
     
    @@ -2855,7 +2854,7 @@ This function replaces the original function, but operates in an identical manner.

    -

    33.9.6 Inheritance

    +

    31.9.6 Inheritance

    @@ -2931,7 +2930,7 @@ particular, inheritance of data members is extremely tricky (and I'm not even sure if it really works).

    -

    33.9.7 Modifying the proxy methods

    +

    31.9.7 Modifying the proxy methods

    @@ -2959,7 +2958,7 @@ public: }; -

    33.10 Adding additional Perl code

    +

    31.10 Adding additional Perl code

    @@ -2985,7 +2984,7 @@ sub set_transform for (my $j = 0; $j < 4, $j++) { mat44_set($a, $i, $j, $x->[i][j]) - } + } } example.set_transform($im, $a); free_mat44($a); @@ -3010,7 +3009,7 @@ set_transform($im, $a); -

    33.11 Cross language polymorphism

    +

    31.11 Cross language polymorphism

    @@ -3044,7 +3043,7 @@ proxy classes, director classes, and C wrapper functions takes care of all the cross-language method routing transparently.

    -

    33.11.1 Enabling directors

    +

    31.11.1 Enabling directors

    @@ -3071,7 +3070,7 @@ 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 +// generate directors for the virtual methods in class Foo %feature("director") Foo; @@ -3089,7 +3088,7 @@ directors for specific classes or methods. So for example,

    -will generate directors for all virtual methods of class Foo except +will generate directors for the virtual methods of class Foo except bar().

    @@ -3104,14 +3103,14 @@ the methods one() and two() (but not three()): %feature("director") Foo; class Foo { public: - Foo(int foo); - virtual void one(); - virtual void two(); + Foo(int foo); + virtual void one(); + virtual void two(); }; class Bar: public Foo { public: - virtual void three(); + virtual void three(); }; @@ -3134,7 +3133,7 @@ sub one { -

    33.11.2 Director classes

    +

    31.11.2 Director classes

    @@ -3154,7 +3153,8 @@ 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 +Virtual methods that have a final specifier are unsurprisingly excluded. +Thus the 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 @@ -3214,7 +3214,7 @@ so there is no need for the extra overhead involved with routing the calls through Perl.

    -

    33.11.3 Ownership and object destruction

    +

    31.11.3 Ownership and object destruction

    @@ -3263,7 +3263,7 @@ sub DESTROY { -

    33.11.4 Exception unrolling

    +

    31.11.4 Exception unrolling

    @@ -3279,9 +3279,9 @@ suffice in most cases:

     %feature("director:except") {
    -    if ($error != NULL) {
    -        throw Swig::DirectorMethodException();
    -    }
    +  if ($error != NULL) {
    +    throw Swig::DirectorMethodException();
    +  }
     }
     
    @@ -3305,8 +3305,8 @@ suitable exception handler:
     %exception {
    -    try { $action }
    -    catch (Swig::DirectorException &e) { SWIG_fail; }
    +  try { $action }
    +  catch (Swig::DirectorException &e) { SWIG_fail; }
     }
     
    @@ -3319,7 +3319,7 @@ Swig::DirectorMethodException is thrown, Perl will register the exception as soon as the C wrapper function returns.

    -

    33.11.5 Overhead and code bloat

    +

    31.11.5 Overhead and code bloat

    @@ -3353,7 +3353,7 @@ directive) for only those methods that are likely to be extended in Perl.

    -

    33.11.6 Typemaps

    +

    31.11.6 Typemaps

    diff --git a/Doc/Manual/Php.html b/Doc/Manual/Php.html index 52bedf87f..09c514e94 100644 --- a/Doc/Manual/Php.html +++ b/Doc/Manual/Php.html @@ -7,7 +7,7 @@ -

    34 SWIG and PHP

    +

    32 SWIG and PHP

      @@ -50,20 +50,13 @@

      -In this chapter, we discuss SWIG's support of PHP. The PHP module -was extensively rewritten in release 1.3.26, and support for generating -OO wrappers for PHP5 was added in 1.3.30. The PHP module now supports most -of the features available in some of the other languages. +In this chapter, we discuss SWIG's support of PHP. SWIG currently supports +generating wrappers for PHP7. Support for PHP5 was removed in SWIG 4.0.0 +and support for PHP4 was removed in SWIG 1.3.37.

      -SWIG supports generating wrappers for PHP5 and PHP7. Support for PHP4 was removed -in SWIG 1.3.37. -

      - -

      -Currently any PHP5 or PHP7 release should work, but we don't regularly test with -PHP < 5.3. +Currently any PHP7 release should work.

      @@ -77,13 +70,13 @@ your extension into php directly, you will need the complete PHP source tree available.

      -

      34.1 Generating PHP Extensions

      +

      32.1 Generating PHP Extensions

      -To build a PHP extension, run swig using the -php5 or --php7 option as follows (-php is also supported -and currently is an alias for -php5): +To build a PHP extension, run swig using the -php7 option as follows +(-php is also supported and currently is an alias for -php7 +but prior to SWIG 4.0.0 it was an alias for -php5):

      @@ -107,9 +100,7 @@ also contain PHP class wrappers.
       SWIG can generate PHP extensions from C++ libraries as well when
       given the -c++ option.  The support for C++ is discussed in
       more detail in section 27.2.6.  The generated
      -C++ wrapper will be called example_wrap.cpp (for PHP5) or
      -example_wrap.cxx (for PHP7 where the default has been changed to align
      -with SWIG's default for every other language).  You can specify a
      +C++ wrapper will be called example_wrap.cxx.  You can specify a
       different extension for the C++ wrapper using -cppext -
       e.g. if you want example_wrap.cc use -cppext cc.
       

      @@ -128,7 +119,7 @@ and it doesn't play nicely with package system. We don't recommend this approach, or provide explicit support for it.

      -

      34.1.1 Building a loadable extension

      +

      32.1.1 Building a loadable extension

      @@ -143,7 +134,7 @@ least work for Linux though): gcc -shared example_wrap.o example.o -o example.so

      -

      34.1.2 Using PHP Extensions

      +

      32.1.2 Using PHP Extensions

      @@ -162,8 +153,8 @@ If the module is in PHP's default extension directory, you can omit the path.

      For some SAPIs (for example, the CLI SAPI) you can instead use the -dl() function to load -an extension at run time, by adding a like like this to the start of each +dl() function to load +an extension at run time, by adding a line like this to the start of each PHP script which uses your extension:

      @@ -172,8 +163,8 @@ PHP script which uses your extension:

    -But note that this doesn't work when running PHP through a webserver in PHP5.3 -and later - you'll need to use extension in php.ini as +But note that dl() isn't supported when running PHP through a +webserver - you'll need to use extension in php.ini as described above.

    @@ -191,7 +182,7 @@ This PHP module also defines the PHP classes for the wrapped API, so you'll almost certainly want to include it anyway.

    -

    34.2 Basic PHP interface

    +

    32.2 Basic PHP interface

    @@ -199,10 +190,11 @@ It is important to understand that PHP uses a single global namespace into which all symbols from extension modules are loaded. It is quite possible for names of symbols in one extension module to clash with other symbols unless care is taken to %rename them. At present -SWIG doesn't have support for the namespace feature added in PHP 5.3. +SWIG doesn't have support for generating wrappers which make use of PHP's +namespace feature.

    -

    34.2.1 Constants

    +

    32.2.1 Constants

    @@ -239,10 +231,12 @@ echo "E = " . E . "\n";

    There's one peculiarity of how constants work in PHP which it is useful to note (this is not specific to SWIG though) - if you try to use an undeclared -constant, PHP will emit a notice and then expand the constant to a string -version of the constant's name. Unfortunately it is easy to miss the notice -if you're using PHP in a webserver, as it will probably end up in error.log or -similar. +constant, PHP will emit a warning (or a notice in PHP 7.1 and earlier) and then +expand the constant to a string version of the constant's name. Unfortunately +it is easy to miss the warning message if you're using PHP in a webserver as +it will probably end up in error.log or similar. Apparently this will throw +an Error in a future version of PHP, but until then it's something to be +aware of.

    @@ -276,11 +270,10 @@ if(EASY_TO_MISPEL) {

    The mis-spelled constant will become the string 'EASY_TO_MISPEL', which is treated as true by the if test, when the value of the intended constant -would be treated as false! Modern versions of PHP will at least issue -a PHP notice by default when this happens. +would be treated as false!

    -

    34.2.2 Global Variables

    +

    32.2.2 Global Variables

    @@ -329,7 +322,7 @@ undefined. At this time SWIG does not support custom accessor methods.

    -

    34.2.3 Functions

    +

    32.2.3 Functions

    @@ -382,7 +375,7 @@ print $s; # The value of $s was not changed. --> -

    34.2.4 Overloading

    +

    32.2.4 Overloading

    @@ -390,8 +383,7 @@ Although PHP does not support overloading functions natively, swig will generate dispatch functions which will use %typecheck typemaps to allow overloading. This dispatch function's operation and precedence is described in Wrapping -Overloaded Functions and Methods. +href="SWIGPlus.html#SWIGPlus_overloaded_methods">Overloaded functions and methods.

    -

    34.2.5 Pointers and References

    +

    32.2.5 Pointers and References

    @@ -526,13 +518,6 @@ this, one needs to include phppointers.i which defines the named typemap REF.

    -

    -Prior to SWIG 3.0, the REF typemaps relied on PHP's call-time -pass-by-reference, which was deprecated in PHP 5.3 and removed in PHP 5.4. -So if you use these REF typemaps, you should ensure that SWIG≥3.0 is -used to generate wrappers from your interface file. -

    -

    In case you write your own typemaps, SWIG supports an attribute called byref: if you set that, then SWIG will make sure that the generated @@ -583,7 +568,7 @@ PHP in a number of ways: by using unset on an existing variable, or assigning NULL to a variable.

    -

    34.2.6 Structures and C++ classes

    +

    32.2.6 Structures and C++ classes

    @@ -644,7 +629,7 @@ Would be used in the following way from PHP: Member variables and methods are accessed using the -> operator.

    -

    34.2.6.1 Using -noproxy

    +

    32.2.6.1 Using -noproxy

    @@ -670,7 +655,7 @@ Complex_im_set($obj, $d); Complex_im_get($obj); -

    34.2.6.2 Constructors and Destructors

    +

    32.2.6.2 Constructors and Destructors

    @@ -711,7 +696,7 @@ the programmer can either reassign the variable or call unset($v)

    -

    34.2.6.3 Static Member Variables

    +

    32.2.6.3 Static Member Variables

    @@ -754,7 +739,7 @@ Ko::threats(10); echo "There have now been " . Ko::threats() . " threats\n"; -

    34.2.6.4 Static Member Functions

    +

    32.2.6.4 Static Member Functions

    @@ -776,7 +761,7 @@ Ko::threats(); -

    34.2.6.5 Specifying Implemented Interfaces

    +

    32.2.6.5 Specifying Implemented Interfaces

    @@ -794,7 +779,7 @@ so: If there are multiple interfaces, just list them separated by commas.

    -

    34.2.7 PHP Pragmas, Startup and Shutdown code

    +

    32.2.7 PHP Pragmas, Startup and Shutdown code

    @@ -820,6 +805,15 @@ Results in the following in "example.php" echo "example.php execution\n"; +

    +The version pragma can be used to add version to generated PHP extension module. The version is inserted in the zend_module_entry block. +

    + +
    +%module example
    +%pragma(php) version="1.5"
    +
    +

    The include pragma is a short cut to add include statements to the example.php file. @@ -882,7 +876,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.

    -

    34.3 Cross language polymorphism

    +

    32.3 Cross language polymorphism

    @@ -917,7 +911,7 @@ wrapper functions takes care of all the cross-language method routing transparently.

    -

    34.3.1 Enabling directors

    +

    32.3.1 Enabling directors

    @@ -944,7 +938,7 @@ 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 +// generate directors for the virtual methods in class Foo %feature("director") Foo; @@ -962,7 +956,7 @@ directors for specific classes or methods. So for example,

    -will generate directors for all virtual methods of class Foo except +will generate directors for the virtual methods of class Foo except bar().

    @@ -977,14 +971,14 @@ the methods one() and two() (but not three()): %feature("director") Foo; class Foo { public: - Foo(int foo); - virtual void one(); - virtual void two(); + Foo(int foo); + virtual void one(); + virtual void two(); }; class Bar: public Foo { public: - virtual void three(); + virtual void three(); }; @@ -1006,7 +1000,7 @@ class MyFoo extends Foo { -

    34.3.2 Director classes

    +

    32.3.2 Director classes

    @@ -1027,7 +1021,8 @@ 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 +Virtual methods that have a final specifier are unsurprisingly excluded. +Thus the virtual method calls, whether they originate in C++ or in PHP 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 @@ -1086,7 +1081,7 @@ so there is no need for the extra overhead involved with routing the calls through PHP.

    -

    34.3.3 Ownership and object destruction

    +

    32.3.3 Ownership and object destruction

    @@ -1116,12 +1111,12 @@ Here is an example:

     class Foo {
     public:
    -    ...
    +  ...
     };
     class FooContainer {
     public:
    -    void addFoo(Foo *);
    -    ...
    +  void addFoo(Foo *);
    +  ...
     };
     
    @@ -1142,7 +1137,7 @@ In this example, we are assuming that FooContainer will take care of deleting all the Foo pointers it contains at some point.

    -

    34.3.4 Exception unrolling

    +

    32.3.4 Exception unrolling

    @@ -1166,9 +1161,9 @@ should suffice in most cases:

     %feature("director:except") {
    -    if ($error == FAILURE) {
    -        throw Swig::DirectorMethodException();
    -    }
    +  if ($error == FAILURE) {
    +    throw Swig::DirectorMethodException();
    +  }
     }
     
    @@ -1195,8 +1190,8 @@ suitable exception handler:
     %exception {
    -    try { $action }
    -    catch (Swig::DirectorException &e) { SWIG_fail; }
    +  try { $action }
    +  catch (Swig::DirectorException &e) { SWIG_fail; }
     }
     
    @@ -1209,7 +1204,7 @@ Swig::DirectorMethodException is thrown, PHP will register the exception as soon as the C wrapper function returns.

    -

    34.3.5 Overhead and code bloat

    +

    32.3.5 Overhead and code bloat

    @@ -1242,7 +1237,7 @@ optimized by selectively enabling director methods (using the %feature directive) for only those methods that are likely to be extended in PHP.

    -

    34.3.6 Typemaps

    +

    32.3.6 Typemaps

    @@ -1256,7 +1251,7 @@ need to be supported.

    -

    34.3.7 Miscellaneous

    +

    32.3.7 Miscellaneous

    Director typemaps for STL classes are mostly in place, and hence you diff --git a/Doc/Manual/Pike.html b/Doc/Manual/Pike.html index 22ab4e2a2..2b8432399 100644 --- a/Doc/Manual/Pike.html +++ b/Doc/Manual/Pike.html @@ -7,7 +7,7 @@ -

    35 SWIG and Pike

    +

    37 SWIG and Pike

    -

    35.2 Basic C/C++ Mapping

    +

    37.2 Basic C/C++ Mapping

    -

    35.2.1 Modules

    +

    37.2.1 Modules

    @@ -144,7 +144,7 @@ concerned), SWIG's %module directive doesn't really have any significance.

    -

    35.2.2 Functions

    +

    37.2.2 Functions

    @@ -169,7 +169,7 @@ exactly as you'd expect it to: (1) Result: 24 -

    35.2.3 Global variables

    +

    37.2.3 Global variables

    @@ -198,7 +198,7 @@ will result in two functions, Foo_get() and Foo_set(): (3) Result: 3.141590 -

    35.2.4 Constants and enumerated types

    +

    37.2.4 Constants and enumerated types

    @@ -206,7 +206,7 @@ Enumerated types in C/C++ declarations are wrapped as Pike constants, not as Pike enums.

    -

    35.2.5 Constructors and Destructors

    +

    37.2.5 Constructors and Destructors

    @@ -214,7 +214,7 @@ Constructors are wrapped as create() methods, and destructors are wrapped as destroy() methods, for Pike classes.

    -

    35.2.6 Static Members

    +

    37.2.6 Static Members

    @@ -230,8 +230,8 @@ For example, given this C++ class declaration: class Shape { public: - static void print(); - static int nshapes; + static void print(); + static int nshapes; }; diff --git a/Doc/Manual/Preface.html b/Doc/Manual/Preface.html index 3b654a6d2..36a99bd1f 100644 --- a/Doc/Manual/Preface.html +++ b/Doc/Manual/Preface.html @@ -69,6 +69,9 @@ over a period of 10 years starting from the year 2000. The final version in the 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. +Version 3.0.0 was released in 2014 focusing on adding C++11 support and C++ nested classes. +Version 4.0.0 was released in 2019 to add in Doxygen support. +Some target languages were disabled as part of a clean up and others were given a new status of either 'Supported' or 'Experimental'.

    1.3 SWIG License

    @@ -364,7 +367,7 @@ a number of packages to be installed. Full instructions at

    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 +inconsistency with how shared libraries are handled by various scripting languages on OS X.

    @@ -435,7 +438,7 @@ don't intend to use these features in your own programs.

    -Note: The test-suite currently contains over 500 tests. If you +Note: The test-suite currently contains over 600 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.

    diff --git a/Doc/Manual/Preprocessor.html b/Doc/Manual/Preprocessor.html index efa0c0f8e..51cc06378 100644 --- a/Doc/Manual/Preprocessor.html +++ b/Doc/Manual/Preprocessor.html @@ -7,7 +7,7 @@ -

    8 Preprocessing

    +

    11 Preprocessing

      @@ -38,7 +38,7 @@ However, a number of modifications and enhancements have been made. This chapter describes some of these modifications.

      -

      8.1 File inclusion

      +

      11.1 File inclusion

      @@ -64,7 +64,7 @@ By default, the #include is ignored unless you run SWIG with the is that you often don't want SWIG to try and wrap everything included in standard header system headers and auxiliary files. -

      8.2 File imports

      +

      11.2 File imports

      @@ -93,7 +93,7 @@ The -importall directive tells SWIG to follow all #include sta as imports. This might be useful if you want to extract type definitions from system header files without generating any wrappers. -

      8.3 Conditional Compilation

      +

      11.3 Conditional Compilation

      @@ -109,31 +109,25 @@ SWIGIMPORTED Defined when SWIG is importing a file with % SWIG_VERSION Hexadecimal (binary-coded decimal) number containing SWIG version, such as 0x010311 (corresponding to SWIG-1.3.11). -SWIGALLEGROCL Defined when using Allegro CL -SWIGCFFI Defined when using CFFI -SWIGCHICKEN Defined when using CHICKEN -SWIGCLISP Defined when using CLISP SWIGCSHARP Defined when using C# +SWIGD Defined when using D +SWIGGO Defined when using Go SWIGGUILE Defined when using Guile SWIGJAVA Defined when using Java SWIGJAVASCRIPT Defined when using Javascript -SWIG_JAVASCRIPT_JSC Defined when using Javascript for JavascriptCore -SWIG_JAVASCRIPT_V8 Defined when using Javascript for v8 or node.js +SWIG_JAVASCRIPT_JSC Defined when using Javascript with -jsc +SWIG_JAVASCRIPT_V8 Defined when using Javascript with -v8 or -node SWIGLUA Defined when using Lua -SWIGMODULA3 Defined when using Modula-3 SWIGMZSCHEME Defined when using Mzscheme -SWIGOCAML Defined when using Ocaml +SWIGOCAML Defined when using OCaml SWIGOCTAVE Defined when using Octave SWIGPERL Defined when using Perl -SWIGPHP Defined when using PHP5 or PHP7 -SWIGPHP5 Defined when using PHP5 +SWIGPHP Defined when using PHP (any version) SWIGPHP7 Defined when using PHP7 -SWIGPIKE Defined when using Pike SWIGPYTHON Defined when using Python SWIGR Defined when using R SWIGRUBY Defined when using Ruby SWIGSCILAB Defined when using Scilab -SWIGSEXP Defined when using S-expressions SWIGTCL Defined when using Tcl SWIGXML Defined when using XML

    @@ -146,20 +140,32 @@ In addition, SWIG defines the following set of standard C/C++ macros:
     __LINE__                        Current line number
     __FILE__                        Current file name
    -__STDC__                        Defined to indicate ANSI C
    +__STDC__                        Defined to indicate ISO C
     __cplusplus                     Defined when -c++ option used
     

    -Interface files can look at these symbols as necessary to change the -way in which an interface is generated or to mix SWIG directives with -C code. These symbols are also defined within the C code generated by -SWIG (except for the symbol `SWIG' which is only defined -within the SWIG compiler). +The following are language specific symbols that might be defined:

    -

    8.4 Macro Expansion

    +
    +SWIG_D_VERSION                  Unsigned integer target version when using D
    +SWIGGO_CGO                      Defined when using Go for cgo
    +SWIGGO_GCCGO                    Defined when using Go for gccgo
    +SWIGGO_INTGO_SIZE               Size of the Go type int when using Go (32 or 64)
    +SWIGPYTHON_PY3                  Defined when using Python with -py3
    +SWIGPYTHON_BUILTIN              Defined when using Python with -builtin
    +SWIG_RUBY_AUTORENAME            Defined when using Ruby with -autorename
    +
    + +

    +Interface files can look at these symbols as necessary to change the +way in which an interface is generated or to mix SWIG directives with +C code. +

    + +

    11.4 Macro Expansion

    @@ -188,9 +194,9 @@ More complex macros can be defined in the standard way. For example:

     #define EXTERN extern
     #ifdef __STDC__
    -#define _ANSI(args)   (args)
    +#define ISOC_(args)   (args)
     #else
    -#define _ANSI(args) ()
    +#define ISOC_(args) ()
     #endif
     
    @@ -214,7 +220,7 @@ like #x. This is a non-standard SWIG extension.
  • -

    8.5 SWIG Macros

    +

    11.5 SWIG Macros

    @@ -260,7 +266,7 @@ many of SWIG's advanced features and libraries are built using this mechanism (s support).

    -

    8.6 C99 and GNU Extensions

    +

    11.6 C99 and GNU Extensions

    @@ -316,14 +322,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.

    -

    8.7 Preprocessing and delimiters

    +

    11.7 Preprocessing and delimiters

    The preprocessor handles { }, " " and %{ %} delimiters differently.

    -

    8.7.1 Preprocessing and %{ ... %} & " ... " delimiters

    +

    11.7.1 Preprocessing and %{ ... %} & " ... " delimiters

    @@ -348,7 +354,7 @@ the contents of the %{ ... %} block are copied without modification to the output (including all preprocessor directives).

    -

    8.7.2 Preprocessing and { ... } delimiters

    +

    11.7.2 Preprocessing and { ... } delimiters

    @@ -390,7 +396,7 @@ to actually go into the wrapper file, prefix the preprocessor directives with % and leave the preprocessor directive in the code.

    -

    8.8 Preprocessor and Typemaps

    +

    11.8 Preprocessor and Typemaps

    @@ -461,17 +467,17 @@ would generate -

    8.9 Viewing preprocessor output

    +

    11.9 Viewing preprocessor output

    Like many compilers, SWIG supports a -E command line option to display the output from the preprocessor. -When the -E switch is used, SWIG will not generate any wrappers. +When the -E option is used, SWIG will not generate any wrappers. Instead the results after the preprocessor has run are displayed. This might be useful as an aid to debugging and viewing the results of macro expansions.

    -

    8.10 The #error and #warning directives

    +

    11.10 The #error and #warning directives

    diff --git a/Doc/Manual/Python.html b/Doc/Manual/Python.html index a5b2100ce..c132afc8a 100644 --- a/Doc/Manual/Python.html +++ b/Doc/Manual/Python.html @@ -7,7 +7,7 @@ -

    36 SWIG and Python

    +

    33 SWIG and Python

    @@ -145,9 +156,9 @@

    This chapter describes SWIG's support of Python. SWIG is compatible -with most recent Python versions including Python 3.0 and Python 2.6, -as well as older versions dating back to Python 2.0. For the best results, -consider using Python 2.3 or newer. +with all recent Python versions (Python 2.7 and Python >= 3.2). If you +still need to generate bindings which work with older versions of Python, +you'll have to use SWIG 3.0.x.

    @@ -157,12 +168,12 @@ very least, make sure you read the "SWIG Basics" chapter.

    -

    36.1 Overview

    +

    33.1 Overview

    To build Python extension modules, SWIG uses a layered approach in which -parts of the extension module are defined in C and other parts are +parts of the extension module are defined in C and other parts are defined in Python. The C layer contains low-level wrappers whereas Python code is used to define high-level features.

    @@ -184,10 +195,10 @@ described followed by a discussion of low-level implementation details.

    -

    36.2 Preliminaries

    +

    33.2 Preliminaries

    -

    36.2.1 Running SWIG

    +

    33.2.1 Running SWIG

    @@ -210,7 +221,7 @@ int fact(int n);

    The #define SWIG_FILE_WITH_INIT line inserts a macro that specifies that the -resulting C file should be built as a python extension, inserting the module +resulting C file should be built as a Python extension, inserting the module init code. This .i file wraps the following simple C file:

    @@ -221,16 +232,15 @@ resulting C file should be built as a python extension, inserting the module #include "example.h" int fact(int n) { - if (n < 0){ /* This should probably return an error, but this is simpler */ - return 0; - } - if (n == 0) { - return 1; - } - else { - /* testing for overflow would be a good idea here */ - return n * fact(n-1); - } + if (n < 0) { /* This should probably return an error, but this is simpler */ + return 0; + } + if (n == 0) { + return 1; + } else { + /* testing for overflow would be a good idea here */ + return n * fact(n-1); + } } @@ -285,13 +295,13 @@ The following sections have further practical examples and details on how you might go about compiling and using the generated files.

    -

    36.2.2 Using distutils

    +

    33.2.2 Using distutils

    -The preferred approach to building an extension module for python is to compile it with -distutils, which comes with all recent versions of python -(Distutils Docs). +The preferred approach to building an extension module for Python is to compile it with +distutils, which comes with all recent versions of Python +(Distutils Docs).

    @@ -300,7 +310,7 @@ flags, headers, etc. for the version of Python it is run with. Distutils will co extension into a shared object file or DLL (.so on Linux, .pyd on Windows, etc). In addition, distutils can handle installing your package into site-packages, if that is desired. A configuration file (conventionally called: setup.py) -describes the extension (and related python modules). The distutils will +describes the extension (and related Python modules). The distutils will then generate all the right compiler directives to build it for you.

    @@ -337,9 +347,9 @@ setup (name = 'example', In this example, the line: example_module = Extension(....) creates an Extension module object, defining the name as _example, and using the source code files: example_wrap.c, generated by swig, and example.c, your original c -source. The swig (and other python extension modules) tradition is for the compiled -extension to have the name of the python portion, prefixed by an underscore. If the name -of your python module is "example.py", then the name of the corresponding object file +source. The swig (and other Python extension modules) tradition is for the compiled +extension to have the name of the Python portion, prefixed by an underscore. If the name +of your Python module is "example.py", then the name of the corresponding object file will be"_example.so"

    @@ -356,11 +366,11 @@ $ python setup.py build_ext --inplace

    And a .so, or .pyd or... will be created for you. It will build a version that matches the -python that you run the command with. Taking apart the command line: +Python that you run the command with. Taking apart the command line:

      -
    • python -- the version of python you want to build for +
    • python -- the version of Python you want to build for
    • setup.py -- the name of your setup script (it can be called anything, but setup.py is the tradition)
    • build_ext -- telling distutils to build extensions @@ -369,7 +379,7 @@ python that you run the command with. Taking apart the command line:

    -The distutils have many other features, consult the python distutils docs for details. +The distutils have many other features, consult the Python distutils docs for details.

    @@ -377,7 +387,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)

    -

    36.2.3 Hand compiling a dynamic module

    +

    33.2.3 Hand compiling a dynamic module

    @@ -395,9 +405,9 @@ $ gcc -shared example.o example_wrap.o -o _example.so

    -The exact commands for doing this vary from platform to platform. -However, SWIG tries to guess the right options when it is installed. Therefore, -you may want to start with one of the examples in the SWIG/Examples/python +The exact commands for doing this vary from platform to platform. +However, SWIG tries to guess the right options when it is installed. Therefore, +you may want to start with one of the examples in the SWIG/Examples/python directory. If that doesn't work, you will need to read the man-pages for your compiler and linker to get the right set of options. You might also check the SWIG Wiki for @@ -409,7 +419,7 @@ When linking the module, the name of the output file has to match the name of the module prefixed by an underscore. If the name of your module is "example", then the name of the corresponding object file should be "_example.so" or "_examplemodule.so". -The name of the module is specified using the %module directive or the +The name of the module is specified using the %module directive or the -module command line option.

    @@ -425,7 +435,7 @@ module actually consists of two files; socket.py and

    -

    36.2.4 Static linking

    +

    33.2.4 Static linking

    @@ -433,7 +443,7 @@ An alternative approach to dynamic linking is to rebuild the Python interpreter with your extension module added to it. In the past, this approach was sometimes necessary due to limitations in dynamic loading support on certain machines. However, the situation has improved greatly -over the last few years and you should not consider this approach +over the last few years and you should not consider this approach unless there is really no other option.

    @@ -493,7 +503,7 @@ linking if possible. Some programmers may be inclined to use static linking in the interest of getting better performance. However, the performance gained by static linking tends to be rather minimal in most situations (and quite frankly not worth the extra -hassle in the opinion of this author). +hassle in the opinion of this author).

    @@ -504,7 +514,7 @@ If using static linking, you might want to rely on a different approach (perhaps using distutils).

    -

    36.2.5 Using your module

    +

    33.2.5 Using your module

    @@ -552,13 +562,13 @@ Another possible error is the following: Traceback (most recent call last): File "<stdin>", line 1, in ? ImportError: dynamic module does not define init function (init_example) ->>> +>>>

    -This error is almost always caused when a bad name is given to the shared object file. -For example, if you created a file example.so instead of _example.so you would +This error is almost always caused when a bad name is given to the shared object file. +For example, if you created a file example.so instead of _example.so you would get this error. Alternatively, this error could arise if the name of the module is inconsistent with the module name supplied with the %module directive. Double-check the interface to make sure the module name and the shared object @@ -584,7 +594,7 @@ This error usually indicates that you forgot to include some object files or libraries in the linking of the shared library file. Make sure you compile both the SWIG wrapper file and your original program into a shared library file. Make sure you pass all of the required libraries -to the linker. +to the linker.

    @@ -619,7 +629,7 @@ problem when you try to use your module: Traceback (most recent call last): File "<stdin>", line 1, in ? ImportError: libfoo.so: cannot open shared object file: No such file or directory ->>> +>>> @@ -642,7 +652,7 @@ $ gcc -shared example.o example_wrap.o -L/home/beazley/projects/lib -lfoo \

    Alternatively, you can set the LD_LIBRARY_PATH environment variable to -include the directory with your shared libraries. +include the directory with your shared libraries. If setting LD_LIBRARY_PATH, be aware that setting this variable can introduce a noticeable performance impact on all other applications that you run. To set it only for Python, you might want to do this instead: @@ -661,7 +671,7 @@ system configuration (this requires root access and you will need to read the man pages).

    -

    36.2.6 Compilation of C++ extensions

    +

    33.2.6 Compilation of C++ extensions

    @@ -707,7 +717,7 @@ $ CC -G example.o example_wrap.o -L/opt/SUNWspro/lib -o _example.so -lCrun

    -Of course, the extra libraries to use are completely non-portable---you will +Of course, the extra libraries to use are completely non-portable---you will probably need to do some experimentation.

    @@ -715,8 +725,8 @@ probably need to do some experimentation. Sometimes people have suggested that it is necessary to relink the Python interpreter using the C++ compiler to make C++ extension modules work. In the experience of this author, this has never actually appeared to be -necessary. Relinking the interpreter with C++ really only includes the -special run-time libraries described above---as long as you link your extension +necessary. Relinking the interpreter with C++ really only includes the +special run-time libraries described above---as long as you link your extension modules with these libraries, it should not be necessary to rebuild Python.

    @@ -753,14 +763,14 @@ erratic program behavior. If working with lots of software components, you might want to investigate using a more formal standard such as COM.

    -

    36.2.7 Compiling for 64-bit platforms

    +

    33.2.7 Compiling for 64-bit platforms

    On platforms that support 64-bit applications (Solaris, Irix, etc.), special care is required when building extension modules. On these machines, 64-bit applications are compiled and linked using a different -set of compiler/linker options. In addition, it is not generally possible to mix +set of compiler/linker options. In addition, it is not generally possible to mix 32-bit and 64-bit code together in the same application.

    @@ -786,11 +796,11 @@ careful about the libraries you link with or the library path you use. In general, a Linux distribution will have two set of libraries, one for native x86_64 programs (under /usr/lib64), and another for 32 bits compatibility (under /usr/lib). Also, the compiler options -m32 -and -m64 allow you to choose the desired binary format for your python +and -m64 allow you to choose the desired binary format for your Python extension.

    -

    36.2.8 Building Python Extensions under Windows

    +

    33.2.8 Building Python extensions under Windows

    @@ -802,6 +812,7 @@ are built with Visual Studio 2003), the standard python setup.py build should just work.

    +

    As of python2.5, the distutils support building extensions with MingGW out of the box. Following the instruction here: @@ -814,10 +825,10 @@ 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. +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 (.dsp files) for Visual C++ 6. These can be opened by more +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. @@ -852,12 +863,12 @@ settings, select the "Custom Build" option. "C++:Preprocessor". Add the include directories for your Python installation under "Additional include directories". -

  • Define the symbol __WIN32__ under preprocessor options. +
  • Define the symbol __WIN32__ under preprocessor options.
  • Finally, select the settings for the entire project and go to "Link Options". Add the Python library file to your link libraries. -For example "python21.lib". Also, set the name of the output file to -match the name of your Python module, ie. _example.pyd - Note that _example.dll also worked with Python-2.4 and earlier. +For example "python27.lib". Also, set the name of the output file to +match the name of your Python module, i.e. _example.pyd
  • Build your project. @@ -866,7 +877,7 @@ match the name of your Python module, ie. _example.pyd - Note that _example.dll If all went well, SWIG will be automatically invoked whenever you build your project. Any changes made to the interface file will result in SWIG being automatically executed to produce a new version of -the wrapper file. +the wrapper file.

    @@ -885,9 +896,9 @@ $ python

    If you get an ImportError exception when importing the module, you may have forgotten to include additional library files when you built your module. -If you get an access violation or some kind of general protection fault -immediately upon import, you have a more serious problem. This -is often caused by linking your extension module against the wrong +If you get an access violation or some kind of general protection fault +immediately upon import, you have a more serious problem. This +is often caused by linking your extension module against the wrong 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.

    @@ -919,7 +930,51 @@ SWIG Wiki.

    -

    36.3 A tour of basic C/C++ wrapping

    +

    33.2.9 Additional Python commandline options

    + + +

    +The following table lists the additional commandline options available for the Python module. They can also be seen by using: +

    + +
    +swig -python -help
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Python specific options
    -builtin Create Python built-in types rather than proxy classes, for better performance
    -castmode Enable the casting mode, which allows implicit cast between types in Python
    -debug-doxygen-parser Display doxygen parser module debugging information
    -debug-doxygen-translator Display doxygen translator module debugging information
    -dirvtable Generate a pseudo virtual table for directors for faster dispatch
    -doxygen Convert C++ doxygen comments to pydoc comments in proxy classes
    -extranative Return extra native wrappers for C++ std containers wherever possible
    -fastproxy Use fast proxy mechanism for member methods
    -globals <name> Set <name> used to access C global variable (default: 'cvar')
    -interface <mod>Set low-level C/C++ module name to <mod> (default: module name prefixed by '_')
    -keyword Use keyword arguments
    -nofastunpack Use traditional UnpackTuple method to parse the argument functions
    -noh Don't generate the output header file
    -noproxy Don't generate proxy classes
    -nortti Disable the use of the native C++ RTTI with directors
    -nothreads Disable thread support for the entire interface
    -olddefs Keep the old method definitions when using -fastproxy
    -py3 Generate code with Python 3 specific features and syntax
    -relativeimport Use relative Python imports
    -threads Add thread support for all the interface
    -O Enable the following optimization options: -fastdispatch -fastproxy -fvirtual
    + +

    +Many of these options are covered later on and their use should become clearer by the time you have finished reading this section on SWIG and Python. +

    + +

    33.3 A tour of basic C/C++ wrapping

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

    -

    36.3.1 Modules

    +

    33.3.1 Modules

    @@ -938,10 +993,10 @@ wrapped into a Python 'example' module. Underneath the covers, this module consists of a Python source file example.py and a low-level extension module _example.so. When choosing a module name, make sure you don't use the same name as a built-in -Python command or standard module name. +Python command or standard module name.

    -

    36.3.2 Functions

    +

    33.3.2 Functions

    @@ -965,7 +1020,7 @@ like you think it does: >>> -

    36.3.3 Global variables

    +

    33.3.3 Global variables

    @@ -991,8 +1046,8 @@ then "a" and "b" are both names for the object containing the value 3.4. Thus, there is only one object containing 3.4 and "a" and "b" are both names that refer to it. This is quite different than C where a variable name refers to a memory location in which -a value is stored (and assignment copies data into that location). -Because of this, there is no direct way to map variable +a value is stored (and assignment copies data into that location). +Because of this, there is no direct way to map variable assignment in C to variable assignment in Python.

    @@ -1038,7 +1093,7 @@ error message. For example: Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: C variable 'density (double )' ->>> +>>>

    @@ -1103,7 +1158,7 @@ that starts with a leading underscore. SWIG does not create cvar if there are no global variables in a module.

    -

    36.3.4 Constants and enums

    +

    33.3.4 Constants and enums

    @@ -1143,7 +1198,7 @@ other object. Unfortunately, there is no easy way for SWIG to generate code that prevents this. You will just have to be careful.

    -

    36.3.5 Pointers

    +

    33.3.5 Pointers

    @@ -1178,7 +1233,7 @@ When wrapped, you will be able to use the functions in a natural way from Python

    If this makes you uneasy, rest assured that there is no deep magic involved. Underneath the covers, pointers to C/C++ objects are -simply represented as opaque values using an especial python container object: +simply represented as opaque values using an especial Python container object:

    @@ -1188,7 +1243,7 @@ simply represented as opaque values using an especial python container object:
     
     

    This pointer value can be freely passed around to different C functions that -expect to receive an object of type FILE *. The only thing you can't do is +expect to receive an object of type FILE *. The only thing you can't do is dereference the pointer from Python. Of course, that isn't much of a concern in this example.

    @@ -1206,7 +1261,7 @@ _c0671108_p_FILE

    Also, if you need to pass the raw pointer value to some external -python library, you can do it by casting the pointer object to an +Python library, you can do it by casting the pointer object to an integer:

    @@ -1271,7 +1326,7 @@ Foo *BarToFoo(Bar *b) { } Foo *IncrFoo(Foo *f, int i) { - return f+i; + return f+i; } %}
    @@ -1284,7 +1339,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.

    -

    36.3.6 Structures

    +

    33.3.6 Structures

    @@ -1308,8 +1363,8 @@ is used as follows: >>> v.x = 3.5 >>> v.y = 7.2 >>> print v.x, v.y, v.z -7.8 -4.5 0.0 ->>> +3.5 7.2 0.0 +>>>

    @@ -1368,7 +1423,7 @@ struct Foo {

    When char * members of a structure are wrapped, the contents are assumed to be dynamically allocated using malloc or new (depending on whether or not -SWIG is run with the -c++ option). When the structure member is set, the old contents will be +SWIG is run with the -c++ option). When the structure member is set, the old contents will be released and a new value created. If this is not the behavior you want, you will have to use a typemap (described later).

    @@ -1381,7 +1436,7 @@ example, consider this:
     struct Bar {
    -    int  x[16];
    +  int  x[16];
     };
     
    @@ -1395,7 +1450,7 @@ If accessed in Python, you will see behavior like this: >>> b = example.Bar() >>> print b.x _801861a4_p_int ->>> +>>> @@ -1460,7 +1515,7 @@ Foo *x = &b->f; /* Points inside b */

    -Because the pointer points inside the structure, you can modify the contents and +Because the pointer points inside the structure, you can modify the contents and everything works just like you would expect. For example:

    @@ -1468,12 +1523,33 @@ everything works just like you would expect. For example:
     >>> b = Bar()
     >>> b.f.a = 3               # Modify attribute of structure member
    ->>> x = b.f                   
    +>>> x = b.f
     >>> x.a = 3                 # Modifies the same structure
     
    -

    36.3.7 C++ classes

    +

    +Note that there is a limitation with structs within structs that will cause a problem +if the outer struct is not a named variable in Python. The following will cause a segfault: +

    + +
    +
    +Bar().f.a = 3
    +
    +
    + +

    +because the unnamed Python proxy class for Bar() has its reference count +decremented by the Python interpreter after f has been obtained from it and +before f is used to obtain a. +This results in the underlying Bar instance being deleted, which of course also deletes +f inside it. Hence the pointer to f points to deleted +memory and use of it results in a segfault or some sort of other undefined behaviour. +

    + + +

    33.3.7 C++ classes

    @@ -1510,13 +1586,13 @@ you can use it in Python like this:

    -Class data members are accessed in the same manner as C structures. +Class data members are accessed in the same manner as C structures.

    -Static class members present a special problem for Python. Prior to Python-2.2, +Static class members present a special problem for Python. Prior to Python-2.2, Python classes had no support for static methods and no version of Python -supports static member variables in a manner that SWIG can utilize. Therefore, +supports static member variables in a manner that SWIG can utilize. Therefore, SWIG generates wrappers that try to work around some of these issues. To illustrate, suppose you have a class like this:

    @@ -1561,7 +1637,7 @@ they are accessed through cvar like this: -

    36.3.8 C++ inheritance

    +

    33.3.8 C++ inheritance

    @@ -1616,7 +1692,7 @@ then the function spam() accepts Foo * or a pointer to any cla It is safe to use multiple inheritance with SWIG.

    -

    36.3.9 Pointers, references, values, and arrays

    +

    33.3.9 Pointers, references, values, and arrays

    @@ -1669,15 +1745,15 @@ const Foo &spam9();

    then all three functions will return a pointer to some Foo object. -Since the third function (spam8) returns a value, newly allocated memory is used -to hold the result and a pointer is returned (Python will release this memory +Since the third function (spam8) returns a value, newly allocated memory is used +to hold the result and a pointer is returned (Python will release this memory when the return value is garbage collected). The fourth case (spam9) -which returns a const reference, in most of the cases will be +which returns a const reference, in most of the cases will be treated as a returning value, and it will follow the same allocation/deallocation process.

    -

    36.3.10 C++ overloaded functions

    +

    33.3.10 C++ overloaded functions

    @@ -1711,9 +1787,9 @@ Similarly, if you have a class like this,

     class Foo {
     public:
    -    Foo();
    -    Foo(const Foo &);
    -    ...
    +  Foo();
    +  Foo(const Foo &);
    +  ...
     };
     
    @@ -1771,7 +1847,7 @@ To fix this, you either need to ignore or rename one of the methods. For exampl
     %rename(spam_short) spam(short);
     ...
    -void spam(int);    
    +void spam(int);
     void spam(short);   // Accessed as spam_short
     
    @@ -1784,7 +1860,7 @@ or
     %ignore spam(short);
     ...
    -void spam(int);    
    +void spam(int);
     void spam(short);   // Ignored
     
    @@ -1797,10 +1873,10 @@ first declaration takes precedence.

    -Please refer to the "SWIG and C++" chapter for more information about overloading. +Please refer to the "SWIG and C++" chapter for more information about overloading.

    -

    36.3.11 C++ operators

    +

    33.3.11 C++ operators

    @@ -1823,7 +1899,7 @@ public: Complex operator-(const Complex &c) const; Complex operator*(const Complex &c) const; Complex operator-() const; - + double re() const { return rpart; } double im() const { return ipart; } }; @@ -1889,7 +1965,15 @@ 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.

    -

    36.3.12 C++ namespaces

    +

    +Operator overloading is implemented in the pyopers.swg library file. +In particular overloaded operators are marked with the python:maybecall feature, also known as %pythonmaybecall. +This feature forces SWIG to generate code that return an instance of Python's NotImplemented +instead of raising an exception when the comparison fails, that is, on any kind of error. +This follows the guidelines in PEP 207 - Rich Comparisons and NotImplemented Python constant. +

    + +

    33.3.12 C++ namespaces

    @@ -1938,11 +2022,11 @@ For example: %rename(Bar_spam) Bar::spam; namespace Foo { - int spam(); + int spam(); } namespace Bar { - int spam(); + int spam(); } @@ -1956,7 +2040,7 @@ utilizes thousands of small deeply nested namespaces each with identical symbol names, well, then you get what you deserve.

    -

    36.3.13 C++ templates

    +

    33.3.13 C++ templates

    @@ -2005,15 +2089,15 @@ In Python:

    Obviously, there is more to template wrapping than shown in this example. -More details can be found in the SWIG and C++ chapter. +More details can be found in the SWIG and C++ chapter. Some more complicated examples will appear later.

    -

    36.3.14 C++ Smart Pointers

    +

    33.3.14 C++ Smart Pointers

    -

    36.3.14.1 The shared_ptr Smart Pointer

    +

    33.3.14.1 The shared_ptr Smart Pointer

    @@ -2024,7 +2108,7 @@ in the shared_ptr smart pointer -

    36.3.14.2 Generic Smart Pointers

    +

    33.3.14.2 Generic Smart Pointers

    @@ -2108,7 +2192,7 @@ simply use the __deref__() method. For example: -

    36.3.15 C++ reference counted objects

    +

    33.3.15 C++ reference counted objects

    @@ -2117,7 +2201,7 @@ Python examples of memory management using referencing counting.

    -

    36.4 Further details on the Python class interface

    +

    33.4 Further details on the Python class interface

    @@ -2140,7 +2224,7 @@ the -builtin option are in the Built-in section.

    -

    36.4.1 Proxy classes

    +

    33.4.1 Proxy classes

    @@ -2153,9 +2237,9 @@ have a class like this

     class Foo {
     public:
    -    int x;
    -    int spam(int);
    -    ...
    +  int x;
    +  int spam(int);
    +  ...
     
    @@ -2166,19 +2250,19 @@ then SWIG transforms it into a set of low-level procedural wrappers. For example
     Foo *new_Foo() {
    -    return new Foo();
    +  return new Foo();
     }
     void delete_Foo(Foo *f) {
    -    delete f;
    +  delete f;
     }
     int Foo_x_get(Foo *f) {
    -    return f->x;
    +  return f->x;
     }
     void Foo_x_set(Foo *f, int value) {
    -    f->x = value;
    +  f->x = value;
     }
     int Foo_spam(Foo *f, int arg1) {
    -    return f->spam(arg1);
    +  return f->spam(arg1);
     }
     
    @@ -2188,7 +2272,7 @@ These wrappers can be found in the low-level extension module (e.g., _exampl

    -Using these wrappers, SWIG generates a high-level Python proxy class (also known as a shadow class) like this (shown +Using these wrappers, SWIG generates a high-level Python proxy class (also known as a shadow class) like this (shown for Python 2.2):

    @@ -2210,7 +2294,7 @@ class Foo(object):

    -This class merely holds a pointer to the underlying C++ object (.this) and dispatches methods and +This class merely holds a pointer to the underlying C++ object (.this) and dispatches methods and member variable access to that object using the low-level accessor functions. From a user's point of view, it makes the class work normally:

    @@ -2229,7 +2313,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).

    -

    36.4.2 Built-in Types

    +

    33.4.2 Built-in Types

    @@ -2239,8 +2323,8 @@ and built-in types, let's take a look at what a wrapped object looks like under both circumstances.

    -

    When proxy classes are used, each wrapped object in python is an instance -of a pure python class. As a reminder, here is what the __init__ method looks +

    When proxy classes are used, each wrapped object in Python is an instance +of a pure Python class. As a reminder, here is what the __init__ method looks like in a proxy class:

    @@ -2254,37 +2338,30 @@ class Foo(object):

    When a Foo instance is created, the call to _example.new_Foo() -creates a new C++ Foo instance; wraps that C++ instance inside an instance of -a python built-in type called SwigPyObject; and stores the SwigPyObject -instance in the 'this' field of the python Foo object. Did you get all that? So, the -python Foo object is composed of three parts:

    +creates a new C++ Foo instance; wraps that C++ instance inside an instance of +a Python built-in type called SwigPyObject; and stores the SwigPyObject +instance in the 'this' field of the Python Foo object. Did you get all that? So, the +Python Foo object is composed of three parts:

      -
    • The python Foo instance, which contains...
    • +
    • The Python Foo instance, which contains...
    • ... an instance of struct SwigPyObject, which contains...
    • ... a C++ Foo instance
    -

    When -builtin is used, the pure python layer is stripped off. Each -wrapped class is turned into a new python built-in type which inherits from +

    When -builtin is used, the pure Python layer is stripped off. Each +wrapped class is turned into a new Python built-in type which inherits from SwigPyObject, and SwigPyObject instances are returned directly -from the wrapped methods. For more information about python built-in extensions, -please refer to the python documentation:

    +from the wrapped methods. For more information about Python built-in extensions, +please refer to the Python documentation:

    -

    http://docs.python.org/extending/newtypes.html

    +

    https://docs.python.org/3/extending/newtypes.html

    -

    36.4.2.1 Limitations

    +

    33.4.2.1 Limitations

    Use of the -builtin option implies a couple of limitations:

      -
    • python version support:

      -
        -
      • Versions 2.5 and up are fully supported
      • -
      • Versions 2.3 and 2.4 are mostly supported; there are problems with director classes and/or sub-classing a wrapped type in python.
      • -
      • Versions older than 2.3 are not supported.
      • -
      -
    • Some legacy syntax is no longer supported; in particular:

      • The functional interface is no longer exposed. For example, you may no longer call Whizzo.new_CrunchyFrog(). Instead, you must use Whizzo.CrunchyFrog().
      • @@ -2292,15 +2369,15 @@ please refer to the python documentation:

        They are instead accessed in the idiomatic way (Dances.FishSlap).
    • -
    • Wrapped types may not be raised as python exceptions. Here's why: the python internals expect that all sub-classes of Exception will have this struct layout:

      +
    • Wrapped types may not be raised as Python exceptions. Here's why: the Python internals expect that all sub-classes of Exception will have this struct layout:

       typedef struct {
      -    PyObject_HEAD
      -    PyObject *dict;
      -    PyObject *args;
      -    PyObject *message;
      +  PyObject_HEAD
      +  PyObject *dict;
      +  PyObject *args;
      +  PyObject *message;
       } PyBaseExceptionObject;
       
      @@ -2310,12 +2387,12 @@ typedef struct {
       typedef struct {
      -    PyObject_HEAD
      -    void *ptr;
      -    swig_type_info *ty;
      -    int own;
      -    PyObject *next;
      -    PyObject *dict;
      +  PyObject_HEAD
      +  void *ptr;
      +  swig_type_info *ty;
      +  int own;
      +  PyObject *next;
      +  PyObject *dict;
       } SwigPyObject;
       
      @@ -2326,18 +2403,18 @@ typedef struct {
       class MyException {
       public:
      -    MyException (const char *msg_);
      -    ~MyException ();
      +  MyException (const char *msg_);
      +  ~MyException ();
       
      -    const char *what () const;
      +  const char *what () const;
       
       private:
      -    char *msg;
      +  char *msg;
       };
       
      -

      ... you can define this python class, which may be raised as an exception:

      +

      ... you can define this Python class, which may be raised as an exception:

      @@ -2352,22 +2429,22 @@ class MyPyException(Exception):
       
    • Reverse binary operators (e.g., __radd__) are not supported.

      To illustrate this point, if you have a wrapped class called MyString, -and you want to use instances of MyString interchangeably with native python +and you want to use instances of MyString interchangeably with native Python strings, you can define an 'operator+ (const char*)' method :

       class MyString {
       public:
      -    MyString (const char *init);
      -    MyString operator+ (const char *other) const;
      -    ...
      +  MyString (const char *init);
      +  MyString operator+ (const char *other) const;
      +  ...
       };
       

      -SWIG will automatically create an operator overload in python that will allow this: +SWIG will automatically create an operator overload in Python that will allow this:

      @@ -2394,7 +2471,7 @@ episode = "Dead " + mystr

      -The above code fails, because the first operand -- a native python string -- +The above code fails, because the first operand -- a native Python string -- doesn't know how to add an instance of MyString to itself.

    • @@ -2430,7 +2507,7 @@ class Derived : public Base {

      The import "A.i" statement is required, because module B depends on module A.

      -

      As long as you obey these requirements, your python code may import the modules in any order :

      +

      As long as you obey these requirements, your Python code may import the modules in any order :

       import B
      @@ -2441,35 +2518,36 @@ assert(issubclass(B.Derived, A.Base))
       
       
    -

    36.4.2.2 Operator overloads and slots -- use them!

    +

    33.4.2.2 Operator overloads and slots -- use them!

    The entire justification for the -builtin option is improved performance. To that end, the best way to squeeze maximum performance out of your wrappers is to use operator overloads. -Named method dispatch is slow in python, even when compared to other scripting languages. -However, python built-in types have a large number of "slots", +Named method dispatch is slow in Python, even when compared to other scripting languages. +However, Python built-in types have a large number of "slots", analogous to C++ operator overloads, which allow you to short-circuit named method dispatch for certain common operations.

    -

    By default, SWIG will translate most C++ arithmetic operator overloads into python +

    By default, SWIG will translate most C++ arithmetic operator overloads into Python slot entries. For example, suppose you have this class:

     class Twit {
     public:
    -    Twit operator+ (const Twit& twit) const;
    +  Twit operator+ (const Twit& twit) const;
     
    -    // Forward to operator+
    -    Twit add (const Twit& twit) const
    -    { return *this + twit; }
    +  // Forward to operator+
    +  Twit add (const Twit& twit) const {
    +    return *this + twit;
    +  }
     };
     
    -

    SWIG will automatically register operator+ as a python slot operator for addition. You may write python code like this:

    +

    SWIG will automatically register operator+ as a Python slot operator for addition. You may write Python code like this:

    @@ -2482,24 +2560,24 @@ percival = nigel.add(emily)
     
    -

    The last two lines of the python code are equivalent, +

    The last two lines of the Python code are equivalent, but the line that uses the '+' operator is much faster.

    In-place operators (e.g., operator+=) and comparison operators -(operator==, operator<, etc.) are also converted to python +(operator==, operator<, etc.) are also converted to Python slot operators. For a complete list of C++ operators that are -automatically converted to python slot operators, refer to the file -python/pyopers.swig in the SWIG library. +automatically converted to Python slot operators, refer to the file +python/pyopers.swg in the SWIG library.

    -Read about all of the available python slots here: -http://docs.python.org/c-api/typeobj.html

    +Read about all of the available Python slots here: +https://docs.python.org/3/c-api/typeobj.html

    -There are two ways to define a python slot function: dispatch to a +There are two ways to define a Python slot function: dispatch to a statically defined function; or dispatch to a method defined on the operand.

    @@ -2545,16 +2623,16 @@ public:

    -If you examine the generated code, the supplied hash function will now be +If you examine the generated code, the supplied hash function will now be the function callback in the tp_hash slot for the builtin type for MyClass:

     static PyHeapTypeObject SwigPyBuiltin__MyClass_type = {
    -    ...
    -    (hashfunc) myHashFunc,       /* tp_hash */
    -    ...
    +  ...
    +  (hashfunc) myHashFunc,       /* tp_hash */
    +  ...
     
    @@ -2586,7 +2664,7 @@ class MyClass {

    -NOTE: Some python slots use a method signature which does not +NOTE: Some Python slots use a method signature which does not match the signature of SWIG-wrapped methods. For those slots, SWIG will automatically generate a "closure" function to re-marshal the arguments before dispatching to the wrapped method. Setting @@ -2596,11 +2674,11 @@ the chosen closure function.

    There is further information on %feature("python:slot") -in the file python/pyopers.swig in the SWIG library. +in the file python/pyopers.swg in the SWIG library.

    -

    36.4.3 Memory management

    +

    33.4.3 Memory management

    NOTE: Although this section refers to proxy objects, everything here also applies @@ -2609,7 +2687,7 @@ when the -builtin option is used.

    Associated with proxy object, is an ownership flag .thisown The value of this flag determines who is responsible for deleting the underlying C++ object. If set to 1, -the Python interpreter will destroy the C++ object when the proxy class is +the Python interpreter will destroy the C++ object when the proxy class is garbage collected. If set to 0 (or if the attribute is missing), then the destruction of the proxy class has no effect on the C++ object.

    @@ -2623,8 +2701,8 @@ ownership of the result. For example:
     class Foo {
     public:
    -    Foo();
    -    Foo bar();
    +  Foo();
    +  Foo bar();
     };
     
    @@ -2653,9 +2731,9 @@ they came from. Therefore, the ownership is set to zero. For example:
     class Foo {
     public:
    -    ...
    -    Foo *spam();
    -    ...
    +  ...
    +  Foo *spam();
    +  ...
     };
     
    @@ -2694,8 +2772,8 @@ or global variable. For example, consider this interface: %module example struct Foo { - int value; - Foo *next; + int value; + Foo *next; }; Foo *head = 0; @@ -2712,7 +2790,7 @@ is assigned to a global variable. For example: >>> f = example.Foo() >>> f.thisown 1 ->>> example.cvar.head = f +>>> example.cvar.head = f >>> f.thisown 0 >>> @@ -2795,44 +2873,7 @@ It is also possible to deal with situations like this using typemaps--an advanced topic discussed later.

    -

    36.4.4 Python 2.2 and classic classes

    - - -

    -SWIG makes every attempt to preserve backwards compatibility with -older versions of Python to the extent that it is possible. However, -in Python-2.2, an entirely new type of class system was introduced. -This new-style class system offers many enhancements including static -member functions, properties (managed attributes), and class methods. -Details about all of these changes can be found on www.python.org and is not repeated here. -

    - -

    -To address differences between Python versions, SWIG currently emits -dual-mode proxy class wrappers. In Python-2.2 and newer releases, -these wrappers encapsulate C++ objects in new-style classes that take -advantage of new features (static methods and properties). However, -if these very same wrappers are imported into an older version of Python, -old-style classes are used instead. -

    - -

    -This dual-nature of the wrapper code means that you can create extension -modules with SWIG and those modules will work with all versions of Python -ranging from Python-2.0 to the very latest release. Moreover, the wrappers take -advantage of Python-2.2 features when available. -

    - -

    -For the most part, the interface presented to users is the same regardless -of what version of Python is used. The only incompatibility lies in the handling -of static member functions. In Python-2.2, they can be accessed via the -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). -

    - -

    36.5 Cross language polymorphism

    +

    33.5 Cross language polymorphism

    @@ -2866,7 +2907,7 @@ proxy classes, director classes, and C wrapper functions takes care of all the cross-language method routing transparently.

    -

    36.5.1 Enabling directors

    +

    33.5.1 Enabling directors

    @@ -2883,18 +2924,18 @@ option to the %module directive, like this:

    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 +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");         
    +%feature("director");
     
    -// generate directors for all virtual methods in class Foo
    -%feature("director") Foo;      
    +// generate directors for the virtual methods in class Foo
    +%feature("director") Foo;
     
    @@ -2911,12 +2952,12 @@ directors for specific classes or methods. So for example,

    -will generate directors for all virtual methods of class Foo except -bar(). +will generate directors for the virtual methods of class Foo except +bar().

    -Directors can also be generated implicitly through inheritance. +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()):

    @@ -2926,21 +2967,21 @@ the methods one() and two() (but not three()): %feature("director") Foo; class Foo { public: - Foo(int foo); - virtual ~Foo(); - virtual void one(); - virtual void two(); + Foo(int foo); + virtual ~Foo(); + virtual void one(); + virtual void two(); }; class Bar: public Foo { public: - virtual void three(); + virtual void three(); };

    -then at the python side you can define +then at the Python side you can define

    @@ -2953,15 +2994,12 @@ class MyFoo(mymodule.Foo): # super().__init__(foo) # Alternative construction for Python3 def one(self): - print "one from python" + print "one from Python"
    -

    36.5.2 Director classes

    - - - +

    33.5.2 Director classes

    @@ -2980,7 +3018,8 @@ 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 +Virtual methods that have a final specifier are unsurprisingly excluded. +Thus the virtual method calls, whether they originate in C++ or in Python 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 @@ -3040,7 +3079,7 @@ so there is no need for the extra overhead involved with routing the calls through Python.

    -

    36.5.3 Ownership and object destruction

    +

    33.5.3 Ownership and object destruction

    @@ -3077,12 +3116,12 @@ references. Here is an example:

     class Foo {
     public:
    -    ...
    +  ...
     };
     class FooContainer {
     public:
    -    void addFoo(Foo *);
    -    ...
    +  void addFoo(Foo *);
    +  ...
     };
     
    @@ -3107,7 +3146,7 @@ deleting all the Foo pointers it contains at some point. Note that no hard references to the Foo objects remain in Python.

    -

    36.5.4 Exception unrolling

    +

    33.5.4 Exception unrolling

    @@ -3123,9 +3162,9 @@ suffice in most cases:

     %feature("director:except") {
    -    if ($error != NULL) {
    -        throw Swig::DirectorMethodException();
    -    }
    +  if ($error != NULL) {
    +    throw Swig::DirectorMethodException();
    +  }
     }
     
    @@ -3152,8 +3191,8 @@ suitable exception handler:
     %exception {
    -    try { $action }
    -    catch (Swig::DirectorException &e) { SWIG_fail; }
    +  try { $action }
    +  catch (Swig::DirectorException &e) { SWIG_fail; }
     }
     
    @@ -3166,7 +3205,7 @@ Swig::DirectorMethodException is thrown, Python will register the exception as soon as the C wrapper function returns.

    -

    36.5.5 Overhead and code bloat

    +

    33.5.5 Overhead and code bloat

    @@ -3200,7 +3239,7 @@ directive) for only those methods that are likely to be extended in Python.

    -

    36.5.6 Typemaps

    +

    33.5.6 Typemaps

    @@ -3214,7 +3253,7 @@ need to be supported.

    -

    36.5.7 Miscellaneous

    +

    33.5.7 Miscellaneous

    @@ -3224,13 +3263,13 @@ be able to use std::vector, std::string, etc., as you would any other type.

    Note: The director typemaps for return types based in const -references, such as +references, such as

     class Foo {
     …
    -    virtual const int& bar();
    +  virtual const int& bar();
     …
     };
     
    @@ -3248,7 +3287,7 @@ types, wherever possible, for example
     class Foo {
     …
    -    virtual int bar();
    +  virtual int bar();
     …
     };
     
    @@ -3261,7 +3300,7 @@ methods that return const references.

    -

    36.6 Common customization features

    +

    33.6 Common customization features

    @@ -3274,7 +3313,7 @@ This section describes some common SWIG features that are used to improve your the interface to an extension module.

    -

    36.6.1 C/C++ helper functions

    +

    33.6.1 C/C++ helper functions

    @@ -3355,7 +3394,7 @@ hard to implement. It is possible to clean this up using Python code, typemaps, customization features as covered in later sections.

    -

    36.6.2 Adding additional Python code

    +

    33.6.2 Adding additional Python code

    @@ -3420,7 +3459,9 @@ 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: +The following example for Python 2.x shows how to insert code into the +generated wrapper to enable print to be used as a Python3-compatible +function instead of a statement:

    @@ -3437,13 +3478,13 @@ print("Loading", "Whizz", "Bang", sep=' ... ')

    -which can be seen when viewing the first few lines of the generated .py file: +The insert code can be seen at the start of the generated .py file:

     # This file was automatically generated by SWIG (http://www.swig.org).
    -# Version 2.0.11
    +# Version 4.0.0
     #
     # Do not make changes to this file unless you know what you are doing--modify
     # the SWIG interface file instead.
    @@ -3469,7 +3510,7 @@ an error for invalid preprocessor directives, so you may have to update
     existing interface files to delimit blocks of Python code correctly.

    As an alternative to providing a block containing Python code, you can -include python code from a file. The code is inserted exactly as in the +include Python code from a file. The code is inserted exactly as in the file, so this avoids any issues with the SWIG preprocessor. It's a good approach if you have a non-trivial chunk of Python code to insert. To use this feature you specify a filename in double quotes, for example:

    @@ -3490,7 +3531,7 @@ entirely replace a proxy function you can use
     %module example
     
    -// Rewrite bar() python code
    +// Rewrite bar() Python code
     
     %feature("shadow") Foo::bar(int) %{
     def bar(*args):
    @@ -3498,16 +3539,16 @@ def bar(*args):
         $action
         #do something after
     %}
    -    
    +
     class Foo {
     public:
    -    int bar(int x);
    +  int bar(int x);
     };
     

    where $action will be replaced by the call to -the C/C++ proper method. +the C/C++ proper method.

    @@ -3525,7 +3566,7 @@ proxy, just before the return statement.

     %module example
     
    -// Add python code to bar() 
    +// Add Python code to bar()
     
     %feature("pythonprepend") Foo::bar(int) %{
         #do something before C++ call
    @@ -3533,12 +3574,13 @@ proxy, just before the return statement.
     
     %feature("pythonappend") Foo::bar(int) %{
         #do something after C++ call
    +    #the 'val' variable holds the return value
     %}
     
    -    
    +
     class Foo {
     public:
    -    int bar(int x);
    +  int bar(int x);
     };
     
    @@ -3554,7 +3596,7 @@ SWIG version 1.3.28 you can use the directive forms
     %module example
     
    -// Add python code to bar() 
    +// Add Python code to bar()
     
     %pythonprepend Foo::bar(int) %{
         #do something before C++ call
    @@ -3562,12 +3604,13 @@ SWIG version 1.3.28 you can use the directive forms
     
     %pythonappend Foo::bar(int) %{
         #do something after C++ call
    +    #the 'val' variable holds the return value
     %}
     
    -    
    +
     class Foo {
     public:
    -    int bar(int x);
    +  int bar(int x);
     };
     
    @@ -3583,7 +3626,7 @@ as it will then get attached to all the overloaded C++ methods. For example:
     %module example
     
    -// Add python code to bar()
    +// Add Python code to bar()
     
     %pythonprepend Foo::bar %{
         #do something before C++ call
    @@ -3596,8 +3639,8 @@ as it will then get attached to all the overloaded C++ methods. For example:
     
     class Foo {
     public:
    -    int bar(int x);
    -    int bar();
    +  int bar(int x);
    +  int bar();
     };
     
    @@ -3607,7 +3650,7 @@ The same applies for overloaded constructors.

    -

    36.6.3 Class extension with %extend

    +

    33.6.3 Class extension with %extend

    @@ -3658,7 +3701,7 @@ Vector(2, 3, 4)

    -%extend can be used for many more tasks than this. +%extend can be used for many more tasks than this. For example, if you wanted to overload a Python operator, you might do this:

    @@ -3687,7 +3730,7 @@ Use it like this: >>> w = example.Vector(10, 11, 12) >>> print v+w Vector(12, 14, 16) ->>> +>>> @@ -3696,7 +3739,7 @@ Vector(12, 14, 16) in any way---the extensions only show up in the Python interface.

    -

    36.6.4 Exception handling with %exception

    +

    33.6.4 Exception handling with %exception

    @@ -3830,7 +3873,143 @@ The language-independent exception.i library file can also be used to raise exceptions. See the SWIG Library chapter.

    -

    36.7 Tips and techniques

    +

    33.6.5 Optimization options

    + + +

    33.6.5.1 -fastproxy

    + + +

    +The -fastproxy command line option enables faster method calling as the call is made directly into the C/C++ layer rather than going through a method wrapper. +

    + +

    +Consider wrapping a C++ class: +

    + +
    +
    +struct Go {
    +  void callme0() {}
    +  void callme4(int a, int b, int c, int d) {}
    +  void callme8(double a, double b, double c, double d, double e, double f, double g, double i) {}
    +};
    +
    +
    + +

    +The default generated proxy class is: +

    + +
    +
    +class Go(object):
    +    def callme0(self):
    +        return _example.Go_callme0(self)
    +
    +    def callme4(self, a, b, c, d):
    +        return _example.Go_callme4(self, a, b, c, d)
    +
    +    def callme8(self, a, b, c, d, e, f, g, i):
    +        return _example.Go_callme8(self, a, b, c, d, e, f, g, i)
    +    ...
    +
    +
    + +

    +Each method in the Python class contains a Python proxy method which passes the arguments on to the underlying function in the low-level C/C++ module (_example in this case). +The generated proxy class when using -fastproxy is: +

    + +
    +
    +%module example
    +class Go(object):
    +    callme0 = _swig_new_instance_method(_example.Go_callme0)
    +    callme4 = _swig_new_instance_method(_example.Go_callme4)
    +    callme8 = _swig_new_instance_method(_example.Go_callme8)
    +    ...
    +
    +
    + +

    +where _swig_new_instance_method adds the method to the proxy class via C API calls for direct access to the underlying function in the low-level C/C++ module. +Note that for some methods it is not possible to generate the direct access call and so -fastproxy is ignored. +This happens, for example, when adding additional code to Python proxy methods, such as using %pythonprepend. +

    + +

    +The overhead calling into C/C++ from Python is reduced slightly using -fastproxy. +Below are some timings in microseconds calling the 3 functions in the example above. +Also included in the table for comparison is using the -builtin option covered in the +Built-in Types. +

    + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Method nameDefault-fastproxy-builtin
    callme00.150.090.07
    callme40.260.160.14
    callme80.320.200.17
    + +

    +Although the -fastproxy option results in faster code over the default, the generated proxy code is not as user-friendly +as docstring/doxygen comments and functions with default values are not visible in the generated Python proxy class. +The -olddefs option can rectify this. +

    + +

    +The generated proxy class for the example above when using -fastproxy -olddefs is: +

    + +
    +
    +class Go(object):
    +    def callme0(self):
    +        return _example.Go_callme0(self)
    +    callme0 = _swig_new_instance_method(_example.Go_callme0)
    +
    +    def callme4(self, a, b, c, d):
    +        return _example.Go_callme4(self, a, b, c, d)
    +    callme4 = _swig_new_instance_method(_example.Go_callme4)
    +
    +    def callme8(self, a, b, c, d, e, f, g, i):
    +        return _example.Go_callme8(self, a, b, c, d, e, f, g, i)
    +    callme8 = _swig_new_instance_method(_example.Go_callme8)
    +    ...
    +
    +
    + +

    +The class defines each method in two different ways. The first definition is replaced by the second definition and so the second definition is the one used when the method is called. +While this possibly provides the best of both worlds, the time to import the module will be slightly slower when the class is defined due to the additional method definitions. +

    + +

    +The command line options mentioned above also apply to wrapped C/C++ global functions, not just class methods. +

    + +

    33.7 Tips and techniques

    @@ -3840,7 +4019,7 @@ strings, binary data, and arrays. This chapter discusses the common techniques solving these problems.

    -

    36.7.1 Input and output parameters

    +

    33.7.1 Input and output parameters

    @@ -3991,7 +4170,7 @@ int send_message(char *text, int *success);

    -When used in Python, the function will return multiple values. +When used in Python, the function will return multiple values.

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

    -

    36.7.2 Simple pointers

    +

    33.7.2 Simple pointers

    @@ -4122,7 +4301,7 @@ If you replace %pointer_functions() by %pointer_class(type, name)SWIG Library chapter for further details.

    -

    36.7.3 Unbounded C Arrays

    +

    33.7.3 Unbounded C Arrays

    @@ -4132,17 +4311,17 @@ Sometimes a C function expects an array to be passed as a pointer. For example,

     int sumitems(int *first, int nitems) {
    -    int i, sum = 0;
    -    for (i = 0; i < nitems; i++) {
    -        sum += first[i];
    -    }
    -    return sum;
    +  int i, sum = 0;
    +  for (i = 0; i < nitems; i++) {
    +    sum += first[i];
    +  }
    +  return sum;
     }
     

    -To wrap this into Python, you need to pass an array pointer as the first argument. +To wrap this into Python, you need to pass an array pointer as the first argument. A simple way to do this is to use the carrays.i library file. For example:

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

    -

    36.7.4 String handling

    +

    33.7.4 String handling

    @@ -4219,13 +4398,13 @@ using the cstring.i library file described in the 36.7.5 Default arguments +

    33.7.5 Default arguments

    C++ default argument code generation is documented in the main Default arguments section. -There is also an optional Python specific feature that can be used called the python:cdefaultargs +There is also an optional Python specific feature that can be used called the python:cdefaultargs feature flag. By default, SWIG attempts to convert C++ default argument values into Python values and generates code into the Python layer containing these values. @@ -4303,7 +4482,7 @@ class CDA(object):

    Adding the feature:

    - +
     %feature("python:cdefaultargs") CDA::fff;
    @@ -4353,7 +4532,7 @@ Versions of SWIG prior to this varied in their ability to convert C++ default va
     equivalent Python default argument values.
     

    -

    36.8 Typemaps

    +

    33.8 Typemaps

    @@ -4364,17 +4543,17 @@ as the material in the "Typemaps" chapter.

    -Before proceeding, it should be stressed that typemaps are not a required +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-Python interface or if you want to elevate your guru status.

    -

    36.8.1 What is a typemap?

    +

    33.8.1 What is a typemap?

    -A typemap is nothing more than a code generation rule that is attached to +A typemap is nothing more than a code generation rule that is attached to a specific C datatype. For example, to convert integers from Python to C, you might define a typemap like this:

    @@ -4486,7 +4665,7 @@ parameter is omitted):
    -

    36.8.2 Python typemaps

    +

    33.8.2 Python typemaps

    @@ -4506,7 +4685,7 @@ like this:

    A detailed list of available methods can be found in the "Typemaps" chapter. +href="Typemaps.html#Typemaps">Typemaps" chapter.

    @@ -4517,7 +4696,7 @@ looking at the files in the SWIG library. Just take into account that in the latest versions of swig (1.3.22+), the library files are not very pristine clear for the casual reader, as they used to be. The extensive use of macros and other ugly techniques in the latest -version produce a very powerful and consistent python typemap library, +version produce a very powerful and consistent Python typemap library, but at the cost of simplicity and pedagogic value.

    @@ -4527,7 +4706,7 @@ a look at the SWIG library version 1.3.20 or so.

    -

    36.8.3 Typemap variables

    +

    33.8.3 Typemap variables

    @@ -4568,7 +4747,7 @@ A PyObject * that holds the result to be returned to Python.

    -The parameter name that was matched. +The parameter name that was matched.

    @@ -4598,7 +4777,7 @@ properly assigned. The Python name of the wrapper function being created.

    -

    36.8.4 Useful Python Functions

    +

    33.8.4 Useful Python Functions

    @@ -4726,7 +4905,7 @@ write me -

    36.9 Typemap Examples

    +

    33.9 Typemap Examples

    @@ -4735,7 +4914,7 @@ might look at the files "python.swg" and "typemaps.i" in the SWIG library.

    -

    36.9.1 Converting Python list to a char **

    +

    33.9.1 Converting Python list to a char **

    @@ -4812,10 +4991,10 @@ 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. +the C function.

    -

    36.9.2 Expanding a Python object into multiple arguments

    +

    33.9.2 Expanding a Python object into multiple arguments

    @@ -4878,7 +5057,7 @@ previous example:

    -When writing a multiple-argument typemap, each of the types is referenced by a variable such +When writing a multiple-argument typemap, each of the types is referenced by a variable such as $1 or $2. The typemap code simply fills in the appropriate values from the supplied Python object.

    @@ -4927,14 +5106,14 @@ If you don't you'll get an error message along the lines of: Traceback (most recent call last): File "runme.py", line 3, in >module< example.foo(["foo", "bar", "spam", "1"]) -NotImplementedError: Wrong number or type of arguments for overloaded function 'foo'. +TypeError: Wrong number or type of arguments for overloaded function 'foo'. Possible C/C++ prototypes are: foo(int, char **) foo() -

    36.9.3 Using typemaps to return arguments

    +

    33.9.3 Using typemaps to return arguments

    @@ -4960,7 +5139,7 @@ A typemap can be used to handle this case as follows : %module outarg // This tells SWIG to treat an double * argument with name 'OutValue' as -// an output value. We'll append the value to the current result which +// an output value. We'll append the value to the current result which // is guaranteed to be a List object by SWIG. %typemap(argout) double *OutValue { @@ -5022,7 +5201,7 @@ function can now be used as follows: >>> -

    36.9.4 Mapping Python tuples into small arrays

    +

    33.9.4 Mapping Python tuples into small arrays

    @@ -5071,7 +5250,7 @@ array, such an approach would not be recommended for huge arrays, but for small structures, this approach works fine.

    -

    36.9.5 Mapping sequences to C arrays

    +

    33.9.5 Mapping sequences to C arrays

    @@ -5160,7 +5339,7 @@ static int convert_darray(PyObject *input, double *ptr, int size) { -

    36.9.6 Pointer handling

    +

    33.9.6 Pointer handling

    @@ -5257,9 +5436,168 @@ that has a this attribute. In addition, class object (if applicable).

    +

    33.9.7 Memory management when returning references to member variables

    -

    36.10 Docstring Features

    +

    +This example shows how to prevent premature garbage collection of objects when the underlying C++ class returns a pointer or reference to a member variable. +The example is a direct equivalent to this Java equivalent. +

    + +

    +Consider the following C++ code: +

    + +
    +
    +#include <iostream>
    +struct Wheel {
    +  int size;
    +  Wheel(int sz = 0) : size(sz) {}
    +  ~Wheel() { std::cout << "~Wheel" << std::endl; }
    +};
    +
    +class Bike {
    +  Wheel wheel;
    +public:
    +  Bike(int val) : wheel(val) {}
    +  Wheel& getWheel() { return wheel; }
    +};
    +
    +
    + +

    +and the following usage from Python after running the code through SWIG: +

    + + +
    +
    +bike = Bike(10)
    +wheel = bike.getWheel()
    +print("wheel size: {}".format(wheel.size))
    +
    +del bike  # Allow bike to be garbage collected
    +print("wheel size: {}".format(wheel.size))
    +
    +
    + +

    +Don't be surprised that if the resulting output gives strange results such as... +

    + +
    +
    +wheel size: 10
    +~Wheel
    +wheel size: 135019664
    +
    +
    + +

    +What has happened here is the garbage collector has collected the Bike instance as it doesn't think it is needed any more. +The proxy instance, wheel, contains a reference to memory that was deleted when the Bike instance was collected. +In order to prevent the garbage collector from collecting the Bike instance, a reference to the Bike must +be added to the wheel instance. +

    + +

    +You can do this by adding the reference when the getWheel() method +is called using one of three approaches: +

    + +

    +The easier, but less optimized, way is to use the %pythonappend directive +(see Adding additional Python code): +

    + +
    +
    +%pythonappend getWheel %{
    +  # val is the Wheel proxy, self is the Bike instance
    +  val.__bike_reference = self
    +%}
    +
    +
    + +

    +The code gets appended to the Python code generated for the +Bike::getWheel wrapper function, where we store the Bike proxy +instance onto the Wheel proxy instance before it is returned to the +caller as follows. +

    + +
    +
    +class Bike(object):
    +    ...
    +    def getWheel(self):
    +        val = _example.Bike_getWheel(self)
    +
    +        # val is the Wheel proxy, self is the Bike instance
    +        val.__bike_reference = self
    +
    +        return val
    +
    +
    + + +

    +The second option, which performs better and is required if you use the +-builtin option, is to set the reference in the CPython implementation: + +

    +
    +%extend Wheel {
    +// A reference to the parent class is added to ensure the underlying C++
    +// object is not deleted while the item is in use
    +%typemap(ret) Wheel& getWheel {
    +  PyObject *bike_reference_string = SWIG_Python_str_FromChar("__bike_reference");
    +  PyObject_SetAttr($result, bike_reference_string, $self);
    +  Py_DecRef(bike_reference_string);
    +}
    +}
    +
    +
    + +

    +The third approach, shown below, is an optimization of the above approach and creates the "__bike_reference" Python string object just once. +While this looks more complex, it is just a small variation on the above typemap plus a support function +bike_reference() in a fragment called bike_reference_function. +The bike_reference_init typemap generates code into the "init" section for an initial call to bike_reference() when the module +is initialized and is done to create the "__bike_reference" Python string singleton in a thread-safe manner. +

    + +
    +
    +%fragment("bike_reference_init", "init") {
    +  // Thread-safe initialization - initialize during Python module initialization
    +  bike_reference();
    +}
    +
    +%fragment("bike_reference_function", "header", fragment="bike_reference_init") {
    +
    +static PyObject *bike_reference() {
    +  static PyObject *bike_reference_string = SWIG_Python_str_FromChar("__bike_reference");
    +  return bike_reference_string;
    +}
    +
    +}
    +
    +%extend Wheel {
    +// A reference to the parent class is added to ensure the underlying C++
    +// object is not deleted while the item is in use
    +%typemap(ret, fragment="bike_reference_function") Wheel& getWheel %{
    +  PyObject_SetAttr($result, bike_reference(), $self);
    +%}
    +}
    +
    +
    + + + + +

    33.10 Docstring Features

    @@ -5287,7 +5625,7 @@ of your users much simpler.

    -

    36.10.1 Module docstring

    +

    33.10.1 Module docstring

    @@ -5312,7 +5650,7 @@ example:

     %define DOCSTRING
    -"The `XmlResource` class allows program resources defining menus, 
    +"The `XmlResource` class allows program resources defining menus,
     layout of controls on a panel, etc. to be loaded from an XML file."
     %enddef
     
    @@ -5321,7 +5659,7 @@ layout of controls on a panel, etc. to be loaded from an XML file."
     
    -

    36.10.2 %feature("autodoc")

    +

    33.10.2 %feature("autodoc")

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

    36.10.2.1 %feature("autodoc", "0")

    +

    33.10.2.1 %feature("autodoc", "0")

    @@ -5378,7 +5716,7 @@ def function_name(*args, **kwargs): -

    36.10.2.2 %feature("autodoc", "1")

    +

    33.10.2.2 %feature("autodoc", "1")

    @@ -5403,7 +5741,7 @@ def function_name(*args, **kwargs): -

    36.10.2.3 %feature("autodoc", "2")

    +

    33.10.2.3 %feature("autodoc", "2")

    @@ -5465,7 +5803,7 @@ def function_name(*args, **kwargs): -

    36.10.2.4 %feature("autodoc", "3")

    +

    33.10.2.4 %feature("autodoc", "3")

    @@ -5491,7 +5829,7 @@ def function_name(*args, **kwargs): -

    36.10.2.5 %feature("autodoc", "docstring")

    +

    33.10.2.5 %feature("autodoc", "docstring")

    @@ -5510,7 +5848,7 @@ void GetPosition(int* OUTPUT, int* OUTPUT); -

    36.10.3 %feature("docstring")

    +

    33.10.3 %feature("docstring")

    @@ -5542,7 +5880,7 @@ with more than one line. -

    36.11 Python Packages

    +

    33.11 Python Packages

    Python has concepts of modules and packages. Modules are separate units of @@ -5601,15 +5939,14 @@ Python3 adds another option for packages with namespace packages). Implicit namespace packages no longer use __init__.py files. SWIG generated Python modules support implicit namespace packages. See -36.11.5 Implicit Namespace -Packages for more information. +Implicit namespace +packages for more information.

    -If you place a SWIG generated module into a Python package then there -are details concerning the way SWIG -searches for the wrapper module -that you may want to familiarize yourself with. +You can place a SWIG generated module into a Python package or keep as a global module, +details are covered a little later in +Location of modules.

    The way Python defines its modules and packages impacts SWIG users. Some @@ -5617,7 +5954,7 @@ users may need to use special features such as the package option in th %module directive or import related command line options. These are explained in the following sections.

    -

    36.11.1 Setting the Python package

    +

    33.11.1 Setting the Python package

    @@ -5671,7 +6008,7 @@ pkg1/pkg2/_foo.so # (shared library built from C/C++ code generated by SWI -

    36.11.2 Absolute and relative imports

    +

    33.11.2 Absolute and relative imports

    Suppose, we have the following hierarchy of files:

    @@ -5768,12 +6105,19 @@ class M2(pkg2.mod3.M3): pass -

    By default, SWIG would generate mod2.py proxy file with +

    By default, SWIG will generate mod2.py proxy file with import directive as in point 1. This can be changed with the -relativeimport command line option. The -relativeimport instructs -SWIG to organize imports as in point 2 (for Python < 2.7.0) or as in point 4 -for Python 2.7.0 and newer. This is a check done at the time the module is -imported. In short, if you have +SWIG to organize imports as in point 4 for Python 2.7.0 and newer. +

    + +

    +Compatibility Note: Versions of SWIG prior to SWIG-4.0.0 supported Python < 2.7.0 +and would organize the imports as in point 2 if an older version of Python was detected at runtime. +

    + +

    +In short, if you have mod2.i and mod3.i as above, then without -relativeimport SWIG will write

    @@ -5788,13 +6132,8 @@ write

    -from sys import version_info
    -if version_info >= (2, 7, 0):
    -    from . import pkg2
    -    import pkg1.pkg2.mod3
    -else:
    -    import pkg2.mod3
    -del version_info
    +from . import pkg2
    +from .pkg2 import mod3
     
    @@ -5806,7 +6145,7 @@ uses relative imports. Second case is, when one puts import directives in __init__.py to import symbols from submodules or subpackages and the submodule depends on other submodules (discussed later).

    -

    36.11.3 Enforcing absolute import semantics

    +

    33.11.3 Enforcing absolute import semantics

    As you may know, there is an incompatibility in import semantics (for the @@ -5832,7 +6171,7 @@ from __future__ import absolute_import -

    at the very beginning of his proxy *.py file. In SWIG, it may be +

    at the very beginning of your proxy *.py file. In SWIG, it may be accomplished with %pythonbegin directive as follows:

    @@ -5843,7 +6182,7 @@ from __future__ import absolute_import
    -

    36.11.4 Importing from __init__.py

    +

    33.11.4 Importing from __init__.py

    Imports in __init__.py are handy when you want to populate a @@ -5953,7 +6292,7 @@ class Bar(pkg3.foo.Foo): pass effect (note, that the Python 2 case also needs the -relativeimport workaround).

    -

    36.11.5 Implicit Namespace Packages

    +

    33.11.5 Implicit namespace packages

    Python 3.3 introduced @@ -6000,7 +6339,7 @@ packages you can place these files in the following configurations: -

    Finally suppose that your pure python code is stored in a .zip file or +

    Finally suppose that your pure Python code is stored in a .zip file or some other way (database, web service connection, etc). Python can load the robin.py module using a custom importer. But the _robin.so module will need to be located on a file system. Implicit namespace packages make this @@ -6031,42 +6370,180 @@ zipimporter requires python-3.5.1 or newer to work with subpackages.

    -

    36.11.6 Searching for the wrapper module

    +

    33.11.6 Location of modules

    When SWIG creates wrappers from an interface file, say foo.i, two Python modules are -created. There is a pure Python module module (foo.py) and C/C++ code which is -built and linked into a dynamically (or statically) loaded low-level module _foo -(see the Preliminaries section for details). So, the interface +created. There is a pure Python module (foo.py) and C/C++ code which is +compiled and linked into a dynamically (or statically) loaded low-level module _foo +(see the Preliminaries section for details). So, the interface file really defines two Python modules. How these two modules are loaded is covered next.

    -The pure Python module needs to load the C/C++ module in order to link -to the wrapped C/C++ methods. To do this it must make some assumptions -about what package the C/C++ module may be located in. The approach the -pure Python module uses to find the C/C++ module is as follows: +The pure Python module needs to load the C/C++ module in order to call +the wrapped C/C++ methods. To do this it must make some assumptions +about the location of the C/C++ module. +There are two configurations that are supported by default.

      -
    1. The pure Python module, foo.py, tries to load the C/C++ module, _foo, from the same package foo.py is - located in. The package name is determined from the __name__ - attribute given to foo.py by the Python loader that imported - foo.py. If foo.py is not in a package then _foo is loaded - as a global module.

      +
    2. Both modules in the same package

    3. -
    4. If the above import of _foo results in an ImportError - being thrown, then foo.py makes a final attempt to load _foo - as a global module.

      +
    5. Both modules are global

    -The Python code implementing the loading logic described above is quite complex to handle multiple -versions of Python, but it can be replaced with custom code. -This is not recommended unless you understand the full intricacies of importing Python modules. +Additional configurations are supported but require custom import code. +

    + + +

    +The following sub-sections look more closely at the two default configurations as well as some customized configurations. +An input interface file, foo.i, results in the two modules foo.py and _foo.so for each of the configurations. +

    + +

    33.11.6.1 Both modules in the same package

    + + +

    +In this configuration, the pure Python module, foo.py, tries to load the C/C++ module, _foo, from the same package foo.py is +located in. The package name is determined from the __package__ +attribute if available, see PEP 366. Otherwise it is derived from the __name__ +attribute given to foo.py by the Python loader that imported foo.py. +The interface file for this configuration would contain: +

    + +
    +
    +%module(package="mypackage") foo
    +
    +
    + +

    The location of the files could be as follows:

    +
    +
    +/dir/mypackage/foo.py
    +/dir/mypackage/__init__.py
    +/dir/mypackage/_foo.so
    +
    +
    + +

    Assuming /dir/ is in PYTHONPATH, the module can be imported using

    + +
    +
    +from mypackage import foo
    +
    +
    + + +

    33.11.6.2 Both modules are global

    + + +

    +In this configuration, there are no packages. +If foo.py is not in a package, that is, it is a global module, then _foo is loaded +as a global module. +The interface file for this configuration would contain: +

    + +
    +
    +%module foo
    +
    +
    + +

    The location of the files could be as follows:

    +
    +
    +/dir/foo.py
    +/dir/_foo.so
    +
    +
    + +

    Assuming /dir/ is in PYTHONPATH, the module can be imported using

    + +
    +
    +import foo
    +
    +
    + +

    33.11.6.3 Split modules custom configuration

    + + +

    In this non-standard 'split module' configuration, the pure Python module is in a package and the low level C/C++ module is global. +This configuration is not generally recommended and is not supported by default as it needs a custom configuration. +The module import code customization required is via the moduleimport attribute in the %module directive. +The next sub-section elaborates further on this. +The interface file for this split module configuration would contain: +

    + +
    +
    +%module(package="mypackage", moduleimport="import _foo") foo
    +
    +
    + +

    +When using -builtin, use the following instead (the reasons are also covered shortly in the next sub-section): +

    + +
    +
    +%module(package="mypackage", moduleimport="from _foo import *") foo
    +
    +
    + +

    The location of the files could be as follows:

    +
    +
    +/dir/mypackage/foo.py
    +/dir/mypackage/__init__.py
    +/dir/_foo.so
    +
    +
    + +

    Assuming /dir/ is in PYTHONPATH, the module can be imported using

    + +
    +
    +from mypackage import foo
    +
    +
    + +

    +Compatibility Note: Versions of SWIG prior to SWIG-4.0.0 supported split modules without the above customization. +However, this had to be removed as the default import code often led to confusion due to obfuscation of genuine Python ImportError problems. +Using one of the two default configurations is the recommended approach now. +

    + + +

    33.11.6.4 More on customizing the module import code

    + + +

    +The Python code implementing the default import logic is shown below. It supports the two configurations described earlier, that is, +either both modules are in a package or loading both as global modules. +The code is generated into the pure Python module, foo.py, and merely imports the low-level _foo module. +

    + +
    +
    +if __package__ or '.' in __name__:
    +    from . import _foo
    +else:
    +    import _foo
    +
    +
    + +

    +This import code implementation is non-trivial but it can be replaced with custom code providing opportunities to make it simpler and/or more flexible. +This is not normally recommended though unless you have a good understanding of the intricacies of importing Python modules. The custom code can be specified by setting the moduleimport option of the %module directive with the appropriate import code. For example:

    @@ -6077,8 +6554,33 @@ The custom code can be specified by setting the moduleimport option of

    -The special variable $module will also be expanded into the low-level C/C++ module name, _foo in the case above. -When you have more than just a line or so then you can retain the easy +This will replace the default import logic above and generate the following into the pure Python module, foo.py: +

    + +
    +
    +import _foo
    +
    +
    + +

    +In fact the above is a simplification customization for the configuration where both modules are global; +it removes the logic for also handling the modules being in a package. +

    + +

    +There is a special variable, $module, which is expanded into the low-level C/C++ module name, _foo in the case above. +The identical output would be generated if instead the following had been used: +

    + +
    +
    +%module(moduleimport="import $module") foo
    +
    +
    + +

    +When you have many lines you can retain the easy readability of the %module directive by using a macro. For example:

    @@ -6097,79 +6599,51 @@ print 'Module has loaded' -

    -Now let's consider an example using the SWIG default loading logic. -Suppose foo.i is compiled into foo.py and _foo.so. Assuming -/dir is on PYTHONPATH, then the two modules can be installed and used in the -following ways: +This will of course generate the following into the pure Python module:

    - -

    36.11.6.1 Both modules in the same package

    - - -

    Both modules are in one package:

    -
    +
    -/dir/package/foo.py
    -/dir/package/__init__.py
    -/dir/package/_foo.so
    -
    -
    -

    And imported with

    -
    -
    -from package import foo
    -
    -
    - - -

    36.11.6.2 Split modules

    - - -

    The pure python module is in a package and the C/C++ module is global:

    -
    -
    -/dir/package/foo.py
    -/dir/package/__init__.py
    -/dir/_foo.so
    -
    -
    -

    And imported with

    -
    -
    -from package import foo
    -
    -
    - - -

    36.11.6.3 Both modules are global

    - - -

    Both modules are global:

    -
    -
    -/dir/foo.py
    -/dir/_foo.so
    -
    -
    -

    And imported with

    -
    -
    -import foo
    +print 'Loading low-level module $module'
    +import _foo
    +print 'Module has loaded'
     

    -If _foo is statically linked into an embedded Python interpreter, then it may or -may not be in a Python package. This depends in the exact way the module was -loaded statically. The above search order will still be used for statically -loaded modules. So, one may place the module either globally or in a package -as desired. +When using the -builtin option, the link between the pure Python module and the low-level C/C++ module is slightly different as +all the objects from the low-level module are imported directly into the pure Python module. +The default import loading code is thus different:

    -

    36.11.6.4 Statically linked C modules

    +
    +
    +if __package__ or '.' in __name__:
    +    from ._foo import *
    +else:
    +    from _foo import *
    +
    +
    + +

    +Any customizations must import the code in a similar manner. +The best way to support both with and without -builtin is to make use of the SWIGPYTHON_BUILTIN macro which is defined when -builtin is specified. +The following will do this for the split modules case above. +

    + + +
    +
    +#if defined(SWIGPYTHON_BUILTIN) /* defined when using -builtin */
    +%module(package="mypackage", moduleimport="from $module import *") foo
    +#else
    +%module(package="mypackage", moduleimport="import $module") foo
    +#endif
    +
    +
    + +

    33.11.6.5 Statically linked C modules

    It is strongly recommended to use dynamically linked modules for the C @@ -6178,7 +6652,7 @@ If for some reason you still need to link the C module of the pair of Python modules generated by SWIG into your interpreter, then this section provides some details on how this impacts the pure Python modules ability to locate the other part of the pair. -Please also see the Static Linking section. +Please also see the Static Linking section.

    When Python is extended with C code the Python interpreter needs to be @@ -6195,7 +6669,7 @@ new SWIG C module exists. which would have normally been called when the shared object was dynamically loaded. The specific name of this method is not given here because statically linked modules are not encouraged with SWIG -(Static Linking). However one can find this +(Static Linking). However one can find this init function in the C file generated by SWIG.

    @@ -6207,8 +6681,8 @@ they treat it affects how the pure Python module will be able to locate the C module.

    -

    The details concerning this are covered completly in the documentation -for Python itself. Links to the relavent sections follow: +

    The details concerning this are covered completely in the documentation +for Python itself. Links to the relevant sections follow:

      @@ -6218,21 +6692,21 @@ for Python itself. Links to the relavent sections follow:

      There are two keys things to understand. The first is that in Python 2 the init() function returns void. In Python 3 the init() function -returns a PyObject * which points to the new module. Secondly, when +returns a PyObject * which points to the new module. Secondly, when you call the init() method manually, you are the Python importer. So, you determine which package the C module will be located in.

      So, if you are using Python 3 it is important that you follow what is described in the Python documentation linked above. In particular, you can't -simply call the init() function generated by SWIG and cast the PyObject +simply call the init() function generated by SWIG and cast the PyObject pointer it returns over the side. If you do then Python 3 will have no idea that your C module exists and the pure Python half of your wrapper will not be able to find it. You need to register your module with the Python interpreter as described in the Python docs.

      -

      With Python 2 things are somewhat more simple. In this case the init function +

      With Python 2 things are somewhat more simple. In this case the init() function returns void. Calling it will register your new C module as a global module. The pure Python part of the SWIG wrapper will be able to find it because it tries both the pure Python module it is part of and the global @@ -6241,17 +6715,15 @@ module then you will either need to refer to the Python documentation on how to do this (remember you are now the Python importer) or use dynamic linking.

      -

      36.12 Python 3 Support

      +

      33.12 Python 3 Support

      -SWIG is able to support Python 3.0. The wrapper code generated by -SWIG can be compiled with both Python 2.x or 3.0. Further more, by +SWIG is able to support Python 3.x. The wrapper code generated by +SWIG can be compiled with both Python 2.x or 3.x. Further more, by passing the -py3 command line option to SWIG, wrapper code with some Python 3 specific features can be generated (see below -subsections for details of these features). The -py3 option also -disables some incompatible features for Python 3, such as --classic. +subsections for details of these features).

      There is a list of known-to-be-broken features in Python 3: @@ -6264,11 +6736,11 @@ There is a list of known-to-be-broken features in Python 3:

    -The following are Python 3.0 new features that are currently supported by +The following are Python 3 new features that are currently supported by SWIG.

    -

    36.12.1 Function annotation

    +

    33.12.1 Function annotation

    @@ -6301,12 +6773,12 @@ For detailed usage of function annotation, see PEP 3107.

    -

    36.12.2 Buffer interface

    +

    33.12.2 Buffer interface

    -Buffer protocols were revised in Python 3. SWIG also gains a series of -new typemaps to support buffer interfaces. These typemap macros are +SWIG has a series of +typemaps to support buffer interfaces. These typemap macros are defined in pybuffer.i, which must be included in order to use them. By using these typemaps, your wrapped function will be able to accept any Python object that exposes a suitable buffer interface. @@ -6323,15 +6795,15 @@ void get_path(char *s);

    Then you can write a typemap like this: (the following example is -applied to both Python 3.0 and 2.6, since the bytearray type -is backported to 2.6. +applied to both Python 2 and 3, since the bytearray type +was backported to 2.6.

     %include <pybuffer.i>
     %pybuffer_mutable_string(char *str);
    -void get_path(char *s);
    +void get_path(char *str);
     

    @@ -6378,7 +6850,7 @@ In Python: >>> snprintf(buf, "Hello world!") >>> print(buf) bytearray(b'Hello\x00') ->>> +>>>

    @@ -6414,7 +6886,7 @@ bytearray(b'FOO\x00')

    Both %pybuffer_mutable_binary and %pybuffer_mutable_string -require the provided buffer to be mutable, eg. they can accept a +require the provided buffer to be mutable, eg. they can accept a bytearray type but can't accept an immutable byte type.

    @@ -6431,7 +6903,7 @@ type. This macro maps an object's buffer to a pointer parm and a size size_parm. It is similar to %pybuffer_mutable_binary, except the -%pybuffer_binary an accept both mutable and immutable +%pybuffer_binary can accept both mutable and immutable buffers. As a result, the wrapped function should not modify the buffer.

    @@ -6453,13 +6925,14 @@ modify the buffer. -

    36.12.3 Abstract base classes

    +

    33.12.3 Abstract base classes

    By including pyabc.i and using the -py3 command line option when calling SWIG, the proxy classes of the STL containers -will automatically gain an appropriate abstract base class. For +will automatically gain an appropriate abstract base class from the +collections.abc module. For example, the following SWIG interface:

    @@ -6476,8 +6949,8 @@ namespace std {

    will generate a Python proxy class Mapii inheriting from -collections.MutableMap and a proxy class IntList -inheriting from collections.MutableSequence. +collections.abc.MutableMap and a proxy class IntList +inheriting from collections.abc.MutableSequence.

    @@ -6486,7 +6959,7 @@ used to define an abstract base class for your own C++ class:

    -%pythonabc(MySet, collections.MutableSet);
    +%pythonabc(MySet, collections.abc.MutableSet);
     

    @@ -6494,7 +6967,15 @@ For details of abstract base class, please see PEP 3119.

    -

    36.12.4 Byte string output conversion

    +

    +Compatibility Note: SWIG-4.0.0 changed the base classes to use the +collections.abc module instead of collections due to the deprecation +of the classes in the collections module in Python 3.7. +The collections.abc module was introduced in Python 3.3 and hence this feature +requires Python 3.3 or later. +

    + +

    33.12.4 Byte string output conversion

    @@ -6511,18 +6992,21 @@ string that cannot be completely decoded as UTF-8:

     %module example
     
    -%include <std_string.i>
    -
     %inline %{
     
    -const char* non_utf8_c_str(void) {
    -        return "h\xe9llo w\xc3\xb6rld";
    +const char * non_utf8_c_str(void) {
    +  return "h\xe9llo w\xc3\xb6rld";
    +}
    +
    +void instring(const char *s) {
    +  ...
     }
     
     %}
     

    +Note that "\xe9" is an invalid UTF-8 encoding, but "\xc3\xb6" is valid. When this method is called from Python 3, the return value is the following text string:

    @@ -6580,6 +7064,20 @@ For more details about the surrogateescape error handler, please see PEP 383.

    +

    +When Python 3 strings are passed to the C/C++ layer, they are expected to be valid UTF8 Unicode strings too. +For example, when the instring method above is wrapped and called, any invalid UTF8 Unicode code strings +will result in a TypeError because the attempted conversion fails: +

    + +
    +>>> example.instring('h\xe9llo')
    +>>> example.instring('h\udce9llo')
    +Traceback (most recent call last):
    +  File "<stdin>", line 1, in <module>
    +TypeError: in method 'instring', argument 1 of type 'char const *'
    +
    +

    In some cases, users may wish to instead handle all byte strings as bytes objects in Python 3. This can be accomplished by adding @@ -6658,7 +7156,7 @@ overloads taking both std::string (as Python bytes) and std::wstring (as Python unicode).

    -

    36.12.5 Python 2 Unicode

    +

    33.12.5 Python 2 Unicode

    @@ -6730,6 +7228,110 @@ the first is allowing unicode conversion and the second is explicitly prohibiting it.

    +

    33.13 Support for Multithreaded Applications

    + + +

    By default, SWIG does not enable support for multithreaded Python applications. More +specifically, the Python wrappers generated by SWIG will not release the + Python's interpreter's Global Interpreter Lock (GIL) when wrapped C/C++ code is +entered. Hence, while any of the wrapped C/C++ code is executing, the Python interpreter +will not be able to run any other threads, even if the wrapped C/C++ code is waiting + in a blocking call for something like network or disk IO. + + Fortunately, SWIG does have the ability to enable multithreaded support and automatic + release of the GIL either for all wrapped code in a module or on a more selective basis. The user + interface for this is described in the next section. +

    + +

    33.13.1 UI for Enabling Multithreading Support

    + + +

    The user interface is as follows:

    +
      +
    1. Module thread support can be enabled in two ways:

      +
        +
      • +

        + The -threads SWIG Python option at the command line (or in setup.py): +

        +
        $ swig -python -threads example.i
        +
      • +
      • +

        + The threads module option in the *.i template file: +

        +
        %module("threads"=1)
        +
      • +
      +
    2. +
    3. You can disable thread support for a given method:

      +
      %feature("nothread") method;
      + or +
      %nothread method;
      +
    4. +
    5. You can partially disable thread support for a given method:

      +
        +
      • To disable the C++/Python thread protection:

        +
        %feature("nothreadblock") method;
        + or +
        %nothreadblock method;
        +
      • +
      • +

        To disable the Python/C++ thread protection

        +
        %feature("nothreadallow") method;
        + or +
        %nothreadallow method;
        +
      • +
      +
    6. +
    + +

    33.13.2 Multithread Performance

    + + +

    + For the curious about performance, here are some numbers for the profiletest.i test, + which is used to check the speed of the wrapped code: +

    + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Thread ModeExecution Time (sec)Comment
    Single Threaded9.6no "-threads" option given
    Fully Multithreaded15.5"-threads" option = 'allow' + 'block'
    No Thread block12.2only 'allow'
    No Thread Allow13.6only block'
    + +

    + Fully threaded code decreases the wrapping performance by + around 60%. If that is important to your application, you + can tune each method using the different 'nothread', + 'nothreadblock' or 'nothreadallow' features as + needed. Note that for some methods deactivating the + 'thread block' or 'thread allow' code is not an option, + so, be careful. +

    + diff --git a/Doc/Manual/R.html b/Doc/Manual/R.html index 40b96d6c9..e44fe432c 100644 --- a/Doc/Manual/R.html +++ b/Doc/Manual/R.html @@ -7,7 +7,7 @@ -

    37 SWIG and R

    +

    34 SWIG and R

    @@ -28,13 +31,19 @@ R is a GPL'ed open source statistical and plotting environment. Information about R can be found at www.r-project.org. - -The R bindings are under active development. They have been used to -compile and run an R interface to QuantLib running on Mandriva Linux -with gcc. The R bindings also work on Microsoft Windows using Visual C++.

    -

    37.1 Bugs

    +

    +The R bindings are under active development. They have been used to +compile and run an R interface to QuantLib running on Mandriva Linux +with gcc. They are also used to create the SimpleITK R package, which +runs on Linux and MacOS. SWIG is used to create all wrapper +interfaces +to SimpleITK. The R +bindings also work on Microsoft Windows using Visual C++. +

    + +

    34.1 Bugs

    @@ -42,11 +51,13 @@ Currently the following features are not implemented or broken:

      -
    • Garbage collection of created objects +
    • Garbage collection of some created objects. Finalizers are + available for wrapped C++ classes and are called by the + garbage collection system.
    • C Array wrappings
    -

    37.2 Using R and SWIG

    +

    34.2 Using R and SWIG

    @@ -113,11 +124,10 @@ cacheMetaData(1) +

    The cacheMetaData(1) will cause R to refresh its object tables. Without it, inheritance of wrapped objects may fail. - -

    -These two files can be loaded in any order +These two files can be loaded in any order.

    @@ -129,7 +139,7 @@ These two files can be loaded in any order

  • If you do not set the output file name appropriately, you might see errors like
    -> fact(4)
    +> fact(4)
     Error in .Call("R_swig_fact", s_arg1, as.logical(.copy), PACKAGE = "example") :
       "R_swig_fact" not available for .Call() for package "example"
     
    @@ -137,25 +147,32 @@ Error in .Call("R_swig_fact", s_arg1, as.logical(.copy), PACKAGE = "example") :
  • Make sure the architecture of the shared library(x64 for instance), matches the architecture of the R program you want to load your shared library into -

    37.3 Precompiling large R files

    +

    34.3 Precompiling large R files

    +

    In cases where the R file is large, one make save a lot of loading time by precompiling the R wrapper. This can be done by creating the file makeRData.R which contains the following +

    -
    +
     source('BigFile.R')
     save(list=ls(all=TRUE), file="BigFile.RData", compress=TRUE)
     q(save="no")
    -
    +
    +

    This will generate a compiled R file called BigFile.RData that will save a large amount of loading time. +

    +

    +There is no need to precompile large R files if the SWIG-generated code is being included +in an R package. The package infrastructure provides this service during package installation. +

    - -

    37.4 General policy

    +

    34.4 General policy

    @@ -164,34 +181,193 @@ wrapping over the underlying functions and rely on the R type system to provide R syntax.

    -

    37.5 Language conventions

    +

    34.5 Language conventions

    -getitem and setitem use C++ conventions (i.e. zero based indices). [<- +getitem and setitem use C++ conventions (i.e. zero based indices). [<- and [ are overloaded to allow for R syntax (one based indices and slices)

    -

    37.6 C++ classes

    +

    34.6 C++ classes

    -C++ objects are implemented as external pointer objects with the class -being the mangled name of the class. The C++ classes are encapsulated -as an SEXP with an external pointer type. The class is the mangled -name of the class. The nice thing about R is that is allows you to -keep track of the pointer object which removes the necessity for a lot -of the proxy class baggage you see in other languages. +Wrapping of C++ classes for R works quite well. R has a special +type, known as an external reference, that can be used as a pointer +to arbitary things, including C++ classes. The proxy layers generated +for other classes are not required.

    -

    37.7 Enumerations

    +

    + SWIG currently creates a custom hierarchy of R classes derived from the + external reference type and implements +type checking and function overloading in the R code it generates. In +the future we hope to utilise the built in R6 class structures. +

    + +

    +The R interface has the following capabilities: +

    +
      +
    • Destructor methods are registered and called automatically by the R garbage collector. +
    • A range of std::vector types are converted automatically to R equivalents via the std_vector.i library. +
    • The $ operator is used for method access. +
    • Variable accessors are automatically generated and called via the $, [, [[, $<-, [<-, [[<- operators. +
    + +

    34.6.1 Examples

    -enumerations are characters which are then converted back and forth to -ints before calling the C routines. All of the enumeration code is -done in R. +Consider the following simple example: +

    + +
    +
    +class Vehicle {
    +private:
    +  int m_axles;
    +
    +public:
    +  int Axles() {
    +    return(m_axles);
    +  }
    +
    +  bool Available;
    +
    +  Vehicle() {
    +    Available=false;
    +    m_axles=2;
    +  }
    +
    +  Vehicle(int ax) {
    +    Available=false;
    +    m_axles=ax;
    +  }
    +};
    +
    +
    + +

    +The following options are available in R: +

    + +
    +
    +v1 <- Vehicle()
    +v2 <- Vehicle(4)
    +# access members
    +v1$Axles()
    +[1] 2
    +v2$Axles
    +[1] 4
    +v1$Available
    +[1] FALSE
    +# Set availabilty
    +v1$Available <- TRUE
    +v1$Available
    +[1] TRUE
    +
    +
    + +

    +A useful trick to determine the methods that are available is to +query the R method definition as follows: +

    + +
    +
    +# display the methods for the class
    +getMethod("$", class(v1))
    +    
    +Method Definition:
    +
    +function (x, name) 
    +{
    +    accessorFuns = list(Axles = Vehicle_Axles, Available = Vehicle_Available_get)
    +    vaccessors = c("Available")
    +    idx = pmatch(name, names(accessorFuns))
    +    if (is.na(idx)) 
    +        return(callNextMethod(x, name))
    +    f = accessorFuns[[idx]]
    +    if (is.na(match(name, vaccessors))) 
    +        function(...) {
    +            f(x, ...)
    +        }
    +    else f(x)
    +}
    +
    +Signatures:
    +        x           
    +target  "_p_Vehicle"
    +defined "_p_Vehicle"
    +
    +
    +
    +

    +The names in the accessorFuns list correspond to class methods while names in the vaccessors section +correspond to variables that may be modified. +

    +

    34.7 Enumerations

    + + +

    +R doesn't have a native enumeration type. Enumerations are represented +as character strings in R, with calls to R functions that convert back +and forth between integers. +

    + +

    +The details of enumeration names and contents are stored in hidden R +environments, which are named according the the enumeration name - for +example, an enumeration colour: +

    + +
    +enum colour { red=-1, blue, green = 10 };
    +
    + +

    +will be initialized by the following call in R: +

    + +
    +defineEnumeration("_colour",
    + .values=c("red" = .Call('R_swig_colour_red_get',FALSE, PACKAGE='enum_thorough'),
    +"blue" = .Call('R_swig_colour_blue_get',FALSE, PACKAGE='enum_thorough'),
    +"green" = .Call('R_swig_colour_green_get',FALSE, PACKAGE='enum_thorough')))
    +
    + +

    +which will create an environment named .__E___colour. The enumeration +values are initialised via calls to C/C++ code, allowing complex +values for enumerations to be used. Calls to the C/C++ code require +the compiled library to be loaded, so a delayedAssign is employed +within defineEnumeration in order to allow the code to be easily used in R +packages. +

    + +

    +The user typically does not need to access the enumeration lookup +functions or know the name of the enumeration type used by +R. Attributes containing the type information are attached by swig to +functions requiring enumeration arguments or returning enumeration +values, and those attributes are used to identify and access the +appropriate environments and thus translate between characters +and integers. +

    + +

    +The relevant functions, for debugging purposes, are enumToInteger and +enumFromInteger. +

    + +

    +Anonymous enumerations are ignored by the binding generation process, +leaving no way of accessing the value of anonymous enumerations from R +code.

    diff --git a/Doc/Manual/Ruby.html b/Doc/Manual/Ruby.html index 51c0ae353..5581cc458 100644 --- a/Doc/Manual/Ruby.html +++ b/Doc/Manual/Ruby.html @@ -8,7 +8,7 @@ -

    38 SWIG and Ruby

    +

    35 SWIG and Ruby

      @@ -149,10 +149,10 @@

      This chapter describes SWIG's support of Ruby.

      -

      38.1 Preliminaries

      +

      35.1 Preliminaries

      -

      SWIG 3.0 is known to work with Ruby versions 1.8 and later. +

      SWIG 4.0 is known to work with Ruby versions 1.9 and later. Given the choice, you should use the latest stable version of Ruby. You should also determine if your system supports shared libraries and dynamic loading. SWIG will work with or without dynamic loading, but @@ -164,7 +164,7 @@ read the "SWIG Basics" chapter. It is also assumed that the reader has a basic understanding of Ruby.

      -

      38.1.1 Running SWIG

      +

      35.1.1 Running SWIG

      To build a Ruby module, run SWIG using the -ruby @@ -188,36 +188,21 @@ 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.

      -

      38.1.2 Getting the right header files

      +

      35.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/include/ruby-2.1.0/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:

      +header file and its dependencies, notably ruby/config.h which is +found in a different, architecture-dependent, directory. The best way to find +the compiler options needed to compile the code is to ask Ruby itself:

      -
      $ ruby -e 'puts $:.join("\n")'
      -/usr/local/lib/site_ruby/2.1.0
      -/usr/local/lib/x86_64-linux-gnu/site_ruby
      -/usr/local/lib/site_ruby
      -/usr/lib/ruby/vendor_ruby/2.1.0
      -/usr/lib/x86_64-linux-gnu/ruby/vendor_ruby/2.1.0
      -/usr/lib/ruby/vendor_ruby
      -/usr/lib/ruby/2.1.0
      -/usr/lib/x86_64-linux-gnu/ruby/2.1.0
      +
      $ ruby -rrbconfig -e 'puts "-I#{RbConfig::CONFIG[%q{rubyhdrdir}]} -I#{RbConfig::CONFIG[%q{rubyarchhdrdir}]}"'
      +-I/usr/include/ruby-2.1.0 -I/usr/include/x86_64-linux-gnu/ruby-2.1.0
       
      -

      38.1.3 Compiling a dynamic module

      +

      35.1.3 Compiling a dynamic module

      Ruby extension modules are typically compiled into shared @@ -290,7 +275,7 @@ manual pages for your compiler and linker to determine the correct set of options. You might also check the SWIG Wiki for additional information.

      -

      38.1.4 Using your module

      +

      35.1.4 Using your module

      Ruby module names must be capitalized, @@ -320,7 +305,7 @@ begins with:

      will result in an extension module using the feature name "example" and Ruby module name "Example".

      -

      38.1.5 Static linking

      +

      35.1.5 Static linking

      An alternative approach to dynamic linking is to rebuild the @@ -335,7 +320,7 @@ finding the Ruby source, adding an entry to the ext/Setup file, adding your directory to the list of extensions in the file, and finally rebuilding Ruby.

      -

      38.1.6 Compilation of C++ extensions

      +

      35.1.6 Compilation of C++ extensions

      On most machines, C++ extension modules should be linked @@ -367,7 +352,7 @@ $libs = append_library($libs, "supc++") create_makefile('example')

    -

    38.2 Building Ruby Extensions under Windows 95/NT

    +

    35.2 Building Ruby Extensions under Windows 95/NT

    Building a SWIG extension to Ruby under Windows 95/NT is @@ -392,7 +377,7 @@ order to build extensions, you may need to download the source distribution to the Ruby package, as you will need the Ruby header files.

    -

    38.2.1 Running SWIG from Developer Studio

    +

    35.2.1 Running SWIG from Developer Studio

    If you are developing your application within Microsoft @@ -456,13 +441,13 @@ Foo = 3.0 -

    38.3 The Ruby-to-C/C++ Mapping

    +

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

    -

    38.3.1 Modules

    +

    35.3.1 Modules

    The SWIG %module directive specifies @@ -534,7 +519,7 @@ option to wrap everything into the global module, take care that the names of your constants, classes and methods don't conflict with any of Ruby's built-in names.

    -

    38.3.2 Functions

    +

    35.3.2 Functions

    Global functions are wrapped as Ruby module methods. For @@ -568,7 +553,7 @@ irb(main):002:0> Example.fact(4) 24 -

    38.3.3 Variable Linking

    +

    35.3.3 Variable Linking

    C/C++ global variables are wrapped as a pair of singleton @@ -630,7 +615,25 @@ directive. For example:

    effect until it is explicitly disabled using %mutable.

    -

    38.3.4 Constants

    +

    Note: When SWIG is invoked with the -globalmodule option in +effect, the C/C++ global variables will be translated into Ruby global +variables. Type-checking and the optional read-only characteristic are +available in the same way as described above. However the example would +then have to be modified and executed in the following way: + +

    +
    $ irb
    +irb(main):001:0> require 'Example'
    +true
    +irb(main):002:0> $variable1 = 2
    +2
    +irb(main):003:0> $Variable2 = 4 * 10.3
    +41.2
    +irb(main):004:0> $Variable2
    +41.2
    +
    + +

    35.3.4 Constants

    C/C++ constants are wrapped as module constants initialized @@ -658,7 +661,7 @@ irb(main):002:0> Example::PI 3.14159 -

    38.3.5 Pointers

    +

    35.3.5 Pointers

    "Opaque" pointers to arbitrary C/C++ types (i.e. types that @@ -682,7 +685,7 @@ returns an instance of an internally generated Ruby class:

    A NULL pointer is always represented by the Ruby nil object.

    -

    38.3.6 Structures

    +

    35.3.6 Structures

    C/C++ structs are wrapped as Ruby classes, with accessor @@ -787,7 +790,7 @@ void Bar_f_set(Bar *b, Foo *val) { } -

    38.3.7 C++ classes

    +

    35.3.7 C++ classes

    Like structs, C++ classes are wrapped by creating a new Ruby @@ -842,7 +845,7 @@ Ale 3 -

    38.3.8 C++ Inheritance

    +

    35.3.8 C++ Inheritance

    The SWIG type-checker is fully aware of C++ inheritance. @@ -995,7 +998,7 @@ inherit from both Base1 and Base2 (i.e. they exhibit "Duck Typing").

    -

    38.3.9 C++ Overloaded Functions

    +

    35.3.9 C++ Overloaded Functions

    C++ overloaded functions, methods, and constructors are @@ -1085,7 +1088,7 @@ arises--in this case, the first declaration takes precedence.

    Please refer to the "SWIG and C++" chapter for more information about overloading.

    -

    38.3.10 C++ Operators

    +

    35.3.10 C++ Operators

    For the most part, overloaded operators are handled @@ -1127,7 +1130,7 @@ c = Example.add_complex(a, b) is discussed in the section on operator overloading.

    -

    38.3.11 C++ namespaces

    +

    35.3.11 C++ namespaces

    SWIG is aware of C++ namespaces, but namespace names do not @@ -1184,7 +1187,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.

    -

    38.3.12 C++ templates

    +

    35.3.12 C++ templates

    C++ templates don't present a huge problem for SWIG. However, @@ -1226,7 +1229,7 @@ irb(main):004:0> p.second 4 -

    38.3.13 C++ Standard Template Library (STL)

    +

    35.3.13 C++ Standard Template Library (STL)

    On a related note, the standard SWIG library contains a @@ -1319,7 +1322,7 @@ puts v shown in these examples. More details can be found in the SWIG and C++ chapter.

    -

    38.3.14 C++ STL Functors

    +

    35.3.14 C++ STL Functors

    Some containers in the STL allow you to modify their default @@ -1380,7 +1383,7 @@ b -

    38.3.15 C++ STL Iterators

    +

    35.3.15 C++ STL Iterators

    The STL is well known for the use of iterators. There @@ -1463,10 +1466,10 @@ i

    If you'd rather have STL classes without any iterators, you should define -DSWIG_NO_EXPORT_ITERATOR_METHODS when running swig.

    -

    38.3.16 C++ Smart Pointers

    +

    35.3.16 C++ Smart Pointers

    -

    38.3.16.1 The shared_ptr Smart Pointer

    +

    35.3.16.1 The shared_ptr Smart Pointer

    @@ -1477,7 +1480,7 @@ in the shared_ptr smart pointer -

    38.3.16.2 Generic Smart Pointers

    +

    35.3.16.2 Generic Smart Pointers

    In certain C++ programs, it is common to use classes that @@ -1542,7 +1545,7 @@ method. For example:

    irb(main):004:0> f = p.__deref__() # Returns underlying Foo *
    -

    38.3.17 Cross-Language Polymorphism

    +

    35.3.17 Cross-Language Polymorphism

    SWIG's Ruby module supports cross-language polymorphism @@ -1551,7 +1554,7 @@ module. Rather than duplicate the information presented in the 38.3.17.1 Exception Unrolling +

    35.3.17.1 Exception Unrolling

    Whenever a C++ director class routes one of its virtual @@ -1574,7 +1577,7 @@ method is "wrapped" using the rb_rescue2() function from Ruby's C API. If any Ruby exception is raised, it will be caught here and a C++ exception is raised in its place.

    -

    38.4 Naming

    +

    35.4 Naming

    Ruby has several common naming conventions. Constants are @@ -1612,7 +1615,7 @@ generated by SWIG, it is turned off by default in SWIG 1.3.28. However, it is planned to become the default option in future releases.

    -

    38.4.1 Defining Aliases

    +

    35.4.1 Defining Aliases

    It's a fairly common practice in the Ruby built-ins and @@ -1682,7 +1685,7 @@ matching rules used for other kinds of features apply (see the chapter on "Customization Features") for more details).

    -

    38.4.2 Predicate Methods

    +

    35.4.2 Predicate Methods

    Ruby methods that return a boolean value and end in a @@ -1731,7 +1734,7 @@ using SWIG's "features" mechanism and so the same name matching rules used for other kinds of features apply (see the chapter on "Customization Features") for more details).

    -

    38.4.3 Bang Methods

    +

    35.4.3 Bang Methods

    Ruby methods that modify an object in-place and end in an @@ -1763,7 +1766,7 @@ using SWIG's "features" mechanism and so the same name matching rules used for other kinds of features apply (see the chapter on "Customization Features") for more details).

    -

    38.4.4 Getters and Setters

    +

    35.4.4 Getters and Setters

    Often times a C++ library will expose properties through @@ -1798,7 +1801,7 @@ irb(main):003:0> puts foo.value %rename("value=") Foo::setValue(int value); -

    38.5 Input and output parameters

    +

    35.5 Input and output parameters

    A common problem in some C programs is handling parameters @@ -1937,10 +1940,10 @@ void get_dimensions(Matrix *m, int *rows, int*columns);

    r, c = Example.get_dimensions(m)
    -

    38.6 Exception handling

    +

    35.6 Exception handling

    -

    38.6.1 Using the %exception directive

    +

    35.6.1 Using the %exception directive

    The SWIG %exception directive can be @@ -2049,7 +2052,7 @@ methods and functions named getitem and setitem. limited to C++ exception handling. See the chapter on Customization Features for more examples.

    -

    38.6.2 Handling Ruby Blocks

    +

    35.6.2 Handling Ruby Blocks

    One of the highlights of Ruby and most of its standard library @@ -2116,7 +2119,7 @@ a special in typemap, like:

    For more information on typemaps, see Typemaps.

    -

    38.6.3 Raising exceptions

    +

    35.6.3 Raising exceptions

    There are three ways to raise exceptions from C++ code to @@ -2273,7 +2276,7 @@ function. The first argument passed to rb_raise() is the exception type. You can raise a custom exception type or one of the built-in Ruby exception types.

    -

    38.6.4 Exception classes

    +

    35.6.4 Exception classes

    Starting with SWIG 1.3.28, the Ruby module supports the %exceptionclass @@ -2310,7 +2313,7 @@ end

    For another example look at swig/Examples/ruby/exception_class.

    -

    38.7 Typemaps

    +

    35.7 Typemaps

    This section describes how you can modify SWIG's default @@ -2325,7 +2328,7 @@ a required part of using SWIG---the default wrapping behavior is enough in most cases. Typemaps are only used if you want to change some aspect of the primitive C-Ruby interface.

    -

    38.7.1 What is a typemap?

    +

    35.7.1 What is a typemap?

    A typemap is nothing more than a code generation rule that is @@ -2482,7 +2485,7 @@ to be used as follows (notice how the length parameter is omitted):

    2 -

    38.7.2 Typemap scope

    +

    35.7.2 Typemap scope

    Once defined, a typemap remains in effect for all of the @@ -2528,7 +2531,7 @@ where the class itself is defined. For example:

    }; -

    38.7.3 Copying a typemap

    +

    35.7.3 Copying a typemap

    A typemap is copied by using assignment. For example:

    @@ -2570,7 +2573,7 @@ rules as for %apply (char *buf, int len) { (char *buffer, int size) }; // Multiple arguments -

    38.7.4 Deleting a typemap

    +

    35.7.4 Deleting a typemap

    A typemap can be deleted by simply defining no code. For @@ -2595,7 +2598,7 @@ defined by typemaps, clearing a fundamental type like int will make that type unusable unless you also define a new set of typemaps immediately after the clear operation.

    -

    38.7.5 Placement of typemaps

    +

    35.7.5 Placement of typemaps

    Typemap declarations can be declared in the global scope, @@ -2666,13 +2669,13 @@ In this example, this is done using the class declaration class string .

    -

    38.7.6 Ruby typemaps

    +

    35.7.6 Ruby typemaps

    The following list details all of the typemap methods that can be used by the Ruby module:

    -

    38.7.6.1 "in" typemap

    +

    35.7.6.1 "in" typemap

    Converts Ruby objects to input @@ -2739,7 +2742,7 @@ arguments to be specified. For example:

    At this time, only zero or one arguments may be converted.

    -

    38.7.6.2 "typecheck" typemap

    +

    35.7.6.2 "typecheck" typemap

    The "typecheck" typemap is used to support overloaded @@ -2761,7 +2764,7 @@ program uses overloaded methods, you should also define a collection of "typecheck" typemaps. More details about this follow in a later section on "Typemaps and Overloading."

    -

    38.7.6.3 "out" typemap

    +

    35.7.6.3 "out" typemap

    Converts return value of a C function @@ -2812,7 +2815,7 @@ version of the C datatype matched by the typemap. -

    38.7.6.4 "arginit" typemap

    +

    35.7.6.4 "arginit" typemap

    The "arginit" typemap is used to set the initial value of a @@ -2827,7 +2830,7 @@ applications. For example:

    } -

    38.7.6.5 "default" typemap

    +

    35.7.6.5 "default" typemap

    The "default" typemap is used to turn an argument into a @@ -2852,7 +2855,7 @@ arguments that follow must have default values. See the 38.7.6.6 "check" typemap +

    35.7.6.6 "check" typemap

    The "check" typemap is used to supply value checking code @@ -2867,7 +2870,7 @@ arguments have been converted. For example:

    } -

    38.7.6.7 "argout" typemap

    +

    35.7.6.7 "argout" typemap

    The "argout" typemap is used to return values from arguments. @@ -2921,7 +2924,7 @@ some function like SWIG_Ruby_AppendOutput.

    See the typemaps.i library for examples.

    -

    38.7.6.8 "freearg" typemap

    +

    35.7.6.8 "freearg" typemap

    The "freearg" typemap is used to cleanup argument data. It is @@ -2948,7 +2951,7 @@ This code is also placed into a special variable $cleanup that may be used in other typemaps whenever a wrapper function needs to abort prematurely.

    -

    38.7.6.9 "newfree" typemap

    +

    35.7.6.9 "newfree" typemap

    The "newfree" typemap is used in conjunction with the %newobject @@ -2972,7 +2975,7 @@ string *foo();

    See Object ownership and %newobject for further details.

    -

    38.7.6.10 "memberin" typemap

    +

    35.7.6.10 "memberin" typemap

    The "memberin" typemap is used to copy data from an @@ -2990,21 +2993,21 @@ example:

    already provides a default implementation for arrays, strings, and other objects.

    -

    38.7.6.11 "varin" typemap

    +

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

    -

    38.7.6.12 "varout" typemap

    +

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

    -

    38.7.6.13 "throws" typemap

    +

    35.7.6.13 "throws" typemap

    The "throws" typemap is only used when SWIG parses a C++ @@ -3045,7 +3048,7 @@ 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.

    -

    38.7.6.14 directorin typemap

    +

    35.7.6.14 directorin typemap

    Converts C++ objects in director @@ -3104,7 +3107,7 @@ referring to the class itself. -

    38.7.6.15 directorout typemap

    +

    35.7.6.15 directorout typemap

    Converts Ruby objects in director @@ -3177,7 +3180,7 @@ exception.

    -

    38.7.6.16 directorargout typemap

    +

    35.7.6.16 directorargout typemap

    Output argument processing in director @@ -3235,19 +3238,19 @@ referring to the instance of the class itself -

    38.7.6.17 ret typemap

    +

    35.7.6.17 ret typemap

    Cleanup of function return values

    -

    38.7.6.18 globalin typemap

    +

    35.7.6.18 globalin typemap

    Setting of C global variables

    -

    38.7.7 Typemap variables

    +

    35.7.7 Typemap variables

    @@ -3297,7 +3300,7 @@ so that their values can be properly assigned.

    The Ruby name of the wrapper function being created.
    -

    38.7.8 Useful Functions

    +

    35.7.8 Useful Functions

    When you write a typemap, you usually have to work directly @@ -3312,7 +3315,7 @@ stick to the swig functions instead of the native Ruby functions. That should help you avoid having to rewrite a lot of typemaps across multiple languages.

    -

    38.7.8.1 C Datatypes to Ruby Objects

    +

    35.7.8.1 C Datatypes to Ruby Objects

    @@ -3354,11 +3357,11 @@ SWIG_From_float(float)
    -

    38.7.8.2 Ruby Objects to C Datatypes

    +

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

    +versions do not, but return a status value to indicate success (SWIG_OK). While more awkward to use, this allows you to write typemaps that report more helpful error messages, like:

    @@ -3422,7 +3425,7 @@ versions do not, but return a status value to indicate success (SWIG_OK
     
     
    -

    38.7.8.3 Macros for VALUE

    +

    35.7.8.3 Macros for VALUE

    RSTRING_LEN(str)

    @@ -3445,7 +3448,7 @@ versions do not, but return a status value to indicate success (SWIG_OK
    pointer to array storage
    -

    38.7.8.4 Exceptions

    +

    35.7.8.4 Exceptions

    void rb_raise(VALUE exception, const char *fmt, @@ -3524,7 +3527,7 @@ message to standard error if Ruby was invoked with the -w flag. The given format string fmt and remaining arguments are interpreted as with printf(). -

    38.7.8.5 Iterators

    +

    35.7.8.5 Iterators

    void rb_iter_break()

    @@ -3570,14 +3573,14 @@ VALUE), VALUE value)

    Equivalent to Ruby's throw.
    -

    38.7.9 Typemap Examples

    +

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

    -

    38.7.10 Converting a Ruby array to a char **

    +

    35.7.10 Converting a Ruby array to a char **

    A common problem in many C programs is the processing of @@ -3642,7 +3645,7 @@ array. Since dynamic memory allocation is used to allocate memory for the array, the "freearg" typemap is used to later release this memory after the execution of the C function.

    -

    38.7.11 Collecting arguments in a hash

    +

    35.7.11 Collecting arguments in a hash

    Ruby's solution to the "keyword arguments" capability of some @@ -3719,7 +3722,7 @@ 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));
    +    $1 = NUM2INT(rb_funcall($input, rb_intern("size"), 0, Qnil));
     }
    @@ -3732,7 +3735,7 @@ 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));
    +    $1 = NUM2INT(rb_funcall($input, rb_intern("size"), 0, Qnil));
         $2 = NULL;
         $3 = NULL;
         if ($1 > 0) {
    @@ -3751,13 +3754,13 @@ 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));
    +    $1 = NUM2INT(rb_funcall($input, rb_intern("size"), 0, Qnil));
         $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);
    +      keys_arr = rb_funcall($input, rb_intern("keys"), 0, Qnil);
           for (i = 0; i < $1; i++) {
           }
         }
    @@ -3773,13 +3776,13 @@ 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));
    +    $1 = NUM2INT(rb_funcall($input, rb_intern("size"), 0, Qnil));
         $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);
    +      keys_arr = rb_funcall($input, rb_intern("keys"), 0, Qnil);
           for (i = 0; i < $1; i++) {
             key = rb_ary_entry(keys_arr, i);
             val = rb_hash_aref($input, key);
    @@ -3796,13 +3799,13 @@ 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));
    +    $1 = NUM2INT(rb_funcall($input, rb_intern("size"), 0, Qnil));
         $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);
    +      keys_arr = rb_funcall($input, rb_intern("keys"), 0, Qnil);
           for (i = 0; i < $1; i++) {
             key = rb_ary_entry(keys_arr, i);
             val = rb_hash_aref($input, key);
    @@ -3820,13 +3823,13 @@ 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));
    +  $1 = NUM2INT(rb_funcall($input, rb_intern("size"), 0, Qnil));
       $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);
    +    keys_arr = rb_funcall($input, rb_intern("keys"), 0, Qnil);
         for (i = 0; i < $1; i++) {
           key = rb_ary_entry(keys_arr, i);
           val = rb_hash_aref($input, key);
    @@ -3856,7 +3859,7 @@ memory leak. Fortunately, this typemap is a lot easier to write: 

    program that uses the extension, can be found in the Examples/ruby/hashargs directory of the SWIG distribution.

    -

    38.7.12 Pointer handling

    +

    35.7.12 Pointer handling

    Occasionally, it might be necessary to convert pointer values @@ -3915,7 +3918,7 @@ For example:

    }
    -

    38.7.12.1 Ruby Datatype Wrapping

    +

    35.7.12.1 Ruby Datatype Wrapping

    VALUE Data_Wrap_Struct(VALUE class, void @@ -3942,7 +3945,7 @@ as above. type c-type from the data object obj and assigns that pointer to ptr. -

    38.7.13 Example: STL Vector to Ruby Array

    +

    35.7.13 Example: STL Vector to Ruby Array

    Another use for macros and type maps is to create a Ruby array @@ -4034,7 +4037,7 @@ STL with ruby, you are advised to use the standard swig STL library, which does much more than this. Refer to the section called the C++ Standard Template Library. -

    38.8 Docstring Features

    +

    35.8 Docstring Features

    @@ -4068,7 +4071,7 @@ generate ri documentation from a c wrap file, you could do:

    $ rdoc -r file_wrap.c
    -

    38.8.1 Module docstring

    +

    35.8.1 Module docstring

    @@ -4098,7 +4101,7 @@ layout of controls on a panel, etc. to be loaded from an XML file." %module(docstring=DOCSTRING) xrc

    -

    38.8.2 %feature("autodoc")

    +

    35.8.2 %feature("autodoc")

    Since SWIG does know everything about the function it wraps, @@ -4119,7 +4122,7 @@ several options for autodoc controlled by the value given to the feature, described below.

    -

    38.8.2.1 %feature("autodoc", "0")

    +

    35.8.2.1 %feature("autodoc", "0")

    @@ -4143,7 +4146,7 @@ Then Ruby code like this will be generated: ...

    -

    38.8.2.2 %feature("autodoc", "1")

    +

    35.8.2.2 %feature("autodoc", "1")

    @@ -4163,7 +4166,7 @@ this: ...

    -

    38.8.2.3 %feature("autodoc", "2")

    +

    35.8.2.3 %feature("autodoc", "2")

    @@ -4175,7 +4178,7 @@ parameter types with the "2" option will result in Ruby code like this:

    -

    38.8.2.4 %feature("autodoc", "3")

    +

    35.8.2.4 %feature("autodoc", "3")

    @@ -4196,7 +4199,7 @@ Parameters: bar - Bar -

    38.8.2.5 %feature("autodoc", "docstring")

    +

    35.8.2.5 %feature("autodoc", "docstring")

    @@ -4212,7 +4215,7 @@ generated string. For example: void GetPosition(int* OUTPUT, int* OUTPUT); -

    38.8.3 %feature("docstring")

    +

    35.8.3 %feature("docstring")

    @@ -4223,10 +4226,10 @@ docstring associated with classes, function or methods are output. If an item already has an autodoc string then it is combined with the docstring and they are output together.

    -

    38.9 Advanced Topics

    +

    35.9 Advanced Topics

    -

    38.9.1 Operator overloading

    +

    35.9.1 Operator overloading

    SWIG allows operator overloading with, by using the %extend @@ -4407,7 +4410,7 @@ separate method for handling inequality since Ruby parses the expression a != b as !(a == b).

    -

    38.9.2 Creating Multi-Module Packages

    +

    35.9.2 Creating Multi-Module Packages

    The chapter on Working @@ -4533,7 +4536,7 @@ irb(main):005:0> c.getX() 5.0 -

    38.9.3 Specifying Mixin Modules

    +

    35.9.3 Specifying Mixin Modules

    The Ruby language doesn't support multiple inheritance, but @@ -4600,7 +4603,7 @@ matching rules used for other kinds of features apply (see the chapter on "Customization Features") for more details).

    -

    38.10 Memory Management

    +

    35.10 Memory Management

    One of the most common issues in generating SWIG bindings for @@ -4623,7 +4626,7 @@ to C++ (or vice versa) depending on what function or methods are invoked. Clearly, developing a SWIG wrapper requires a thorough understanding of how the underlying library manages memory.

    -

    38.10.1 Mark and Sweep Garbage Collector

    +

    35.10.1 Mark and Sweep Garbage Collector

    Ruby uses a mark and sweep garbage collector. When the garbage @@ -4654,7 +4657,7 @@ any memory has been allocated in creating the underlying C struct or C++ struct, then a "free" function must be defined that deallocates this memory.

    -

    38.10.2 Object Ownership

    +

    35.10.2 Object Ownership

    As described above, memory management depends on clearly @@ -4799,7 +4802,7 @@ public:

    This code can be seen in swig/examples/ruby/tracking.

    -

    38.10.3 Object Tracking

    +

    35.10.3 Object Tracking

    The remaining parts of this section will use the class library @@ -5025,7 +5028,7 @@ However, if you implement your own free functions (see below) you may also have to call the SWIG_RubyRemoveTracking and RubyUnlinkObjects methods.

    -

    38.10.4 Mark Functions

    +

    35.10.4 Mark Functions

    With a bit more testing, we see that our class library still @@ -5154,7 +5157,7 @@ irb(main):016:0>

    This code can be seen in swig/examples/ruby/mark_function.

    -

    38.10.5 Free Functions

    +

    35.10.5 Free Functions

    By default, SWIG creates a "free" function that is called when @@ -5322,7 +5325,7 @@ been freed, and thus raises a runtime exception.

    This code can be seen in swig/examples/ruby/free_function.

    -

    38.10.6 Embedded Ruby and the C++ Stack

    +

    35.10.6 Embedded Ruby and the C++ Stack

    As has been said, the Ruby GC runs and marks objects before diff --git a/Doc/Manual/SWIG.html b/Doc/Manual/SWIG.html index c6dc1eef6..c54d117e0 100644 --- a/Doc/Manual/SWIG.html +++ b/Doc/Manual/SWIG.html @@ -88,7 +88,7 @@

    This chapter describes the basic operation of SWIG, the structure of its -input files, and how it handles standard ANSI C declarations. C++ support is +input files, and how it handles standard ISO C declarations. C++ support is described in the next chapter. However, C++ programmers should still read this chapter to understand the basics. Specific details about each target language are described in later @@ -103,71 +103,156 @@ To run SWIG, use the swig command with options and a filename like this

    -swig [ options ] filename
    +swig [ options ] filename
     

    where filename is a SWIG interface file or a C/C++ header file. -Below is a subset of options that can be used. +Full help can be seen by running swig -help. +Below is the common set of options that can be used. Additional options are also defined for each target language. A full list -can be obtained by typing swig -help or swig --<lang> -help for language <lang> specific options. +can be obtained by running swig +-<lang> -help for language <lang> specific options, +for example, swig -ruby -help for Ruby.

    --allegrocl            Generate ALLEGROCL wrappers
    --chicken              Generate CHICKEN wrappers
    --clisp                Generate CLISP wrappers
    --cffi                 Generate CFFI wrappers
    --csharp               Generate C# wrappers
    --d                    Generate D wrappers
    --go                   Generate Go wrappers
    --guile                Generate Guile wrappers
    --java                 Generate Java wrappers
    --javascript           Generate Javascript wrappers
    --lua                  Generate Lua wrappers
    --modula3              Generate Modula 3 wrappers
    --mzscheme             Generate Mzscheme wrappers
    --ocaml                Generate Ocaml wrappers
    --octave               Generate Octave wrappers
    --perl                 Generate Perl wrappers
    --php5                 Generate PHP5 wrappers
    --php7                 Generate PHP7 wrappers
    --pike                 Generate Pike wrappers
    --python               Generate Python wrappers
    --r                    Generate R (aka GNU S) wrappers
    --ruby                 Generate Ruby wrappers
    --scilab               Generate Scilab wrappers
    --sexp                 Generate Lisp S-Expressions wrappers
    --tcl                  Generate Tcl wrappers
    --uffi                 Generate Common Lisp / UFFI wrappers
    --xml                  Generate XML wrappers
    +Supported Target Language Options
    +     -csharp         - Generate C# wrappers
    +     -d              - Generate D wrappers
    +     -go             - Generate Go wrappers
    +     -guile          - Generate Guile wrappers
    +     -java           - Generate Java wrappers
    +     -javascript     - Generate Javascript wrappers
    +     -lua            - Generate Lua wrappers
    +     -octave         - Generate Octave wrappers
    +     -perl5          - Generate Perl 5 wrappers
    +     -php7           - Generate PHP 7 wrappers
    +     -python         - Generate Python wrappers
    +     -r              - Generate R (aka GNU S) wrappers
    +     -ruby           - Generate Ruby wrappers
    +     -scilab         - Generate Scilab wrappers
    +     -tcl8           - Generate Tcl 8 wrappers
    +     -xml            - Generate XML wrappers
     
    --c++                  Enable C++ processing
    --cppext ext           Change file extension of C++ generated files to ext
    -                      (default is cxx, except for PHP5 which uses cpp)
    --Dsymbol              Define a preprocessor symbol
    --Fmicrosoft           Display error/warning messages in Microsoft format
    --Fstandard            Display error/warning messages in commonly used format
    --help                 Display all options
    --Idir                 Add a directory to the file include path
    --lifile               Include SWIG library file <ifile>
    --module name          Set the name of the SWIG module
    --o outfile            Set name of C/C++ output file to <outfile>
    --oh headfile          Set name of C++ output header file for directors to <headfile>
    --outcurrentdir        Set default output dir to current dir instead of input file's path
    --outdir dir           Set language specific files output directory
    --pcreversion          Display PCRE version information
    --swiglib              Report location of SWIG library and exit
    --version              Display SWIG version number
    +Experimental Target Language Options
    +     -mzscheme       - Generate MzScheme/Racket wrappers
    +     -ocaml          - Generate OCaml wrappers
     
    +General Options
    +     -addextern      - Add extra extern declarations
    +     -c++            - Enable C++ processing
    +     -co <file>      - Check <file> out of the SWIG library
    +     -copyctor       - Automatically generate copy constructors wherever possible
    +     -cpperraswarn   - Treat the preprocessor #error statement as #warning (default)
    +     -cppext <ext>   - Change file extension of generated C++ files to <ext>
    +                       (default is cxx)
    +     -copyright      - Display copyright notices
    +     -debug-classes  - Display information about the classes found in the interface
    +     -debug-module <n>- Display module parse tree at stages 1-4, <n> is a csv list of stages
    +     -debug-symtabs  - Display symbol tables information
    +     -debug-symbols  - Display target language symbols in the symbol tables
    +     -debug-csymbols - Display C symbols in the symbol tables
    +     -debug-lsymbols - Display target language layer symbols
    +     -debug-tags     - Display information about the tags found in the interface
    +     -debug-template - Display information for debugging templates
    +     -debug-top <n>  - Display entire parse tree at stages 1-4, <n> is a csv list of stages
    +     -debug-typedef  - Display information about the types and typedefs in the interface
    +     -debug-typemap  - Display typemap debugging information
    +     -debug-tmsearch - Display typemap search debugging information
    +     -debug-tmused   - Display typemaps used debugging information
    +     -directors      - Turn on director mode for all the classes, mainly for testing
    +     -dirprot        - Turn on wrapping of protected members for director classes (default)
    +     -D<symbol>      - Define a symbol <symbol> (for conditional compilation)
    +     -E              - Preprocess only, does not generate wrapper code
    +     -external-runtime [file] - Export the SWIG runtime stack
    +     -fakeversion <v>- Make SWIG fake the program version number to <v>
    +     -fcompact       - Compile in compact mode
    +     -features <list>- Set global features, where <list> is a comma separated list of
    +                       features, eg -features directors,autodoc=1
    +                       If no explicit value is given to the feature, a default of 1 is used
    +     -fastdispatch   - Enable fast dispatch mode to produce faster overload dispatcher code
    +     -Fmicrosoft     - Display error/warning messages in Microsoft format
    +     -Fstandard      - Display error/warning messages in commonly used format
    +     -fvirtual       - Compile in virtual elimination mode
    +     -help           - Display help
    +     -I-             - Don't search the current directory
    +     -I<dir>         - Look for SWIG files in directory <dir>
    +     -ignoremissing  - Ignore missing include files
    +     -importall      - Follow all #include statements as imports
    +     -includeall     - Follow all #include statements
    +     -l<ifile>       - Include SWIG library file <ifile>
    +     -macroerrors    - Report errors inside macros
    +     -makedefault    - Create default constructors/destructors (the default)
    +     -M              - List all dependencies
    +     -MD             - Is equivalent to `-M -MF <file>', except `-E' is not implied
    +     -MF <file>      - Generate dependencies into <file> and continue generating wrappers
    +     -MM             - List dependencies, but omit files in SWIG library
    +     -MMD            - Like `-MD', but omit files in SWIG library
    +     -module <name>  - Set module name to <name>
    +     -MP             - Generate phony targets for all dependencies
    +     -MT <target>    - Set the target of the rule emitted by dependency generation
    +     -nocontract     - Turn off contract checking
    +     -nocpperraswarn - Do not treat the preprocessor #error statement as #warning
    +     -nodefault      - Do not generate default constructors nor default destructors
    +     -nodefaultctor  - Do not generate implicit default constructors
    +     -nodefaultdtor  - Do not generate implicit default destructors
    +     -nodirprot      - Do not wrap director protected members
    +     -noexcept       - Do not wrap exception specifiers
    +     -nofastdispatch - Disable fast dispatch mode (default)
    +     -nopreprocess   - Skip the preprocessor step
    +     -notemplatereduce - Disable reduction of the typedefs in templates
    +     -O              - Enable the optimization options:
    +                        -fastdispatch -fvirtual
    +     -o <outfile>    - Set name of C/C++ output file to <outfile>
    +     -oh <headfile>  - Set name of C++ output header file for directors to <headfile>
    +     -outcurrentdir  - Set default output dir to current dir instead of input file's path
    +     -outdir <dir>   - Set language specific files output directory to <dir>
    +     -pcreversion    - Display PCRE version information
    +     -small          - Compile in virtual elimination and compact mode
    +     -swiglib        - Report location of SWIG library and exit
    +     -templatereduce - Reduce all the typedefs in templates
    +     -v              - Run in verbose mode
    +     -version        - Display SWIG version number
    +     -Wall           - Remove all warning suppression, also implies -Wextra
    +     -Wallkw         - Enable keyword warnings for all the supported languages
    +     -Werror         - Treat warnings as errors
    +     -Wextra         - Adds the following additional warnings: 202,309,403,405,512,321,322
    +     -w<list>        - Suppress/add warning messages, eg -w401,+321 - see Warnings.html
    +     -xmlout <file>  - Write XML version of the parse tree to <file> after normal processing
     
    +

    +Arguments may also be passed in a command-line options file (also known as a +response file) which is useful if they exceed the system command line length +limit. To do this, put the arguments in a file, then provide the file name +prefixed with @ like so: +

    + +
    +swig @file
    +
    + +

    +The options read from the file are inserted in place of the file option. If the +file does not exist, or cannot be read, then the option will be treated +literally and not removed. +

    + +

    +Options in the file are separated by whitespace. A whitespace character may be +included in an option by surrounding the entire option in either single or +double quotes. Any character (including a backslash) may be included by +prefixing the character to be included with a backslash. The file may itself +contain additional @file options; any such options will be processed +recursively. +

    +

    5.1.1 Input format

    -As input, SWIG expects a file containing ANSI C/C++ declarations and +As input, SWIG expects a file containing ISO C/C++ declarations and special SWIG directives. More often than not, this is a special SWIG interface file which is usually denoted with a special .i or .swg suffix. In certain cases, SWIG can be used directly on @@ -185,7 +270,7 @@ The most common format of a SWIG interface is as follows: %{ #include "myheader.h" %} -// Now list ANSI C/C++ declarations +// Now list ISO C/C++ declarations int foo; int bar(int x); ... @@ -389,7 +474,7 @@ For example /* bar not wrapped unless foo has been defined and the declaration of bar within foo has already been parsed */ int foo::bar(int) { - ... whatever ... + ... whatever ... } @@ -741,6 +826,32 @@ However, for the same conservative reasons even a constant with a simple cast wi +

    +This logic can lead to false attempts at converting #define into %constant though. +For example the following case does not have any undefined symbols within the macro: +

    + +
    +
    +// For indicating pure virtual functions such as: virtual void f() PURE;
    +#define PURE = 0
    +
    +
    + +

    +A warning is issued: +

    + +
    +
    +pure.h:1: Warning 305: Bad constant value (ignored).
    +
    +
    + +

    +In such cases simply ignore the warning or suppress it using the normal warning suppression techniques. +

    +

    The use of constant expressions is allowed, but SWIG does not evaluate them. Rather, it passes them through to the output file and lets the C @@ -1043,14 +1154,14 @@ expect :

     # Copy a file 
     def filecopy(source, target):
    -  f1 = fopen(source, "r")
    -  f2 = fopen(target, "w")
    -  buffer = malloc(8192)
    -  nbytes = fread(buffer, 8192, 1, f1)
    -  while (nbytes > 0):
    -    fwrite(buffer, 8192, 1, f2)
    -          nbytes = fread(buffer, 8192, 1, f1)
    -  free(buffer)
    +    f1 = fopen(source, "r")
    +    f2 = fopen(target, "w")
    +    buffer = malloc(8192)
    +    nbytes = fread(buffer, 8192, 1, f1)
    +    while (nbytes > 0):
    +        fwrite(buffer, 8192, 1, f2)
    +            nbytes = fread(buffer, 8192, 1, f1)
    +    free(buffer)
     

    @@ -1236,9 +1347,9 @@ creating a wrapper equivalent to the following:

     double wrap_dot_product(Vector *a, Vector *b) {
    -    Vector x = *a;
    -    Vector y = *b;
    -    return dot_product(x, y);
    +  Vector x = *a;
    +  Vector y = *b;
    +  return dot_product(x, y);
     }
     
    @@ -1266,12 +1377,12 @@ pointers. As a result, SWIG creates a wrapper like this:
     Vector *wrap_cross_product(Vector *v1, Vector *v2) {
    -        Vector x = *v1;
    -        Vector y = *v2;
    -        Vector *result;
    -        result = (Vector *) malloc(sizeof(Vector));
    -        *(result) = cross(x, y);
    -        return result;
    +  Vector x = *v1;
    +  Vector y = *v2;
    +  Vector *result;
    +  result = (Vector *) malloc(sizeof(Vector));
    +  *(result) = cross(x, y);
    +  return result;
     }
     
    @@ -1280,10 +1391,10 @@ or if SWIG was run with the -c++ option:

     Vector *wrap_cross(Vector *v1, Vector *v2) {
    -        Vector x = *v1;
    -        Vector y = *v2;
    -        Vector *result = new Vector(cross(x, y)); // Uses default copy constructor
    -        return result;
    +  Vector x = *v1;
    +  Vector y = *v2;
    +  Vector *result = new Vector(cross(x, y)); // Uses default copy constructor
    +  return result;
     }
     
    @@ -1736,6 +1847,16 @@ already defined in the target scripting language. However, if you are careful about namespaces and your use of modules, you can usually avoid these problems.

    +

    +When wrapping C code, simple use of identifiers/symbols with %rename usually suffices. +When wrapping C++ code, simple use of simple identifiers/symbols with %rename might be too +limiting when using C++ features such as function overloading, default arguments, namespaces, template specialization etc. +If you are using the %rename directive and C++, make sure you read the +SWIG and C++ chapter and in particular the section on +Renaming and ambiguity resolution +for method overloading and default arguments. +

    +

    Closely related to %rename is the %ignore directive. %ignore instructs SWIG to ignore declarations that match a given identifier. For example: @@ -2078,7 +2199,7 @@ except those consisting of capital letters only:

    Finally, variants of %rename and %ignore directives can be used to help wrap C++ overloaded functions and methods or C++ methods which use default arguments. This is described in the -Ambiguity resolution and renaming section in the C++ chapter. +Renaming and ambiguity resolution section in the C++ chapter.

    @@ -2147,7 +2268,7 @@ used in Tcl as follows :

    -Although the ANSI C standard does not allow default arguments, default +Although the ISO C standard does not allow default arguments, default arguments specified in a SWIG interface work with both C and C++.

    @@ -2167,7 +2288,7 @@ in the C++ chapter for further details.

    Occasionally, a C library may include functions that expect to receive pointers to functions--possibly to serve as callbacks. SWIG -provides full support for function pointers provided that the callback +provides full support for function pointers when the callback functions are defined in C and not in the target language. For example, consider a function like this:

    @@ -2311,14 +2432,16 @@ And now, a final note about function pointer support. Although SWIG does not normally allow callback functions to be written in the target language, this can be accomplished with the use of typemaps and other advanced SWIG features. See the Typemaps chapter for more about typemaps -and individual target language chapters for more on callbacks and the 'director' feature. +and individual target language chapters for more on callbacks. +The 'director' feature can be used to make callbacks from C/C++ into the target language, +see Callbacks to the target language.

    5.5 Structures and unions

    -This section describes the behavior of SWIG when processing ANSI C structures and union declarations. Extensions to +This section describes the behavior of SWIG when processing ISO C structures and union declarations. Extensions to handle C++ are described in the next section.

    @@ -2368,10 +2491,10 @@ defined in the interface. For example:
     struct Vector *new_Vector() {
    -    return (Vector *) calloc(1, sizeof(struct Vector));
    +  return (Vector *) calloc(1, sizeof(struct Vector));
     }
     void delete_Vector(struct Vector *obj) {
    -    free(obj);
    +  free(obj);
     }
     
    @@ -2602,10 +2725,10 @@ like this:
     WORD Foo_w_get(Foo *f) {
    -    return f->w;
    +  return f->w;
     }
     void Foo_w_set(FOO *f, WORD value) {
    -    f->w = value;
    +  f->w = value;
     }
     
    @@ -2896,7 +3019,7 @@ instead of a method. To do this, you might write some code like this:
     // Add a new attribute to Vector
     %extend Vector {
    -    const double magnitude;
    +  const double magnitude;
     }
     // Now supply the implementation of the Vector_magnitude_get function
     %{
    @@ -3140,9 +3263,9 @@ output of SWIG is structured first.

    -When SWIG creates its output file, it is broken up into five sections +When SWIG creates its output C/C++ file, it is broken up into five sections corresponding to runtime code, headers, wrapper functions, and module -initialization code (in that order). +initialization code (in that order).

      @@ -3176,9 +3299,37 @@ the module upon loading.

      -Code is inserted into the appropriate code section by using one -of the code insertion directives listed below. The order of the sections in -the wrapper file is as shown: +The %insert directive enables inserting blocks of code into a given section of the generated code. +It can be used in one of two ways: +

      + +
      +
      +%insert("section") "filename"
      +%insert("section") %{ ... %}
      +
      +
      + +

      +The first will dump the contents of the file in the given filename into the named section. +The second inserts the code between the braces into the named section. +For example, the following adds code into the runtime section: +

      + +
      +
      +%insert("runtime") %{
      +  ... code in runtime section ...
      +%}
      +
      +
      + +

      +There are the 5 sections, however, some target languages add in additional sections and some of these result in code being generated into a target language file instead of the C/C++ wrapper file. +These are documented when available in the target language chapters. +Macros named after the code sections are available as additional directives and these macro directives are normally used instead of %insert. +For example, %runtime is used instead of %insert("runtime"). +The valid sections and order of the sections in the generated C/C++ wrapper file is as shown:

      @@ -3265,11 +3416,27 @@ Vector *new_Vector() { return (Vector *) malloc(sizeof(Vector)); } %} -

    -The %inline directive inserts all of the code that follows +This is the same as writing: +

    + +
    +%{
    +/* Create a new vector */
    +Vector *new_Vector() {
    +  return (Vector *) malloc(sizeof(Vector));
    +}
    +%}
    +
    +/* Create a new vector */
    +Vector *new_Vector() {
    +  return (Vector *) malloc(sizeof(Vector));
    +}
    +
    +

    +In other words, the %inline directive inserts all of the code that follows verbatim into the header portion of an interface file. The code is then parsed by both the SWIG preprocessor and parser. Thus, the above example creates a new command new_Vector using only one @@ -3277,6 +3444,11 @@ declaration. Since the code inside an %inline %{ ... %} block is given to both the C compiler and SWIG, it is illegal to include any SWIG directives inside a %{ ... %} block.

    + +

    +Note: The usual SWIG C preprocessor rules apply to code in %apply blocks when SWIG parses this code. For example, as mentioned earlier, SWIG's C Preprocessor does not follow #include directives by default. +

    +

    5.6.4 Initialization blocks

    @@ -3292,6 +3464,18 @@ initialization on module loading, you could write this: %} +

    +Please note that some language backends (e.g. C# or Java) don't have any +initialization function, hence you should define a global object performing +the necessary initialization for them instead: +

    + +
    +%init %{
    +  static struct MyInit { MyInit() { init_variables(); } } myInit;
    +%}
    +
    +

    5.7 An Interface Building Strategy

    @@ -3323,7 +3507,7 @@ interface to your program. SWIG's %include directive to process an entire C source/header file. -
  • Make sure everything in the interface file uses ANSI C/C++ syntax. +
  • Make sure everything in the interface file uses ISO C/C++ syntax.
  • Make sure all necessary `typedef' declarations and type-information is available in the interface file. diff --git a/Doc/Manual/SWIGPlus.html b/Doc/Manual/SWIGPlus.html index 6fe9c2909..0c259e393 100644 --- a/Doc/Manual/SWIGPlus.html +++ b/Doc/Manual/SWIGPlus.html @@ -31,7 +31,6 @@
  • Static members
  • Member data -
  • Default arguments
  • Protection
  • Enums and constants
  • Friends @@ -39,16 +38,27 @@
  • Pass and return by value
  • Inheritance
  • A brief discussion of multiple inheritance, pointers, and type checking -
  • Wrapping Overloaded Functions and Methods +
  • Default arguments +
  • Overloaded functions and methods -
  • Wrapping overloaded operators +
  • Overloaded operators
  • Class extension
  • Templates +
  • Namespaces @@ -70,9 +85,16 @@

    -This chapter describes SWIG's support for wrapping C++. As a prerequisite, +This chapter describes SWIG's support for wrapping C++. +It is mostly concerned about C++ as defined by the C++ 98 and 03 standards. +For additions to the original C++ standard, please read the +SWIG and C++11, +SWIG and C++14 and +SWIG and C++17 chapters. +SWIG and C++20 chapters. +As a prerequisite, you should first read the chapter SWIG Basics to see -how SWIG wraps ANSI C. Support for C++ builds upon ANSI C +how SWIG wraps ISO C. Support for C++ builds upon ISO C wrapping and that material will be useful in understanding this chapter.

    @@ -123,7 +145,7 @@ yourself in the foot. You will just have to be careful.

    To wrap C++, SWIG uses a layered approach to code generation. -At the lowest level, SWIG generates a collection of procedural ANSI-C style +At the lowest level, SWIG generates a collection of procedural ISO C style wrappers. These wrappers take care of basic type conversion, type checking, error handling, and other low-level details of the C++ binding. These wrappers are also sufficient to bind C++ into any target language @@ -346,8 +368,8 @@ public: class Spam { public: - Foo *value; - ... + Foo *value; + ... }; @@ -706,7 +728,7 @@ class Foo { protected: Foo(); // Not wrapped. public: - ... + ... }; @@ -726,7 +748,7 @@ public: class Grok : public Bar { public: - Grok(); // Not wrapped. No implementation of abstract spam(). + Grok(); // Not wrapped. No implementation of abstract spam(). }; @@ -777,9 +799,9 @@ the normal constructor function. For example, if you have this:

     class List {
     public:
    -    List();    
    -    List(const List &);      // Copy constructor
    -    ...
    +  List();    
    +  List(const List &);      // Copy constructor
    +  ...
     };
     
    @@ -803,7 +825,7 @@ through a special function like this:
     List *copy_List(List *f) {
    -    return new List(*f);
    +  return new List(*f);
     }
     
    @@ -832,7 +854,7 @@ However, copy constructor wrappers can be generated if using the copyctor @@ -851,9 +873,9 @@ could be wrapped, but they had to be renamed. For example:
     class Foo {
     public:
    -    Foo();
    +  Foo();
       %name(CopyFoo) Foo(const Foo &);
    -    ...
    +  ...
     };
     
    @@ -969,8 +991,8 @@ not primitive types, such as classes. For instance, if you had another class lik
     class Foo {
     public:
    -    List items;
    -    ...
    +  List items;
    +  ...
     
    @@ -982,10 +1004,10 @@ For example:
     List *Foo_items_get(Foo *self) {
    -    return &self->items;
    +  return &self->items;
     }
     void Foo_items_set(Foo *self, List *value) {
    -    self->items = *value;
    +  self->items = *value;
     }
     
    @@ -1007,10 +1029,10 @@ It is the naturalvar feature and can be used to effectively change the way acces
     const List &Foo_items_get(Foo *self) {
    -    return self->items;
    +  return self->items;
     }
     void Foo_items_set(Foo *self, const List &value) {
    -    self->items = value;
    +  self->items = value;
     }
     
    @@ -1094,113 +1116,7 @@ a few problems related to structure wrapping and some of SWIG's customization features.

    -

    6.7 Default arguments

    - - -

    -SWIG will wrap all types of functions that have default arguments. For example member functions: -

    - -
    -
    -class Foo {
    -public:
    -    void bar(int x, int y = 3, int z = 4);
    -};
    -
    -
    - -

    -SWIG handles default arguments by generating an extra overloaded method for each defaulted argument. -SWIG is effectively handling methods with default arguments as if it was wrapping the equivalent overloaded methods. -Thus for the example above, it is as if we had instead given the following to SWIG: -

    - -
    -
    -class Foo {
    -public:
    -    void bar(int x, int y, int z);
    -    void bar(int x, int y);
    -    void bar(int x);
    -};
    -
    -
    - -

    -The wrappers produced are exactly the same as if the above code was instead fed into SWIG. -Details of this are covered later in the Wrapping Overloaded Functions and Methods section. -This approach allows SWIG to wrap all possible default arguments, but can be verbose. -For example if a method has ten default arguments, then eleven wrapper methods are generated. -

    - -

    -Please see the Features and default arguments -section for more information on using %feature with functions with default arguments. -The Ambiguity resolution and renaming section -also deals with using %rename and %ignore on methods with default arguments. -If you are writing your own typemaps for types used in methods with default arguments, you may also need to write a typecheck typemap. -See the Typemaps and overloading section for details or otherwise -use the compactdefaultargs feature flag as mentioned below. -

    - -

    -Compatibility note: Versions of SWIG prior to SWIG-1.3.23 wrapped default arguments slightly differently. -Instead a single wrapper method was generated and the default values were copied into the C++ wrappers -so that the method being wrapped was then called with all the arguments specified. -If the size of the wrappers are a concern then this approach to wrapping methods with default arguments -can be re-activated by using the compactdefaultargs -feature flag. -

    - -
    -
    -%feature("compactdefaultargs") Foo::bar;
    -class Foo {
    -public:
    -    void bar(int x, int y = 3, int z = 4);
    -};
    -
    -
    - - -

    -This is great for reducing the size of the wrappers, but the caveat is it does not work for the statically typed languages, -such as C# and Java, -which don't have optional arguments in the language, -Another restriction of this feature is that it cannot handle default arguments that are not public. -The following example illustrates this: -

    - -
    -
    -class Foo {
    -private:
    -  static const int spam;
    -public:
    -  void bar(int x, int y = spam);   // Won't work with %feature("compactdefaultargs") -
    -                                   // private default value
    -};
    -
    -
    - -

    -This produces uncompilable wrapper code because default values in C++ are -evaluated in the same scope as the member function whereas SWIG -evaluates them in the scope of a wrapper function (meaning that the -values have to be public). -

    - -

    -The compactdefaultargs feature is automatically turned on when wrapping C code with default arguments. -Some target languages will also automatically turn on this feature -if the keyword arguments feature (kwargs) is specified for either C or C++ functions, and the target language supports kwargs, -the compactdefaultargs feature is also automatically turned on. -Keyword arguments are a language feature of some scripting languages, for example Ruby and Python. -SWIG is unable to support kwargs when wrapping overloaded methods, so the default approach cannot be used. -

    - -

    6.8 Protection

    +

    6.7 Protection

    @@ -1220,7 +1136,7 @@ until you explicitly give a `public:' declaration (This is the same convention used by C++).

    -

    6.9 Enums and constants

    +

    6.8 Enums and constants

    @@ -1250,7 +1166,7 @@ Swig_STOUT = Swig::STOUT Members declared as const are wrapped as read-only members and do not create constants.

    -

    6.10 Friends

    +

    6.9 Friends

    @@ -1278,7 +1194,7 @@ equivalent to one generated for the following declaration

     class Foo {
     public:
    -    ...
    +  ...
     };
     
     void blah(Foo *f);    
    @@ -1311,7 +1227,7 @@ namespace bar {
     and a wrapper for the method 'blah' will not be generated.
     

    -

    6.11 References and pointers

    +

    6.10 References and pointers

    @@ -1411,7 +1327,7 @@ templates and the STL. This was first added in SWIG-1.3.12.

    -

    6.12 Pass and return by value

    +

    6.11 Pass and return by value

    @@ -1485,8 +1401,8 @@ class A; %feature("valuewrapper") B; struct B { - B(); - // .... + B(); + // .... };

    @@ -1515,7 +1431,7 @@ classes that don't define a default constructor. It is not used for C++ pointers or references.

    -

    6.13 Inheritance

    +

    6.12 Inheritance

    @@ -1701,7 +1617,7 @@ functions for virtual members that are already defined in a base class.

    -

    6.14 A brief discussion of multiple inheritance, pointers, and type checking

    +

    6.13 A brief discussion of multiple inheritance, pointers, and type checking

    @@ -1833,7 +1749,113 @@ int y = B_function((B *) pB); In practice, the pointer is held as an integral number in the target language proxy class.

    -

    6.15 Wrapping Overloaded Functions and Methods

    +

    6.14 Default arguments

    + + +

    +SWIG will wrap all types of functions that have default arguments. For example member functions: +

    + +
    +
    +class Foo {
    +public:
    +  void bar(int x, int y = 3, int z = 4);
    +};
    +
    +
    + +

    +SWIG handles default arguments by generating an extra overloaded method for each defaulted argument. +SWIG is effectively handling methods with default arguments as if it was wrapping the equivalent overloaded methods. +Thus for the example above, it is as if we had instead given the following to SWIG: +

    + +
    +
    +class Foo {
    +public:
    +  void bar(int x, int y, int z);
    +  void bar(int x, int y);
    +  void bar(int x);
    +};
    +
    +
    + +

    +The wrappers produced are exactly the same as if the above code was instead fed into SWIG. +Details of this are covered in the next section Overloaded functions and methods. +This approach allows SWIG to wrap all possible default arguments, but can be verbose. +For example if a method has ten default arguments, then eleven wrapper methods are generated. +

    + +

    +Please see the Features and default arguments +section for more information on using %feature with functions with default arguments. +The Renaming and ambiguity resolution section +also deals with using %rename and %ignore on methods with default arguments. +If you are writing your own typemaps for types used in methods with default arguments, you may also need to write a typecheck typemap. +See the Typemaps and overloading section for details or otherwise +use the compactdefaultargs feature flag as mentioned below. +

    + +

    +Compatibility note: Versions of SWIG prior to SWIG-1.3.23 wrapped default arguments slightly differently. +Instead a single wrapper method was generated and the default values were copied into the C++ wrappers +so that the method being wrapped was then called with all the arguments specified. +If the size of the wrappers are a concern then this approach to wrapping methods with default arguments +can be re-activated by using the compactdefaultargs +feature flag. +

    + +
    +
    +%feature("compactdefaultargs") Foo::bar;
    +class Foo {
    +public:
    +  void bar(int x, int y = 3, int z = 4);
    +};
    +
    +
    + + +

    +This is great for reducing the size of the wrappers, but the caveat is it does not work for the statically typed languages, +such as C# and Java, +which don't have optional arguments in the language, +Another restriction of this feature is that it cannot handle default arguments that are not public. +The following example illustrates this: +

    + +
    +
    +class Foo {
    +private:
    +  static const int spam;
    +public:
    +  void bar(int x, int y = spam);   // Won't work with %feature("compactdefaultargs") -
    +                                   // private default value
    +};
    +
    +
    + +

    +This produces uncompilable wrapper code because default values in C++ are +evaluated in the same scope as the member function whereas SWIG +evaluates them in the scope of a wrapper function (meaning that the +values have to be public). +

    + +

    +The compactdefaultargs feature is automatically turned on when wrapping C code with default arguments. +Some target languages will also automatically turn on this feature +if the keyword arguments feature (kwargs) is specified for either C or C++ functions, and the target language supports kwargs, +the compactdefaultargs feature is also automatically turned on. +Keyword arguments are a language feature of some scripting languages, for example Ruby and Python. +SWIG is unable to support kwargs when wrapping overloaded methods, so the default approach cannot be used. +

    + +

    6.15 Overloaded functions and methods

    @@ -2021,7 +2043,7 @@ checked in the same order as they appear in this ranking. If you're still confused, don't worry about it---SWIG is probably doing the right thing.

    -

    6.15.2 Ambiguity in Overloading

    +

    6.15.2 Ambiguity in overloading

    @@ -2139,7 +2161,7 @@ it means that the target language module has not yet implemented support for ove functions and methods. The only way to fix the problem is to read the next section.

    -

    6.15.3 Ambiguity resolution and renaming

    +

    6.15.3 Renaming and ambiguity resolution

    @@ -2399,8 +2421,8 @@ the first renaming rule found on a depth-first traversal of the class hierarchy is used.

  • -
  • The name matching rules strictly follow member qualification rules. -For example, if you have a class like this:

    +
  • The name matching rules strictly follow member qualifier rules. +For example, if you have a class and member with a member that is const qualified like this:

    @@ -2424,7 +2446,7 @@ the declaration
     

    -will not apply as there is no unqualified member bar(). The following will apply as +will not apply as there is no unqualified member bar(). The following will apply the rename as the qualifier matches correctly:

    @@ -2434,6 +2456,26 @@ the qualifier matches correctly: +

    +Similarly for combinations of cv-qualifiers and ref-qualifiers, all the qualifiers must be specified to match correctly: +

    + +
    +
    +%rename(name) Jam::bar();          // will not match
    +%rename(name) Jam::bar() &;        // will not match
    +%rename(name) Jam::bar() const;    // will not match
    +%rename(name) Jam::bar() const &;  // ok, will match
    +
    +class Jam {
    +public:
    +  ...
    +  void bar() const &;
    +  ...
    +};
    +
    +
    +

    An often overlooked C++ feature is that classes can define two different overloaded members that differ only in their qualifiers, like this: @@ -2466,7 +2508,7 @@ For example we can give them separate names in the target language:

    Similarly, if you merely wanted to ignore one of the declarations, use %ignore -with the full qualification. For example, the following directive +with the full qualifier. For example, the following directive would tell SWIG to ignore the const version of bar() above:

    @@ -2532,8 +2574,7 @@ exactly matches the wrapped method:

    The C++ method can then be called from the target language with the new name no matter how many arguments are specified, for example: newbar(2, 2.0), newbar(2) or newbar(). -However, if the %rename does not contain the default arguments, it will only apply to the single equivalent target language overloaded method. -So if instead we have: +However, if the %rename does not contain the default arguments:

    @@ -2542,9 +2583,24 @@ So if instead we have:
    +

    +then only one of the three equivalent overloaded methods will be renamed and wrapped as if SWIG parsed: +

    + +
    +
    +void Spam::newbar(int i, double d);
    +void Spam::bar(int i);
    +void Spam::bar();
    +
    +
    +

    The C++ method must then be called from the target language with the new name newbar(2, 2.0) when both arguments are supplied or with the original name as bar(2) (one argument) or bar() (no arguments). +

    + +

    In fact it is possible to use %rename on the equivalent overloaded methods, to rename all the equivalent overloaded methods:

    @@ -2586,7 +2642,7 @@ As a general rule, statically typed languages like Java are able to provide more than dynamically typed languages like Perl, Python, Ruby, and Tcl.

    -

    6.16 Wrapping overloaded operators

    +

    6.16 Overloaded operators

    @@ -2779,7 +2835,7 @@ into two methods such that additional logic can be packed into the operations; C this[type key] { get { ... } set { ... }}, Python uses __getitem__ and __setitem__, etc. In C++ if the return type of operator[] is a reference and the method is const, it is often indicative of the setter, -and and the getter is usually a const function return an object by value. +and the getter is usually a const function return an object by value. In the absence of any hard and fast rules and the fact that there may be multiple index operators, it is up to the user to choose the getter and setter to use by using %rename as shown earlier.

    @@ -2936,63 +2992,76 @@ as vector<int>. The wrapper for foo() will accept either variant.

    +

    6.18.1 The %template directive

    + +

    -Starting with SWIG-1.3.7, simple C++ template declarations can also be -wrapped. SWIG-1.3.12 greatly expands upon the earlier implementation. Before discussing this any further, there are a few things -you need to know about template wrapping. First, a bare C++ template +There are a couple of important points about template wrapping. +First, a bare C++ template does not define any sort of runnable object-code for which SWIG can normally create a wrapper. Therefore, in order to wrap a template, you need to give SWIG information about a particular template -instantiation (e.g., vector<int>, +instantiation (e.g., vector<int>, array<double>, etc.). Second, an instantiation name such as vector<int> is generally not a valid identifier name in most target languages. Thus, you will need to give the -template instantiation a more suitable name such as intvector -when creating a wrapper. +template instantiation a more suitable name such as intvector.

    -To illustrate, consider the following template definition: +To illustrate, consider the following class template definition:

     template<class T> class List {
     private:
    -    T *data;
    -    int nitems;
    -    int maxitems;
    +  T *data;
    +  int nitems;
    +  int maxitems;
     public:
    -    List(int max) {
    -      data = new T [max];
    -      nitems = 0;
    -      maxitems = max;
    -    }
    -    ~List() {
    -      delete [] data;
    -    };
    -    void append(T obj) {
    -      if (nitems < maxitems) {
    -        data[nitems++] = obj;
    -      }
    -    }
    -    int length() {
    -      return nitems;
    -    }
    -    T get(int n) {
    -      return data[n];
    +  List(int max) {
    +    data = new T [max];
    +    nitems = 0;
    +    maxitems = max;
    +  }
    +  ~List() {
    +    delete [] data;
    +  };
    +  void append(T obj) {
    +    if (nitems < maxitems) {
    +      data[nitems++] = obj;
         }
    +  }
    +  int length() {
    +    return nitems;
    +  }
    +  T get(int n) {
    +    return data[n];
    +  }
     };
     

    -By itself, this template declaration is useless--SWIG simply ignores it -because it doesn't know how to generate any code until unless a definition of +By itself, this class template is useless--SWIG simply ignores it +because it doesn't know how to generate any code unless a definition of T is provided. +The %template directive is required to instantiate the template for use in a target language. +The directive requires an identifier name for use in the target language plus the template for instantiation. +The example below instantiates List<int> for use as a class named intList:

    +
    +
    +%template(intList) List<int>;
    +
    +
    +

    -One way to create wrappers for a specific template instantiation is to simply -provide an expanded version of the class directly like this: +The instantiation expands the template code as a C++ compiler would do and then makes it available +under the given identifier name. +Essentially it is the same as wrapping the following concept code where +the class template definition has T expanded to int +(note that this is not entirely valid syntax):

    @@ -3000,42 +3069,20 @@ provide an expanded version of the class directly like this: %rename(intList) List<int>; // Rename to a suitable identifier class List<int> { private: - int *data; - int nitems; - int maxitems; + int *data; + int nitems; + int maxitems; public: - List(int max); - ~List(); - void append(int obj); - int length(); - int get(int n); + List(int max); + ~List(); + void append(int obj); + int length(); + int get(int n); };
    -

    -The %rename directive is needed to give the template class an appropriate identifier -name in the target language (most languages would not recognize C++ template syntax as a valid -class name). The rest of the code is the same as what would appear in a normal -class definition. -

    - -

    -Since manual expansion of templates gets old in a hurry, the %template directive can -be used to create instantiations of a template class. Semantically, %template is -simply a shortcut---it expands template code in exactly the same way as shown above. Here -are some examples: -

    - -
    -
    -/* Instantiate a few different versions of the template */
    -%template(intList) List<int>;
    -%template(doubleList) List<double>;
    -
    -
    -

    The argument to %template() is the name of the instantiation in the target language. The name you choose should not conflict with @@ -3053,7 +3100,81 @@ typedef List<int> intList; // OK

    -SWIG can also generate wrappers for function templates using a similar technique. +The %template directive +must always appear after the definition of the template to be expanded, so the following will work: +

    + +
    +
    +template<class T> class List { ... };
    +%template(intList) List<int>;
    +
    +
    + +

    +but if %template is used before the template definition, such as: +

    + +
    +
    +%template(intList) List<int>;
    +template<class T> class List { ... };
    +
    +
    + +

    +SWIG will generate an error: +

    + +
    +
    +example.i:3: Error: Template 'List' undefined.
    +
    +
    + +

    +Since the type system knows how to handle typedef, it is +generally not necessary to instantiate different versions of a template +for typenames that are equivalent. For instance, consider this code: +

    + +
    +
    +%template(intList) List<int>;
    +typedef int Integer;
    +...
    +void foo(List<Integer> *x);
    +
    +
    + +

    +In this case, List<Integer> is exactly the same type as +List<int>. Any use of List<Integer> is mapped back to the +instantiation of List<int> created earlier. Therefore, it is +not necessary to instantiate a new class for the type Integer (doing so is +redundant and will simply result in code bloat). +

    + +

    +The template provided to %template for instantiation must be the actual template and not a typedef to a template. +

    + +
    +
    +typedef List<int> ListOfInt;
    +
    +%template(intList) List<int>; // ok
    +%template(intList) ListOfInt; // illegal - Syntax error
    +
    +
    + + +

    6.18.2 Function templates

    + + +

    +SWIG can also generate wrappers for function templates using a similar technique +to that shown above for class templates. For example:

    @@ -3073,6 +3194,28 @@ In this case, maxint and maxdouble become unique names for spe instantiations of the function.

    +

    +SWIG even supports overloaded templated functions. As usual the %template directive +is used to wrap templated functions. For example: +

    + +
    +
    +template<class T> void foo(T x) { };
    +template<class T> void foo(T x, T y) { };
    +
    +%template(foo) foo<int>;
    +
    +
    + +

    +This will generate two overloaded wrapper methods, the first will take a single integer as an argument +and the second will take two integer arguments. +

    + +

    6.18.3 Default template arguments

    + +

    The number of arguments supplied to %template should match that in the original template definition. Template default arguments are supported. For example: @@ -3110,28 +3253,8 @@ instantiation only once in order to reduce the potential for code bloat.

    -

    -Since the type system knows how to handle typedef, it is -generally not necessary to instantiate different versions of a template -for typenames that are equivalent. For instance, consider this code: -

    +

    6.18.4 Template base classes

    -
    -
    -%template(intList) vector<int>;
    -typedef int Integer;
    -...
    -void foo(vector<Integer> *x);
    -
    -
    - -

    -In this case, vector<Integer> is exactly the same type as -vector<int>. Any use of Vector<Integer> is mapped back to the -instantiation of vector<int> created earlier. Therefore, it is -not necessary to instantiate a new class for the type Integer (doing so is -redundant and will simply result in code bloat). -

    When a template is instantiated using %template, information @@ -3158,13 +3281,13 @@ nothing is known about List<int>, you will get a warning message

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

    -If a template class inherits from another template class, you need to +If a class template inherits from another class template, you need to make sure that base classes are instantiated before derived classes. For example:

    @@ -3235,6 +3358,9 @@ TEMPLATE_WRAP(PairStringInt, std::pair<string, int>) Note the use of a vararg macro for the type T. If this wasn't used, the comma in the templated type in the last example would not be possible.

    +

    6.18.5 Template specialization

    + +

    The SWIG template mechanism does support specialization. For instance, if you define a class like this, @@ -3244,15 +3370,15 @@ a class like this,

     template<> class List<int> {
     private:
    -    int *data;
    -    int nitems;
    -    int maxitems;
    +  int *data;
    +  int nitems;
    +  int maxitems;
     public:
    -    List(int max);
    -    ~List();
    -    void append(int obj);
    -    int length();
    -    int get(int n);
    +  List(int max);
    +  ~List();
    +  void append(int obj);
    +  int length();
    +  int get(int n);
     };
     
    @@ -3275,15 +3401,15 @@ code defines a template that is applied when the template argument is a pointer.
     template<class T> class List<T*> {
     private:
    -    T *data;
    -    int nitems;
    -    int maxitems;
    +  T *data;
    +  int nitems;
    +  int maxitems;
     public:
    -    List(int max);
    -    ~List();
    -    void append(int obj);
    -    int length();
    -    T get(int n);
    +  List(int max);
    +  ~List();
    +  void append(T obj);
    +  int length();
    +  T get(int n);
     };
     
    @@ -3322,10 +3448,13 @@ SWIG implements template argument deduction so that the following partial specia +

    6.18.6 Member templates

    + +

    -Member function templates are supported. The underlying principle is the same +Member templates are supported. The underlying principle is the same as for normal templates--SWIG can't create a wrapper unless you provide -more information about types. For example, a class with a member template might +more information about types. For example, a class with a member function template might look like this:

    @@ -3399,11 +3528,6 @@ methods to the Foo class.

    -

    -Note: because of the way that templates are handled, the %template directive -must always appear after the definition of the template to be expanded. -

    -

    Now, if your target language supports overloading, you can even try

    @@ -3424,7 +3548,7 @@ depending on the argument type.

    When used with members, the %template directive may be placed in another -template class. Here is a slightly perverse example: +class template. Here is a slightly perverse example:

    @@ -3475,7 +3599,7 @@ template<class T1, class T2> struct pair {

    This declaration is perfectly acceptable to SWIG, but the constructor template will be ignored unless you explicitly expand it. To do that, you could expand a few versions of the constructor -in the template class itself. For example: +in the class template itself. For example:

    @@ -3536,6 +3660,110 @@ constructor, that will dispatch the proper call depending on the argument type.

    +

    6.18.7 Scoping and templates

    + + +

    +The %template directive for a class template is the equivalent to an explicit instantiation +of a C++ class template. The scope for a valid %template instantiation is the same +as the scope required for a valid explicit instantiation of a C++ template. +A definition of the template for the explicit instantiation must be in scope +where the instantiation is declared and must not be enclosed within a different namespace. +

    + +

    +For example, a few %template instantiations and C++ explicit instantiations are shown below: +

    + +
    +
    +namespace N {
    +  template<typename T> class C {};
    +}
    +
    +// valid
    +%template(cin) N::C<int>;
    +template class N::C<int>;
    +
    +// valid
    +namespace N {
    +  %template(cin) C<int>;
    +  template class C<int>;
    +}
    +
    +// valid
    +using namespace N;
    +%template(cin) C<int>;
    +template class C<int>;
    +
    +// valid
    +using N::C;
    +%template(cin) C<int>;
    +template class C<int>;
    +
    +// ill-formed
    +namespace unrelated {
    +  using N::C;
    +  %template(cin) C<int>;
    +  template class C<int>;
    +}
    +
    +// ill-formed
    +namespace unrelated {
    +  using namespace N;
    +  %template(cin) C<int>;
    +  template class C<int>;
    +}
    +
    +// ill-formed
    +namespace unrelated {
    +  namespace N {
    +    %template(cin) C<int>;
    +    template class C<int>;
    +  }
    +}
    +
    +// ill-formed
    +namespace unrelated {
    +  %template(cin) N::C<int>;
    +  template class N::C<int>;
    +}
    +
    +
    + +

    +When the scope is incorrect, such as for the ill-formed examples above, an error occurs: +

    + +
    +
    +cpp_template_scope.i:34: Error: 'C' resolves to 'N::C' and was incorrectly instantiated
    +in scope 'unrelated' instead of within scope 'N'.
    +
    +
    + +

    +A note for the C++ standard geeks out there; a valid instantiation is one which conforms to +the C++03 standard as C++11 made a change to disallow using declarations and using directives to find a template. +

    + +
    +
    +// valid C++03, ill-formed C++11
    +using N::C;
    +template class C<int>;
    +
    +
    + +

    +Compatibility Note: Versions prior to SWIG-4.0.0 did not error out with incorrectly scoped +%template declarations, but this led to numerous subtle template scope problems. +

    + + +

    6.18.8 More on templates

    + +

    If all of this isn't quite enough and you really want to make someone's head explode, SWIG directives such as @@ -3568,7 +3796,7 @@ instantiation.

    -It is also possible to separate these declarations from the template class. For example: +It is also possible to separate these declarations from the class template. For example:

    @@ -3587,11 +3815,11 @@ It is also possible to separate these declarations from the template class. For ... template<class T> class List { - ... - public: - List() { } - T get(int index); - ... + ... + public: + List() { } + T get(int index); + ... };
    @@ -3609,30 +3837,48 @@ additional methods to a specific instantiation. For example: %template(intList) List<int>; %extend List<int> { - void blah() { - printf("Hey, I'm an List<int>!\n"); - } + void blah() { + printf("Hey, I'm an List<int>!\n"); + } };

    -SWIG even supports overloaded templated functions. As usual the %template directive -is used to wrap templated functions. For example: +It is even possible to extend a class via %extend with template methods, for example:

    -template<class T> void foo(T x) { };
    -template<class T> void foo(T x, T y) { };
    +%include <std_string.i>
     
    -%template(foo) foo<int>;
    +%inline %{
    +class ExtendMe {
    +public:
    +  template <typename T>
    +  T do_stuff_impl(int a, T b, double d) {
    +    return b;
    +  }
    +};
    +%}
    +
    +%extend ExtendMe {
    +  template<typename T>
    +  T do_overloaded_stuff(T b) {
    +    return $self->do_stuff_impl(0, b, 4.0);
    +  }
    +}
    +%template(do_overloaded_stuff) ExtendMe::do_overloaded_stuff<std::string>;
    +%template(do_overloaded_stuff) ExtendMe::do_overloaded_stuff<double>;
     

    -This will generate two overloaded wrapper methods, the first will take a single integer as an argument -and the second will take two integer arguments. +The wrapped ExtendMe class will then have two (overloaded) methods called do_overloaded_stuff. +

    + +

    +Compatibility Note: Extending a class with template methods was added in version 3.0.12

    @@ -3657,20 +3903,20 @@ For example:

     template <class T> class OuterTemplateClass {};
     
    -// The nested class OuterClass::InnerClass inherits from the template class
    +// The nested class OuterClass::InnerClass inherits from the class template
     // OuterTemplateClass<OuterClass::InnerStruct> and thus the template needs
     // to be expanded with %template before the OuterClass declaration.
     %template(OuterTemplateClass_OuterClass__InnerStruct)
    -    OuterTemplateClass<OuterClass::InnerStruct>
    +  OuterTemplateClass<OuterClass::InnerStruct>
     
     
     // Don't forget to use %feature("flatnested") for OuterClass::InnerStruct and
     // OuterClass::InnerClass if the target language doesn't support nested classes.
     class OuterClass {
    -    public:
    -        // Forward declarations:
    -        struct InnerStruct;
    -        class InnerClass;
    +  public:
    +    // Forward declarations:
    +    struct InnerStruct;
    +    class InnerClass;
     };
     
     struct OuterClass::InnerStruct {};
    @@ -3699,7 +3945,7 @@ introduced a new class name.  This name could then be used with other directives
     
     %template(vectori) vector<int>;
     %extend vectori {
    -    void somemethod() { }
    +  void somemethod() { }
     };
     
    @@ -3713,7 +3959,7 @@ as the class name. For example:
     %template(vectori) vector<int>;
     %extend vector<int> {
    -    void somemethod() { }
    +  void somemethod() { }
     };
     
    @@ -3878,6 +4124,8 @@ then SWIG simply creates three wrapper functions bar(), spam(), and blah() in the target language. SWIG does not prepend the names with a namespace prefix nor are the functions packaged in any kind of nested scope. +Note that the default handling of flattening all the namespace scopes in the target language +can be changed via the nspace feature.

    @@ -3972,7 +4220,7 @@ in a different namespace. For example:

     namespace foo {
    -    template<typename T> T max(T a, T b) { return a > b ? a : b; }
    +  template<typename T> T max(T a, T b) { return a > b ? a : b; }
     }
     
     using foo::max;
    @@ -3981,8 +4229,8 @@ using foo::max;
     %template(maxfloat) foo::max<float>;    // Okay (qualified name).
     
     namespace bar {
    -    using namespace foo;
    -    %template(maxdouble)  max<double>;    // Okay.
    +  using namespace foo;
    +  %template(maxdouble)  max<double>;    // Okay.
     }
     
    @@ -4003,7 +4251,7 @@ namespace foo { typedef int Integer; class bar { public: - ... + ... }; } @@ -4166,9 +4414,7 @@ namespace foo {

    Note: The flattening of namespaces is only intended to serve as a basic namespace implementation. -None of the target language modules are currently programmed -with any namespace awareness. In the future, language modules may or may not provide -more advanced namespace support. +More advanced handling of namespaces is discussed next.

    6.19.1 The nspace feature for namespaces

    @@ -4264,9 +4510,9 @@ In the example below, the generic template type is used to rename to bbb
    -%rename(bbb) Space::ABC::aaa(T t);                  // will match but with lower precedence than ccc
    +%rename(bbb) Space::ABC::aaa(T t);                     // will match but with lower precedence than ccc
     %rename(ccc) Space::ABC<Space::XYZ>::aaa(Space::XYZ t);// will match but with higher precedence
    -                                                             // than bbb
    +                                                       // than bbb
     
     namespace Space {
       class XYZ {};
    @@ -4344,9 +4590,9 @@ class Error { };
     
     class Foo {
     public:
    -    ...
    -    void blah() throw(Error);
    -    ...
    +  ...
    +  void blah() throw(Error);
    +  ...
     };
     
    @@ -4371,7 +4617,7 @@ except Error, e:

    Details of how to tailor code for handling the caught C++ exception and converting it into the target language's exception/error handling mechanism -is outlined in the "throws" typemap section. +is outlined in the "throws" typemap section.

    @@ -4388,7 +4634,7 @@ The next section details a way of simulating an exception specification or repla Exceptions are automatically handled for methods with an exception specification. Similar handling can be achieved for methods without exception specifications through the %catches feature. It is also possible to replace any declared exception specification using the %catches feature. -In fact, %catches uses the same "throws" typemaps that SWIG uses for exception specifications in handling exceptions. +In fact, %catches uses the same "throws" typemaps that SWIG uses for exception specifications in handling exceptions. The %catches feature must contain a list of possible types that can be thrown. For each type that is in the list, SWIG will generate a catch handler, in the same way that it would for types declared in the exception specification. Note that the list can also include the catch all specification "...". @@ -4408,10 +4654,10 @@ struct Error4 : EBase { }; class Foo { public: - ... - void bar(); - void blah() throw(Error1, Error2, Error3, Error4); - ... + ... + void bar(); + void blah() throw(Error1, Error2, Error3, Error4); + ... }; @@ -4487,7 +4733,7 @@ for member pointers.

    In some C++ programs, objects are often encapsulated by smart-pointers or proxy classes. This is sometimes done to implement automatic memory management (reference counting) or -persistence. Typically a smart-pointer is defined by a template class where +persistence. Typically a smart-pointer is defined by a class template where the -> operator has been overloaded. This class is then wrapped around some other class. For example:

    @@ -4496,21 +4742,21 @@ around some other class. For example:
     // Smart-pointer class
     template<class T> class SmartPtr {
    -    T *pointee;
    +  T *pointee;
     public:
    -    SmartPtr(T *p) : pointee(p) { ... }
    -    T *operator->() {
    -        return pointee;
    -    }
    -    ...
    +  SmartPtr(T *p) : pointee(p) { ... }
    +  T *operator->() {
    +    return pointee;
    +  }
    +  ...
     };
     
     // Ordinary class
     class Foo_Impl {
     public:
    -    int x;
    -    virtual void bar();
    -    ...
    +  int x;
    +  virtual void bar();
    +  ...
     };
     
     // Smart-pointer wrapper
    @@ -4518,13 +4764,13 @@ typedef SmartPtr<Foo_Impl> Foo;
     
     // Create smart pointer Foo
     Foo make_Foo() {
    -    return SmartPtr<Foo_Impl>(new Foo_Impl());
    +  return SmartPtr<Foo_Impl>(new Foo_Impl());
     }
     
     // Do something with smart pointer Foo
     void do_something(Foo f) {
    -    printf("x = %d\n", f->x);
    -    f->bar();
    +  printf("x = %d\n", f->x);
    +  f->bar();
     }
     
     // Call the wrapped smart pointer proxy class in the target language 'Foo'
    @@ -4623,13 +4869,13 @@ example, if you have this code

     class Foo {
     public:
    -    int x;
    +  int x;
     };
     
     class Bar {
     public:
    -    int x;       
    -    Foo *operator->();
    +  int x;       
    +  Foo *operator->();
     };
     
    @@ -4792,19 +5038,19 @@ For example:

    where the code passed to the "ref" and "unref" features will be -executed as needed whenever a new object is passed to python, or when -python tries to release the proxy object instance, respectively. +executed as needed whenever a new object is passed to Python, or when +Python tries to release the proxy object instance, respectively.

    -On the python side, the use of a reference counted object is no +On the Python side, the use of a reference counted object is no different to any other regular instance:

     def create_A():
    -    a = A()         # SWIG ref 'a' - new object is passed to python (count: 1)
    +    a = A()         # SWIG ref 'a' - new object is passed to Python (count: 1)
         b1 = B(a)       # C++ ref 'a (count: 2)
         if 1 + 1 == 2:
             b2 = B(a)   # C++ ref 'a' (count: 3)
    @@ -4832,8 +5078,8 @@ features:
     
     

    In other words, SWIG will not do anything special when a new object -is passed to python, and it will always 'delete' the underlying object when -python releases the proxy instance. +is passed to Python, and it will always 'delete' the underlying object when +Python releases the proxy instance.

    @@ -4878,19 +5124,19 @@ base classes. For example:

     class Foo {
     public:
    -      int  blah(int x);
    +  int  blah(int x);
     };
     
     class Bar {
     public:
    -      double blah(double x);
    +  double blah(double x);
     };
     
     class FooBar : public Foo, public Bar {
     public:
    -      using Foo::blah;  
    -      using Bar::blah;
    -      char *blah(const char *x);
    +  using Foo::blah;
    +  using Bar::blah;
    +  char *blah(const char *x);
     };
     
    @@ -4933,14 +5179,14 @@ you wrap this code in Python, the module works just like you would expect:
     class Foo {
     protected:
    -    int x;
    -    int blah(int x);
    +  int x;
    +  int blah(int x);
     };
     
     class Bar : public Foo {
     public:
    -    using Foo::x;       // Make x public
    -    using Foo::blah;    // Make blah public
    +  using Foo::x;       // Make x public
    +  using Foo::blah;    // Make blah public
     };
     
    @@ -4971,14 +5217,14 @@ correctly, you can always change the interface to the following: class FooBar : public Foo, public Bar { public: #ifndef SWIG - using Foo::blah; - using Bar::blah; + using Foo::blah; + using Bar::blah; #else - int blah(int x); // explicitly tell SWIG about other declarations - double blah(double x); + int blah(int x); // explicitly tell SWIG about other declarations + double blah(double x); #endif - char *blah(const char *x); + char *blah(const char *x); };
    @@ -5040,7 +5286,7 @@ normal classes.

    If the target language doesn't support nested classes directly, or the support is not implemented in the -language module (like for python currently), then the visible nested classes are moved to the same name +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: @@ -5151,7 +5397,152 @@ using another tool if maintaining constness is the most important part of your project.

    -

    6.29 Where to go for more information

    +

    6.29 Callbacks to the target language

    + + +

    +C/C++ function pointers are often used for callbacks and this is discussed in the +Pointers to functions and callbacks section. +The callback techniques described therein provide a way to control callbacks to a C/C++ function but not callbacks into the target language. +The techniques described below show how the director feature can be used to support callbacks from C/C++ to the target language. +

    + +

    6.29.1 Introduction to director classes

    + + +

    +The director feature enables the ability for a target language class to derive from a wrapped C++ class. +The target language can override virtual methods of a wrapped C++ class, thereby supporting cross-language polymorphism. +Code can 'call up' from C++ into the target language by simply calling a virtual method overridden in a derived class in the target language. +The wrapped C++ classes that have this ability are termed 'director' classes. +The director feature is documented individually in each target language and the reader should locate and read this to obtain a full understanding of directors. +

    + +

    6.29.2 Using directors and target language callbacks

    + + +

    +SWIG's primary goal is to make it possible to call C/C++ code from a target language, however, the director feature enables the reverse. +While there isn't simple direct support for calling target language code from C, the director feature makes this possible. +It does require some work and additional wrapper code to be provided by the user. +The additional code required must be C++ and not C code and hence may introduce a small dependency on C++ if using a pure C project. +In a nutshell, the user must create a C++ base class and turn it into a director class. +A virtual method in the director base class is required. +SWIG generates the code to call up into the target language when wrapping the director virtual method. +

    + +

    +Let's look at some details next. +Consider the same function pointer for a callback called binary_op from the +Pointers to functions and callbacks section. +For completeness, the code required for the module and director feature is also shown: +

    + +
    +%module(directors="1") example
    +
    +%{
    +int binary_op(int a, int b, int (*op)(int, int)) {
    +  return op(a, b);
    +}
    +%}
    +
    + +

    +The goal is to have a target language function that gets called by binary_op. +The target language function should have the equivalent signature as the C/C++ function pointer int (*op)(int, int). +As we are using directors, we need a C++ virtual method with this signature, so let's +define the C++ class and pure virtual method first and make it a director class via the +director feature: +

    + +
    +%feature("director") BinaryOp;
    +
    +%inline %{
    +struct BinaryOp {
    +  virtual int handle(int a, int b) = 0;
    +  virtual ~BinaryOp() {}
    +};
    +%}
    +
    + +

    +The following handler_helper function and binary_op_wrapper function completes the code needed in the +C++/SWIG layer. The binary_op_wrapper function is wrapped by SWIG and is very similar to the binary_op function, +however, it takes a pointer to the director base class BinaryOp instead of a C/C++ function pointer. +

    + +
    +%{
    +static BinaryOp *handler_ptr = NULL;
    +static int handler_helper(int a, int b) {
    +  // Make the call up to the target language when handler_ptr
    +  // is an instance of a target language director class
    +  return handler_ptr->handle(a, b);
    +}
    +// If desired, handler_ptr above could be changed to a thread-local variable in order to make thread-safe
    +%}
    +
    +%inline %{
    +int binary_op_wrapper(int a, int b, BinaryOp *handler) {
    +  handler_ptr = handler;
    +  int result = binary_op(a, b, &handler_helper);
    +  handler = NULL;
    +  return result;
    +}
    +%}
    +
    + +

    +On the target language side, we need to derive a class from BinaryOp and override the +handle method. In Python this could be as simple as: +

    + +
    +
    +import example
    +
    +# PythonBinaryOp class is defined and derived from C++ class BinaryOp
    +class PythonBinaryOp(example.BinaryOp):
    +
    +    # Define Python class 'constructor'
    +    def __init__(self):
    +        # Call C++ base class constructor
    +        example.BinaryOp.__init__(self)
    +
    +    # Override C++ method: virtual int handle(int a, int b) = 0;
    +    def handle(self, a, b):
    +        # Return the product
    +        return a * b
    +
    +
    + +

    +For this to work from Python, an instance of the PythonBinaryOp class is created +and then passed to binary_op_wrapper. The net result is the binary_op +function will in turn be called which will call handler_helper which will call +the virtual handle method, that is, the Python method handle in the PythonBinaryOp class. The result will be the product of 10 and 20 and make its way back to Python and hence +200 will be printed with the following code: +

    + +
    +
    +handler = PythonBinaryOp()
    +result = example.binary_op_wrapper(10, 20, handler)
    +print result
    +
    +
    + +

    +This has thus demonstrated a C/C++ function pointer calling back into a target language function. +The code could be made a little more user friendly by using %rename to provide the +original binary_op name from the target language instead of binary_op_wrapper. +A C++ functor base class and Python functor class +could also be used instead, but these are left as exercises for the reader. +

    + +

    6.30 Where to go for more information

    diff --git a/Doc/Manual/Scilab.html b/Doc/Manual/Scilab.html index 90bd8bb9a..5c4ef6269 100644 --- a/Doc/Manual/Scilab.html +++ b/Doc/Manual/Scilab.html @@ -9,7 +9,7 @@ -

    39 SWIG and Scilab

    +

    36 SWIG and Scilab

      @@ -39,7 +39,7 @@
  • Pointers
  • Structures @@ -88,11 +88,11 @@ This chapter explains how to use SWIG for Scilab. After this introduction, you s

    -

    39.1 Preliminaries

    +

    36.1 Preliminaries

    -SWIG for Scilab supports Linux. Other operating sytems haven't been tested. +SWIG for Scilab supports Linux. Other operating systems haven't been tested.

    @@ -105,7 +105,7 @@ SWIG for Scilab supports C language. C++ is partially supported. See 39.2 Running SWIG +

    36.2 Running SWIG

    @@ -121,15 +121,15 @@ In this example we bind from C a function and a global variable into Scilab. The double Foo = 3.0; int fact(int n) { - if (n < 0) { - return 0; - } - else if (n == 0) { - return 1; - } - else { - return n * fact(n-1); - } + if (n < 0) { + return 0; + } + else if (n == 0) { + return 1; + } + else { + return n * fact(n-1); + } } %} @@ -139,7 +139,7 @@ Note: a code in an %inline section is both parsed and wrapped by SWIG,

    -

    39.2.1 Generating the module

    +

    36.2.1 Generating the module

    @@ -182,7 +182,7 @@ The swig executable has several other command line options you can use.

    -

    39.2.2 Building the module

    +

    36.2.2 Building the module

    @@ -202,7 +202,7 @@ $ gcc -shared example_wrap.o -o libexample.so Note: we supposed in this example that the path to the Scilab include directory is /usr/local/include/scilab (which is the case in a Debian environment), this should be changed for another environment.

    -

    39.2.3 Loading the module

    +

    36.2.3 Loading the module

    @@ -226,7 +226,7 @@ Link done. which means that Scilab has successfully loaded the shared library. The module functions and other symbols are now available in Scilab.

    -

    39.2.4 Using the module

    +

    36.2.4 Using the module

    @@ -260,7 +260,7 @@ ans = Note: for conciseness, we assume in the subsequent Scilab code examples that the modules have been beforehand built and loaded in Scilab.

    -

    39.2.5 Scilab command line options

    +

    36.2.5 Scilab command line options

    @@ -304,6 +304,11 @@ The following table lists the Scilab specific command line options in addition t Generate the gateway XML with the given <gateway_id> + +-targetversion +Generate for Scilab target (major) version + +

    @@ -315,10 +320,10 @@ $ swig -scilab -help -

    39.3 A basic tour of C/C++ wrapping

    +

    36.3 A basic tour of C/C++ wrapping

    -

    39.3.1 Overview

    +

    36.3.1 Overview

    @@ -327,18 +332,22 @@ This means that functions, structs, classes, variables, etc... are interfaced th There are a few exceptions, such as constants and enumerations, which can be wrapped directly as Scilab variables.

    -

    39.3.2 Identifiers

    +

    36.3.2 Identifiers

    -In Scilab 5.x, identifier names are composed of 24 characters maximum (this limitation should disappear from Scilab 6.0 onwards). -
    Thus long function or variable names may be truncated and this can cause ambiguities. +In Scilab 5.x, identifier names are composed of 24 characters maximum (this limitation disappears from Scilab 6.0 onwards). +
    By default, variable, member, and function names longer than 24 characters are truncated, and a warning is produced for each truncation.

    -

    This happens especially when wrapping structs/classes, for which the wrapped function name is composed of the struct/class name and field names. +

    This can cause ambiguities, especially when wrapping structs/classes, for which the wrapped function name is composed of the struct/class name and field names. In these cases, the %rename directive can be used to choose a different Scilab name.

    -

    39.3.3 Functions

    +

    +Note: truncations can be disabled by specifying the target version 6 of Scilab in the targetversion argument (i.e. -targetversion 6). +

    + +

    36.3.3 Functions

    @@ -369,7 +378,7 @@ ans = 24. -

    39.3.3.1 Argument passing

    +

    36.3.3.1 Argument passing

    @@ -422,7 +431,7 @@ In Scilab, parameters are passed by value. The output (and inout) parameters are 7. -

    39.3.3.2 Multiple output arguments

    +

    36.3.3.2 Multiple output arguments

    @@ -471,7 +480,7 @@ int divide(int n, int d, int *OUTPUT, int *OUTPUT); -

    39.3.4 Global variables

    +

    36.3.4 Global variables

    @@ -540,10 +549,10 @@ It works the same:

    -

    39.3.5 Constants and enumerations

    +

    36.3.5 Constants and enumerations

    -

    39.3.5.1 Constants

    +

    36.3.5.1 Constants

    @@ -684,7 +693,7 @@ are mapped to Scilab variables, with the same name: 3.14 -

    39.3.5.2 Enumerations

    +

    36.3.5.2 Enumerations

    @@ -749,14 +758,14 @@ typedef enum { RED, BLUE, GREEN } color; -

    39.3.6 Pointers

    +

    36.3.6 Pointers

    Pointers are supported by SWIG. A pointer can be returned from a wrapped C/C++ function, stored in a Scilab variable, and used in input argument of another C/C++ function.

    -Also, thanks to the SWIG runtime which stores informations about types, pointer types are tracked between exchanges Scilab and the native code. Indeed pointer types are stored alongside the pointer adress. +Also, thanks to the SWIG runtime which stores information about types, pointer types are tracked between exchanges Scilab and the native code. Indeed pointer types are stored alongside the pointer address. A pointer is mapped to a Scilab structure (tlist), which contains as fields the pointer address and the pointer type (in fact a pointer to the type information structure in the SWIG runtime).
    Why a native pointer is not mapped to a Scilab pointer (type name: "pointer", type ID: 128) ? The big advantage of mapping to a tlist is that it exposes a new type for the pointer in Scilab, type which can be acessed in Scilab with the typeof function, and manipulated using the overloading mechanism. @@ -811,7 +820,7 @@ Note: the type name _p_FILE which means "pointer to FILE". The user of a pointer is responsible for freeing it or, like in the example, closing any resources associated with it (just as is required in a C program).

    -

    39.3.6.1 Utility functions

    +

    36.3.6.1 Utility functions

    @@ -852,7 +861,7 @@ ans = -

    39.3.6.2 Null pointers:

    +

    36.3.6.2 Null pointers:

    @@ -868,7 +877,7 @@ Using the previous SWIG_this() and SWIG_ptr(), it is possible -

    39.3.7 Structures

    +

    36.3.7 Structures

    @@ -887,8 +896,8 @@ Let's see it on an example of a struct with two members: %inline %{ typedef struct { - int x; - int arr[4]; + int x; + int arr[4]; } Foo; %} @@ -964,7 +973,7 @@ ans =

    -Note: the pointer to the struct works as described in Pointers. For example, the type of the struct pointer can be get with typeof, as following: +Note: the pointer to the struct works as described in Pointers. For example, the type of the struct pointer can be get with typeof, as following:

    @@ -977,7 +986,7 @@ Note: the pointer to the struct works as described in 39.3.8 C++ classes
    +

    36.3.8 C++ classes

    @@ -1028,7 +1037,7 @@ ans =

    -Note: like structs, class pointers are mapped as described in Pointers. Let's give an example which shows that each class pointer type is a new type in Scilab that can be used for example (through overloading) to implement a custom print for the Point class: +Note: like structs, class pointers are mapped as described in Pointers. Let's give an example which shows that each class pointer type is a new type in Scilab that can be used for example (through overloading) to implement a custom print for the Point class:

    @@ -1045,7 +1054,7 @@ Note: like structs, class pointers are mapped as described in 39.3.9 C++ inheritance
    +

    36.3.9 C++ inheritance

    @@ -1120,25 +1129,25 @@ But we can use either use the get_perimeter() function of the parent cl 18.84

    -

    39.3.10 C++ overloading

    +

    36.3.10 C++ overloading

    -As explained in 6.15 SWIG provides support for overloaded functions and constructors. +As explained in Overloaded functions and methods SWIG provides support for overloaded functions and constructors.

    -

    As SWIG knows pointer types, the overloading works also with pointer types, here is is an example with a function magnify overloaded for the previous classes Shape and Circle: +

    As SWIG knows pointer types, the overloading works also with pointer types, here is an example with a function magnify overloaded for the previous classes Shape and Circle:

     %module example
     
     void magnify(Square *square, double factor) {
    -    square->size *= factor;
    +  square->size *= factor;
     };
     
     void magnify(Circle *circle, double factor) {
    -    square->radius *= factor;
    +  square->radius *= factor;
     };
     
    @@ -1160,7 +1169,7 @@ void magnify(Circle *circle, double factor) { -

    39.3.11 Pointers, references, values, and arrays

    +

    36.3.11 Pointers, references, values, and arrays

    @@ -1218,7 +1227,7 @@ All these functions will return a pointer to an instance of Foo. As the function spam7 returns a value, new instance of Foo has to be allocated, and a pointer on this instance is returned.

    -

    39.3.12 C++ templates

    +

    36.3.12 C++ templates

    @@ -1277,7 +1286,7 @@ Then in Scilab: More details on template support can be found in the templates documentation.

    -

    39.3.13 C++ operators

    +

    36.3.13 C++ operators

    @@ -1330,7 +1339,7 @@ private: -

    39.3.14 C++ namespaces

    +

    36.3.14 C++ namespaces

    @@ -1408,7 +1417,7 @@ Note: the nspace feature is not supp

    -

    39.3.15 C++ exceptions

    +

    36.3.15 C++ exceptions

    @@ -1432,7 +1441,7 @@ void throw_exception() throw(char const *) {

     -->throw_exception()
       !--error 999
    -SWIG/Scilab: Exception (char const *) occured: Bye world !
    +SWIG/Scilab: Exception (char const *) occurred: Bye world !
     

    @@ -1449,7 +1458,7 @@ It can be used with the lasterror() function as following: --> lasterror() ans = - SWIG/Scilab: Exception (char const *) occured: Bye world ! + SWIG/Scilab: Exception (char const *) occurred: Bye world !

    @@ -1479,7 +1488,7 @@ void throw_stl_invalid_arg(int i) throw(std::invalid_argument) {

     --> throw_int();
                 !--error 999
    -SWIG/Scilab: Exception (int) occured: 12
    +SWIG/Scilab: Exception (int) occurred: 12
     
     -->throw_stl_invalid_arg(-1);
                               !--error 999
    @@ -1491,17 +1500,17 @@ More complex or custom exception types require specific exception typemaps to be
     See the SWIG C++ documentation for more details.
     

    -

    39.3.16 C++ STL

    +

    36.3.16 C++ STL

    The Standard Template Library (STL) is partially supported. See STL for more details.

    -

    39.4 Type mappings and libraries

    +

    36.4 Type mappings and libraries

    -

    39.4.1 Default primitive type mappings

    +

    36.4.1 Default primitive type mappings

    @@ -1552,7 +1561,7 @@ The default behaviour is for SWIG to generate code that will give a runtime erro -

    39.4.2 Arrays

    +

    36.4.2 Arrays

    @@ -1607,15 +1616,15 @@ void printArray(int values[], int len) { [ 0 1 2 3 ]

    -

    39.4.3 Pointer-to-pointers

    +

    36.4.3 Pointer-to-pointers

    -There are no specific typemaps for pointer-to-pointers, they are are mapped as pointers in Scilab. +There are no specific typemaps for pointer-to-pointers, they are mapped as pointers in Scilab.

    -Pointer-to-pointers are sometimes used to implement matrices in C. The following is a an example of this: +Pointer-to-pointers are sometimes used to implement matrices in C. The following is an example of this:

    @@ -1680,7 +1689,7 @@ void print_matrix(double **M, int nbRows, int nbCols) { -

    39.4.4 Matrices

    +

    36.4.4 Matrices

    @@ -1773,7 +1782,7 @@ The remarks made earlier for arrays also apply here:

  • There is no control while converting double values to integers, double values are truncated without any checking or warning.
  • -

    39.4.5 STL

    +

    36.4.5 STL

    @@ -1973,7 +1982,7 @@ ans = --> delete_PersonPtrSet(p); -

    39.5 Module initialization

    +

    36.5 Module initialization

    @@ -1997,7 +2006,7 @@ For example, to initialize the module example: --> example_Init(); -

    39.6 Building modes

    +

    36.6 Building modes

    @@ -2012,7 +2021,7 @@ To produce a dynamic module, when generating the wrapper, there are two possibil

  • the builder mode. In this mode, Scilab is responsible of building. -

    39.6.1 No-builder mode

    +

    36.6.1 No-builder mode

    @@ -2025,7 +2034,7 @@ This mode is the best option to use when you have to integrate the module build

    -

    39.6.2 Builder mode

    +

    36.6.2 Builder mode

    @@ -2053,7 +2062,7 @@ In this mode, the following SWIG options may be used to setup the build: Let's give an example how to build a module example, composed of two sources, and using a library dependency:

      -
    • the sources are baa1.c and baa2.c (and are stored in in the current directory)
    • +
    • the sources are baa1.c and baa2.c (and are stored in the current directory)
    • the library is libfoo in /opt/foo (headers stored in /opt/foo/include, and shared library in /opt/foo/lib)
    @@ -2065,14 +2074,14 @@ The command is: $ swig -scilab -builder -buildercflags -I/opt/foo/include -builderldflags "-L/opt/foo/lib -lfoo" -buildersources baa1.cxx, baa2.cxx example.i -

    39.7 Generated scripts

    +

    36.7 Generated scripts

    In this part we give some details about the generated Scilab scripts.

    -

    39.7.1 Builder script

    +

    36.7.1 Builder script

    @@ -2097,7 +2106,7 @@ ilib_build(ilib_name, table, files, libs);

  • table: two column string matrix containing a table of pairs of 'scilab function name', 'C function name'.
  • -

    39.7.2 Loader script

    +

    36.7.2 Loader script

    @@ -2136,7 +2145,7 @@ clear get_file_path; -

    39.8 Other resources

    +

    36.8 Other resources

    -

    Language Module Documentation

    +

    Supported Language Modules Documentation

    +

    Experimental Language Modules Documentation

    + + +

    Developer Documentation

    -

    11.12.1 Implementation

    +

    14.12.1 Implementation

    @@ -4298,7 +4412,7 @@ structures rather than creating new ones. These swig_module_info structures are chained together in a circularly linked list.

    -

    11.12.2 Usage

    +

    14.12.2 Usage

    This section covers how to use these functions from typemaps. To learn how to @@ -4394,7 +4508,7 @@ probably just look at the output of SWIG to get a better sense for how types are managed.

    -

    11.13 Typemaps and overloading

    +

    14.13 Typemaps and overloading

    @@ -4516,37 +4630,69 @@ To support dynamic dispatch, SWIG first defines a general purpose type hierarchy

     Symbolic Name                   Precedence Value
     ------------------------------  ------------------
    -SWIG_TYPECHECK_POINTER           0  
    -SWIG_TYPECHECK_VOIDPTR           10 
    -SWIG_TYPECHECK_BOOL              15 
    -SWIG_TYPECHECK_UINT8             20 
    -SWIG_TYPECHECK_INT8              25 
    -SWIG_TYPECHECK_UINT16            30 
    -SWIG_TYPECHECK_INT16             35 
    -SWIG_TYPECHECK_UINT32            40 
    -SWIG_TYPECHECK_INT32             45 
    -SWIG_TYPECHECK_UINT64            50 
    -SWIG_TYPECHECK_INT64             55 
    -SWIG_TYPECHECK_UINT128           60 
    -SWIG_TYPECHECK_INT128            65 
    -SWIG_TYPECHECK_INTEGER           70 
    -SWIG_TYPECHECK_FLOAT             80 
    -SWIG_TYPECHECK_DOUBLE            90 
    -SWIG_TYPECHECK_COMPLEX           100 
    -SWIG_TYPECHECK_UNICHAR           110 
    -SWIG_TYPECHECK_UNISTRING         120 
    -SWIG_TYPECHECK_CHAR              130 
    -SWIG_TYPECHECK_STRING            140 
    -SWIG_TYPECHECK_BOOL_ARRAY        1015 
    -SWIG_TYPECHECK_INT8_ARRAY        1025 
    -SWIG_TYPECHECK_INT16_ARRAY       1035 
    -SWIG_TYPECHECK_INT32_ARRAY       1045 
    -SWIG_TYPECHECK_INT64_ARRAY       1055 
    -SWIG_TYPECHECK_INT128_ARRAY      1065 
    -SWIG_TYPECHECK_FLOAT_ARRAY       1080 
    -SWIG_TYPECHECK_DOUBLE_ARRAY      1090 
    -SWIG_TYPECHECK_CHAR_ARRAY        1130 
    -SWIG_TYPECHECK_STRING_ARRAY      1140 
    +SWIG_TYPECHECK_POINTER           0
    +SWIG_TYPECHECK_ITERATOR          5
    +SWIG_TYPECHECK_VOIDPTR           10
    +SWIG_TYPECHECK_BOOL              15
    +SWIG_TYPECHECK_UINT8             20
    +SWIG_TYPECHECK_INT8              25
    +SWIG_TYPECHECK_UINT16            30
    +SWIG_TYPECHECK_INT16             35
    +SWIG_TYPECHECK_UINT32            40
    +SWIG_TYPECHECK_INT32             45
    +SWIG_TYPECHECK_SIZE              47
    +SWIG_TYPECHECK_PTRDIFF           48
    +SWIG_TYPECHECK_UINT64            50
    +SWIG_TYPECHECK_INT64             55
    +SWIG_TYPECHECK_UINT128           60
    +SWIG_TYPECHECK_INT128            65
    +SWIG_TYPECHECK_INTEGER           70
    +SWIG_TYPECHECK_FLOAT             80
    +SWIG_TYPECHECK_DOUBLE            90
    +SWIG_TYPECHECK_CPLXFLT           95
    +SWIG_TYPECHECK_CPLXDBL           100
    +SWIG_TYPECHECK_COMPLEX           105
    +SWIG_TYPECHECK_UNICHAR           110
    +SWIG_TYPECHECK_STDUNISTRING      115
    +SWIG_TYPECHECK_UNISTRING         120
    +SWIG_TYPECHECK_CHAR              130
    +SWIG_TYPECHECK_STDSTRING         135
    +SWIG_TYPECHECK_STRING            140
    +SWIG_TYPECHECK_PAIR              150
    +SWIG_TYPECHECK_STDARRAY          155
    +SWIG_TYPECHECK_VECTOR            160
    +SWIG_TYPECHECK_DEQUE             170
    +SWIG_TYPECHECK_LIST              180
    +SWIG_TYPECHECK_SET               190
    +SWIG_TYPECHECK_MULTISET          200
    +SWIG_TYPECHECK_MAP               210
    +SWIG_TYPECHECK_MULTIMAP          220
    +SWIG_TYPECHECK_STACK             230
    +SWIG_TYPECHECK_QUEUE             240
    +SWIG_TYPECHECK_BOOL_ARRAY        1015
    +SWIG_TYPECHECK_INT8_ARRAY        1025
    +SWIG_TYPECHECK_INT16_ARRAY       1035
    +SWIG_TYPECHECK_INT32_ARRAY       1045
    +SWIG_TYPECHECK_INT64_ARRAY       1055
    +SWIG_TYPECHECK_INT128_ARRAY      1065
    +SWIG_TYPECHECK_FLOAT_ARRAY       1080
    +SWIG_TYPECHECK_DOUBLE_ARRAY      1090
    +SWIG_TYPECHECK_CHAR_ARRAY        1130
    +SWIG_TYPECHECK_STRING_ARRAY      1140
    +SWIG_TYPECHECK_OBJECT_ARRAY      1150
    +SWIG_TYPECHECK_BOOL_PTR          2015
    +SWIG_TYPECHECK_UINT8_PTR         2020
    +SWIG_TYPECHECK_INT8_PTR          2025
    +SWIG_TYPECHECK_UINT16_PTR        2030
    +SWIG_TYPECHECK_INT16_PTR         2035
    +SWIG_TYPECHECK_UINT32_PTR        2040
    +SWIG_TYPECHECK_INT32_PTR         2045
    +SWIG_TYPECHECK_UINT64_PTR        2050
    +SWIG_TYPECHECK_INT64_PTR         2055
    +SWIG_TYPECHECK_FLOAT_PTR         2080
    +SWIG_TYPECHECK_DOUBLE_PTR        2090
    +SWIG_TYPECHECK_CHAR_PTR          2130
    +SWIG_TYPECHECK_SWIGOBJECT        5000
     
    @@ -4671,7 +4817,8 @@ then the type is given a precedence higher than any other known precedence level
    -example.i:18: Warning 467: Overloaded method foo(int) not supported (incomplete type checking rule - no precedence level in typecheck typemap for 'int').
    +example.i:18: Warning 467: Overloaded method foo(int) not supported (incomplete type
    +checking rule - no precedence level in typecheck typemap for 'int').
     
    @@ -4696,17 +4843,119 @@ simply check the type of the first array element and use that to dispatch to the Subsequent "in" typemaps would then perform more extensive type-checking. -
  • Make sure you read the section on overloading in the "SWIG and C++" chapter. +
  • Make sure you read the section on overloading in the SWIG and C++ chapter.
  • -

    11.14 More about %apply and %clear

    +

    14.13.1 SWIG_TYPECHECK_POINTER precedence level and the typecheck typemap

    + + +

    +When it comes to overloading of a particular type passed by value, pointer or reference (const and non-const), +a C++ compiler can disambiguate which overloaded function to call. +However, SWIG effectively treats these as pointers in the target language and thus as equivalent types. +For example, consider: +

    + +
    +
    +class X { ... };
    +void m(X const &c); // equivalent: void m(X *c);
    +void m(X &r);       // equivalent: void m(X *r);
    +void m(X *p);       // equivalent: void m(X *p);
    +
    +
    + +

    +These cannot be disambiguated in the target languages and so SWIG will choose the first method and ignore the subsequent two methods. +The scripting languages do this by using the overload dispatch mechanism described earlier and warnings indicate this: +

    + +
    +
    +example.i:6: Warning 509: Overloaded method m(X &) effectively ignored,
    +example.i:5: Warning 509: as it is shadowed by m(X const &).
    +example.i:7: Warning 509: Overloaded method m(X *) effectively ignored,
    +example.i:5: Warning 509: as it is shadowed by m(X const &).
    +
    +
    + +

    +The statically typed languages like Java and C# automatically ignore all but the first equivalent overloaded methods with warnings: +

    + +
    +
    +example.i:6: Warning 516: Overloaded method m(X &) ignored,
    +example.i:5: Warning 516: using m(X const &) instead.
    +example.i:7: Warning 516: Overloaded method m(X *) ignored,
    +example.i:5: Warning 516: using m(X const &) instead.
    +
    +
    + +

    +You can select the overloaded method you would like to wrap by ignoring the other two with %ignore or rename two of them with %rename +and this will of course remove the warnings too. +The problem of ambiguity is also discussed in the C++ chapter on overloading. +

    + +

    +So how does this work with respect to typemaps? +The typemaps SWIG provides to handle overloading for these three methods are from the SWIGTYPE family. +As discussed earlier, in Default typemap matching rules, +the SWIGTYPE & typemaps are used for references and SWIGTYPE * typemaps are used for pointers. +SWIG uses the special SWIG_TYPECHECK_POINTER (0) precedence level to handle these types in the "typecheck" typemap: +

    + +
    +
    +%typemap(typecheck, precedence=SWIG_TYPECHECK_POINTER) SWIGTYPE & "..."
    +%typemap(typecheck, precedence=SWIG_TYPECHECK_POINTER) SWIGTYPE * "..."
    +
    +
    + +

    +When the SWIGTYPE "typecheck" typemaps use the SWIG_TYPECHECK_POINTER precedence level, +SWIG converts the type to a pointer equivalent type and then uses the equivalent type to detect if it can be disambiguated in an overloaded method in the target language. +In our example above, the equivalent types for X const &, X & and X * are all X *. +As they are the same, they cannot be disambiguated and so just the first overloaded method is chosen. +

    + +

    +The automatic conversion to equivalent types and subsequent type comparison is triggered via the use of the special SWIG_TYPECHECK_POINTER precedence level +and works for types passed by value, pointer and reference. +Alas, there are more ways to overload a method that also need handling. +C++ smart pointers are such a type which can be disambiguated by a C++ compiler but not automatically by SWIG. +SWIG does not automatically know that a smart pointer has an equivalent type, but it can be told manually. +Just specify the 'equivalent' attribute in the "typecheck" typemap with a pointer to the underlying type. +

    + +
    +
    +%typemap(typecheck, precedence=SWIG_TYPECHECK_POINTER, equivalent="X *") MySmartPtr<X> " ... "
    +
    +void m(X &r);            // equivalent: void m(X *r);
    +void m(MySmartPtr<X> s); // equivalent: void m(X *s);
    +
    +
    + +

    +Now SWIG will detect the two types are equivalent and generate valid code by wrapping just the first overloaded method. +You can of course choose which method to wrap by ignoring one of them with %ignore. +Otherwise both can be wrapped by removing the overloading name ambiguity by renaming one of them with %rename. +

    + +

    +The 'equivalent' attribute is used in the implementation for the shared_ptr smart pointer library. +

    + +

    14.14 More about %apply and %clear

    In order to implement certain kinds of program behavior, it is sometimes necessary to -write sets of typemaps. For example, to support output arguments, one often writes -a set of typemaps like this: +write a family of typemap methods. For example, to support output arguments, one often writes +a family of typemaps like this:

    @@ -4722,7 +4971,7 @@ a set of typemaps like this:

    To make it easier to apply the typemap to different argument types and names, the %apply directive -performs a copy of all typemaps from one type to another. For example, if you specify this, +performs a copy of all typemaps from a source type to one or more set of target types. For example, if you specify this,

    @@ -4732,12 +4981,14 @@ performs a copy of all typemaps from one type to another. For example, if you s

    -then all of the int *OUTPUT typemaps are copied to int *retvalue and int32 *output. +then all of the int *OUTPUT (source) typemap methods are copied to int *retvalue and int32 *output (the targets).

    -However, there is a subtle aspect of %apply that needs more description. Namely, %apply does not -overwrite a typemap rule if it is already defined for the target datatype. This behavior allows you to do two things: +However, there is a subtle aspect of %apply that needs clarification. +Namely, if a target contains a typemap method that the source does not, +the target typemap method remains in place and unchanged. +This behavior allows you to do two things:

      @@ -4745,7 +4996,7 @@ overwrite a typemap rule if it is already defined for the target datatype. Thi %apply to incorporate the remaining pieces. -
    • Sets of different typemaps can be applied to the same datatype using repeated %apply directives. +
    • Different typemaps can be applied to the same datatype using repeated %apply directives.
    @@ -4767,6 +5018,10 @@ For example: } } +%typemap(arginit) int *invalue %{ + $1 = NULL; +%} + ... %apply int *INPUT { int *invalue }; %apply int *POSITIVE { int *invalue }; @@ -4774,9 +5029,11 @@ For example:

    -Since %apply does not overwrite or replace any existing rules, the only way to reset behavior is to -use the %clear directive. %clear removes all typemap rules defined for a specific datatype. For -example: +In this example, neither of the two %apply directives will overwrite / delete the "arginit" typemap as neither has an "arginit" typemap. +The result is a family of three relevant typemaps for int *invalue. +Since %apply does not overwrite / delete any existing rules, the only way to reset behavior is to +delete them, such as with the %clear directive. +For example:

    @@ -4785,8 +5042,19 @@ example:
    +

    +will delete the typemaps for all the typemap methods; namely "in", "check" and "arginit". Alternatively delete each one individually: +

    -

    11.15 Passing data between typemaps

    +
    +
    +%typemap(in) int *invalue;
    +%typemap(check) int *invalue;
    +%typemap(arginit) int *invalue;
    +
    +
    + +

    14.15 Passing data between typemaps

    @@ -4823,7 +5091,7 @@ sure that the typemaps sharing information have exactly the same types and names

    -

    11.16 C++ "this" pointer

    +

    14.16 C++ "this" pointer

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

    -

    11.17 Where to go for more information?

    +

    14.17 Where to go for more information?

    diff --git a/Doc/Manual/Varargs.html b/Doc/Manual/Varargs.html index fb58ee39a..620f2e5a0 100644 --- a/Doc/Manual/Varargs.html +++ b/Doc/Manual/Varargs.html @@ -7,7 +7,7 @@ -

    14 Variable Length Arguments

    +

    17 Variable Length Arguments

      @@ -43,7 +43,7 @@ added in SWIG-1.3.12. Most other wrapper generation tools have wisely chosen to avoid this issue.

      -

      14.1 Introduction

      +

      17.1 Introduction

      @@ -140,7 +140,7 @@ List make_list(const char *s, ...) {

    -

    14.2 The Problem

    +

    17.2 The Problem

    @@ -233,7 +233,7 @@ can also support real varargs wrapping (with stack-frame manipulation) if you are willing to get hands dirty. Keep reading.

    -

    14.3 Default varargs support

    +

    17.3 Default varargs support

    @@ -302,7 +302,7 @@ Read on for further solutions.

    -

    14.4 Argument replacement using %varargs

    +

    17.4 Argument replacement using %varargs

    @@ -413,7 +413,7 @@ mixed argument types such as printf(). Providing general purpose wrappers to such functions presents special problems (covered shortly).

    -

    14.5 Varargs and typemaps

    +

    17.5 Varargs and typemaps

    @@ -423,8 +423,8 @@ Variable length arguments may be used in typemap specifications. For example:

     %typemap(in) (...) {
    -    // Get variable length arguments (somehow)
    -    ...
    +  // Get variable length arguments (somehow)
    +  ...
     }
     
     %typemap(in) (const char *fmt, ...) {
    @@ -529,8 +529,11 @@ like this:
           SWIG_fail;
         }
         pystr = PyUnicode_AsUTF8String(pyobj);
    +    if (!pystr) {
    +      SWIG_fail;
    +    }
         str = strdup(PyBytes_AsString(pystr));
    -    Py_XDECREF(pystr);
    +    Py_DECREF(pystr);
     %#else  
         if (!PyString_Check(pyobj)) {
           PyErr_SetString(PyExc_ValueError, "Expected a string");
    @@ -590,7 +593,7 @@ really want to elevate your guru status and increase your job
     security, continue to the next section.
     

    -

    14.6 Varargs wrapping with libffi

    +

    17.6 Varargs wrapping with libffi

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

    -

    14.7 Wrapping of va_list

    +

    17.7 Wrapping of va_list

    @@ -896,7 +899,7 @@ int my_vprintf(const char *fmt, ...) {

    -

    14.8 C++ Issues

    +

    17.8 C++ Issues

    @@ -965,7 +968,7 @@ design or to provide an alternative interface using a helper function than it is fully general wrapper to a varargs C++ member function.

    -

    14.9 Discussion

    +

    17.9 Discussion

    diff --git a/Doc/Manual/Warnings.html b/Doc/Manual/Warnings.html index e7b291f21..0cf2a1066 100644 --- a/Doc/Manual/Warnings.html +++ b/Doc/Manual/Warnings.html @@ -7,7 +7,7 @@ -

    15 Warning Messages

    +

    19 Warning Messages

    @@ -36,7 +37,7 @@ -

    15.1 Introduction

    +

    19.1 Introduction

    @@ -56,7 +57,7 @@ where the generated wrapper code will probably compile, but it may not work like you expect.

    -

    15.2 Warning message suppression

    +

    19.2 Warning message suppression

    @@ -148,7 +149,7 @@ your interface. Ignore the warning messages at your own peril.

    -

    15.3 Enabling extra warnings

    +

    19.3 Enabling extra warnings

    @@ -221,7 +222,7 @@ that is, any warnings suppressed or added in %warnfilter, #pragma S or the -w option.

    -

    15.4 Issuing a warning message

    +

    19.4 Issuing a warning message

    @@ -275,7 +276,7 @@ example.i:24: Warning 901: You are really going to regret this usage of blah * s

    -

    15.5 Symbolic symbols

    +

    19.5 Symbolic symbols

    @@ -310,7 +311,7 @@ or -

    15.6 Commentary

    +

    19.6 Commentary

    @@ -327,7 +328,7 @@ no obvious recovery. There is no mechanism for suppressing error messages.

    -

    15.7 Warnings as errors

    +

    19.7 Warnings as errors

    @@ -336,7 +337,7 @@ option. This will cause SWIG to exit with a non successful exit code if a warning is encountered.

    -

    15.8 Message output format

    +

    19.8 Message output format

    @@ -355,10 +356,10 @@ $ swig -python -Fmicrosoft example.i example.i(4) : Syntax error in input(1). -

    15.9 Warning number reference

    +

    19.9 Warning number reference

    -

    15.9.1 Deprecated features (100-199)

    +

    19.9.1 Deprecated features (100-199)

      @@ -386,7 +387,7 @@ example.i(4) : Syntax error in input(1).
    • 126. The 'nestedworkaround' feature is deprecated.
    -

    15.9.2 Preprocessor (200-299)

    +

    19.9.2 Preprocessor (200-299)

      @@ -398,7 +399,7 @@ example.i(4) : Syntax error in input(1).
    • 206. Unexpected tokens after #directive directive.
    -

    15.9.3 C/C++ Parser (300-399)

    +

    19.9.3 C/C++ Parser (300-399)

      @@ -475,7 +476,7 @@ example.i(4) : Syntax error in input(1).
    • 395. operator delete[] ignored.
    -

    15.9.4 Types and typemaps (400-499)

    +

    19.9.4 Types and typemaps (400-499)