diff --git a/.gitignore b/.gitignore
index 4001af7c3..e94087e29 100644
--- a/.gitignore
+++ b/.gitignore
@@ -85,8 +85,6 @@ swig.spec
# Build Artifacts
.dirstamp
CCache/ccache-swig
-CCache/ccache-swig.1
-CCache/web/ccache-man.html
Lib/swigwarn.swg
Source/CParse/parser.c
Source/CParse/parser.h
@@ -96,7 +94,6 @@ swig
Tools/javascript/javascript
# Generated documentation
-Doc/Manual/CCache.html
Doc/Manual/SWIGDocumentation.html
Doc/Manual/SWIGDocumentation.pdf
Doc/Manual/*.book
@@ -114,6 +111,10 @@ Examples/scratch
# Out of source tree build directories
*build*/
+# errors test-suite
+Examples/test-suite/errors/*.newerr
+Examples/test-suite/errors/*.py
+
########## Language specific files ##########
# C#
@@ -132,6 +133,14 @@ Examples/d/**/runme
# Go
*.[5689]
*_gc.c
+Examples/test-suite/go/*.go
+!Examples/test-suite/go/*runme.go
+Examples/test-suite/go/*runme
+Examples/test-suite/go/gopath
+Examples/test-suite/go/testdir
+Examples/go/*/gopath
+Examples/go/*/example.go
+Examples/go/*/runme
# Guile
Examples/guile/*/my-guile
diff --git a/.travis.yml b/.travis.yml
index 9b47611b7..bc1324dad 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -2,133 +2,316 @@ language: cpp
matrix:
include:
- compiler: clang
+ os: linux
+ env: SWIGLANG=
+ sudo: required
+ dist: trusty
+ - compiler: gcc
+ os: linux
env: SWIGLANG=
- compiler: gcc
+ os: linux
env: SWIGLANG=
+ sudo: required
+ dist: trusty
+ - os: linux
+ env: SWIGLANG= SWIG_CC=gcc-5 SWIG_CXX=g++-5 CPP11=1
+ sudo: required
+ dist: trusty
+ - os: linux
+ env: SWIGLANG= SWIG_CC=gcc-6 SWIG_CXX=g++-6
+ sudo: required
+ dist: trusty
- compiler: gcc
- env: SWIGLANG= GCC5=1 CPP11=1
- - compiler: gcc
- env: SWIGLANG= GCC5=1 CPP14=1
- - compiler: gcc
+ os: linux
env: SWIGLANG=csharp
+ sudo: required
+ dist: trusty
- compiler: gcc
+ os: linux
env: SWIGLANG=d
+ sudo: required
+ dist: trusty
- compiler: gcc
+ os: linux
env: SWIGLANG=go
+ sudo: required
+ dist: trusty
- compiler: gcc
+ os: linux
+ env: SWIGLANG=go VER=1.5
+ sudo: required
+ dist: trusty
+ - compiler: gcc
+ os: linux
env: SWIGLANG=guile
+ sudo: required
+ dist: trusty
- compiler: gcc
+ os: linux
env: SWIGLANG=java
+ sudo: required
+ dist: trusty
- compiler: gcc
+ os: linux
env: SWIGLANG=javascript ENGINE=node
- compiler: gcc
+ os: linux
env: SWIGLANG=javascript ENGINE=jsc
+ sudo: required
+ dist: trusty
- compiler: gcc
+ os: linux
env: SWIGLANG=javascript ENGINE=v8
+ sudo: required
+ dist: trusty
- compiler: gcc
+ os: linux
env: SWIGLANG=lua
+ sudo: required
+ dist: trusty
- compiler: gcc
- env: SWIGLANG=octave SWIGJOBS=-j3 # 3.2
+ os: linux
+ env: SWIGLANG=lua VER=5.3
+ sudo: required
+ dist: trusty
- compiler: gcc
- env: SWIGLANG=octave SWIGJOBS=-j3 VER=3.8
+ os: linux
+ env: SWIGLANG=octave SWIGJOBS=-j2 # 3.2
- compiler: gcc
- env: SWIGLANG=octave SWIGJOBS=-j3 VER=4.0
+ 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
- env: SWIGLANG=php
+ 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
- env: SWIGLANG=python PY3=3 # 3.2
+ 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
- env: SWIGLANG=python SWIG_FEATURES=-builtin PY3=3
+ 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
- env: SWIGLANG=ruby
+ 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
- env: SWIGLANG=csharp GCC5=1 CPP11=1
- - compiler: gcc
- env: SWIGLANG=java GCC5=1 CPP11=1
- - compiler: gcc
- env: SWIGLANG=python GCC5=1 CPP11=1
+ 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
- compiler: gcc
+ os: linux
env: SWIGLANG=ocaml
- # Occasional gcc internal compiler error
- - compiler: gcc
- env: SWIGLANG=octave SWIGJOBS=-j3 VER=3.8
- # Occasional gcc internal compiler error
- - compiler: gcc
- env: SWIGLANG=octave SWIGJOBS=-j3 VER=4.0
- # Not quite working yet
- - compiler: gcc
- env: SWIGLANG=python SWIG_FEATURES=-classic
+ sudo: required
+ dist: trusty
# Not quite working yet
- compiler: gcc
+ os: linux
env: SWIGLANG=python SWIG_FEATURES=-O
- # Runtime errors in Travis environment
+ sudo: required
+ dist: trusty
+ # php7.1 nearly working
- compiler: gcc
- env: SWIGLANG=r
+ os: linux
+ env: SWIGLANG=php VER=7.1
+ sudo: required
+ dist: trusty
before_install:
- date -u
- uname -a
- - lsb_release -a
- - sudo apt-get -qq update
- - if test -n "$GCC5"; then sudo add-apt-repository -y ppa:ubuntu-toolchain-r/test && sudo apt-get -qq update && sudo apt-get install -qq g++-5 && export CC=gcc-5 && export CXX=g++-5; fi
- - if test -z "$GCC5"; then sudo apt-get -qq install libboost-dev; fi
- - if test -n "$GCC5"; then sudo add-apt-repository -y ppa:boost-latest/ppa && sudo apt-get -qq update && sudo apt-get install -qq libboost1.55-dev; fi
- - if test -z "$SWIGLANG"; then sudo apt-get -qq install yodl; fi
- - if test "$SWIGLANG" = "csharp"; then sudo apt-get -qq install mono-devel; fi
- - if test "$SWIGLANG" = "d"; then wget http://downloads.dlang.org/releases/2014/dmd_2.066.0-0_amd64.deb; sudo dpkg -i dmd_2.066.0-0_amd64.deb; fi
- - if test "$SWIGLANG" = "go"; then go env | sed -e 's/^/export /' > goenvsetup && source goenvsetup && rm -f goenvsetup; fi # Until configure.ac is fixed
- - if test "$SWIGLANG" = "javascript" -a "$ENGINE" = "node"; then sudo apt-get install -qq rlwrap python-software-properties && echo 'yes' | sudo add-apt-repository ppa:chris-lea/node.js && sudo apt-get -qq update && sudo apt-get install -qq nodejs && sudo npm install -g node-gyp; fi
- - if test "$SWIGLANG" = "javascript" -a "$ENGINE" = "jsc"; then sudo apt-get install -qq libwebkitgtk-dev; fi
- - if test "$SWIGLANG" = "javascript" -a "$ENGINE" = "v8"; then sudo apt-get install -qq libv8-dev; fi
- - if test "$SWIGLANG" = "guile"; then sudo apt-get -qq install guile-2.0-dev; fi
- - if test "$SWIGLANG" = "lua"; then sudo apt-get -qq install lua5.1 liblua5.1-dev; fi
- # configure also looks for ocamldlgen, but this isn't packaged. But it isn't used by default so this doesn't matter.
- - if test "$SWIGLANG" = "ocaml"; then sudo apt-get -qq install ocaml ocaml-findlib; fi
- - if test "$SWIGLANG" = "octave" -a -z "$VER"; then sudo apt-get -qq install octave3.2 octave3.2-headers; fi
- - if test "$SWIGLANG" = "octave" -a "$VER"; then sudo add-apt-repository -y ppa:kwwette/octaves && sudo apt-get -qq update && sudo apt-get -qq install liboctave${VER}-dev; fi
- - if test "$SWIGLANG" = "php"; then sudo apt-get install php5-cli php5-dev; fi
- - if test "$SWIGLANG" = "python"; then git clone https://github.com/jcrocholl/pep8.git && pushd pep8 && git checkout tags/1.5.7 && python ./setup.py build && sudo python ./setup.py install && popd; fi
- - if test "$SWIGLANG" = "python" -a "$PY3" -a -z "$VER"; then sudo apt-get install -qq python3-dev; fi
- - if test "$SWIGLANG" = "python" -a "$VER"; then sudo add-apt-repository -y ppa:fkrull/deadsnakes && sudo apt-get -qq update && sudo apt-get -qq install python${VER}-dev && CONFIGOPTS+=("--with-python${PY3}=python${VER}"); fi
- - if test "$SWIGLANG" = "r"; then sudo apt-get -qq install r-base; fi
- - if test "$SWIGLANG" = "scilab"; then sudo apt-get -qq install scilab; fi
- - if test "$SWIGLANG" = "tcl"; then sudo apt-get -qq install tcl8.4-dev; fi
+ - 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" = "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
+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
- 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
- # Stricter compile flags for examples. Various headers and SWIG generated code prevents full use of -pedantic.
- - if test -n "$SWIGLANG"; then export cflags=$(Tools/testflags.py --language $SWIGLANG --cflags --std=$CSTD) && echo $cflags; fi
- - if test -n "$SWIGLANG"; then export cxxflags=$(Tools/testflags.py --language $SWIGLANG --cxxflags --std=$CPPSTD) && echo $cxxflags; fi
script:
- echo 'Configuring...' && echo -en 'travis_fold:start:script.1\\r'
+ - if test -n "$SWIGLANG"; then CONFIGOPTS+=(--without-alllang --with-$WITHLANG); fi
- echo "${CONFIGOPTS[@]}"
- ./autogen.sh && mkdir -p build/build && cd build/build && ../../configure "${CONFIGOPTS[@]}"
- echo -en 'travis_fold:end:script.1\\r'
@@ -139,12 +322,13 @@ script:
- echo 'Installing...' && echo -en 'travis_fold:start:script.2\\r'
- if test -z "$SWIGLANG"; then sudo make -s install && swig -version && ccache-swig -V; fi
- echo -en 'travis_fold:end:script.2\\r'
+ # Stricter compile flags for examples. Various headers and SWIG generated code prevents full use of -pedantic.
+ - if test -n "$SWIGLANG"; then cflags=$($TRAVIS_BUILD_DIR/Tools/testflags.py --language $SWIGLANG --cflags --std=$CSTD --compiler=$CC) && echo $cflags; fi
+ - if test -n "$SWIGLANG"; then cxxflags=$($TRAVIS_BUILD_DIR/Tools/testflags.py --language $SWIGLANG --cxxflags --std=$CPPSTD --compiler=$CC) && echo $cxxflags; fi
- if test -n "$SWIGLANG"; then make -s check-$SWIGLANG-version; fi
+ - if test -n "$SWIGLANG"; then make check-$SWIGLANG-enabled; fi
- 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
- echo -en 'travis_fold:end:script.3\\r'
-branches:
- only:
- - master
diff --git a/ANNOUNCE b/ANNOUNCE
index f7d7eb8a9..53c5bbc59 100644
--- a/ANNOUNCE
+++ b/ANNOUNCE
@@ -1,8 +1,8 @@
-*** ANNOUNCE: SWIG 3.0.7 (in progress) ***
+*** ANNOUNCE: SWIG 3.0.11 (in progress) ***
http://www.swig.org
-We're pleased to announce SWIG-3.0.7, the latest SWIG release.
+We're pleased to announce SWIG-3.0.11, the latest SWIG release.
What is SWIG?
=============
@@ -18,15 +18,20 @@ include generation of scripting language extension modules, rapid
prototyping, testing, and user interface development for large
C/C++ systems.
+Release Notes
+=============
+Detailed release notes are available with the release and are also
+published on the SWIG web site at http://swig.org/release.html.
+
Availability
============
The release is available for download on Sourceforge at
- http://prdownloads.sourceforge.net/swig/swig-3.0.7.tar.gz
+ http://prdownloads.sourceforge.net/swig/swig-3.0.11.tar.gz
A Windows version is also available at
- http://prdownloads.sourceforge.net/swig/swigwin-3.0.7.zip
+ http://prdownloads.sourceforge.net/swig/swigwin-3.0.11.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 6cded08d4..67fd3f363 100644
--- a/CCache/Makefile.in
+++ b/CCache/Makefile.in
@@ -43,17 +43,21 @@ $(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
-install: $(PACKAGE_NAME)$(EXEEXT) $(srcdir)/$(PACKAGE_NAME).1
+install: $(PACKAGE_NAME)$(EXEEXT)
@echo "Installing $(PACKAGE_NAME)"
@echo "Installing $(DESTDIR)${bindir}/`echo $(PACKAGE_NAME) | sed '$(transform)'`$(EXEEXT)"
${INSTALLCMD} -d $(DESTDIR)${bindir}
${INSTALLCMD} -m 755 $(PACKAGE_NAME)$(EXEEXT) $(DESTDIR)${bindir}/`echo $(PACKAGE_NAME) | sed '$(transform)'`$(EXEEXT)
+
+install-docs: $(srcdir)/$(PACKAGE_NAME).1
@echo "Installing $(DESTDIR)${mandir}/man1/`echo $(PACKAGE_NAME) | sed '$(transform)'`.1"
${INSTALLCMD} -d $(DESTDIR)${mandir}/man1
${INSTALLCMD} -m 644 $(srcdir)/$(PACKAGE_NAME).1 $(DESTDIR)${mandir}/man1/`echo $(PACKAGE_NAME) | sed '$(transform)'`.1
-uninstall: $(PACKAGE_NAME)$(EXEEXT) $(srcdir)/$(PACKAGE_NAME).1
+uninstall: $(PACKAGE_NAME)$(EXEEXT)
rm -f $(DESTDIR)${bindir}/`echo $(PACKAGE_NAME) | sed '$(transform)'`$(EXEEXT)
+
+uninstall-docs: $(srcdir)/$(PACKAGE_NAME).1
rm -f $(DESTDIR)${mandir}/man1/`echo $(PACKAGE_NAME) | sed '$(transform)'`.1
clean:
diff --git a/CCache/ccache.c b/CCache/ccache.c
index e7dd1d30a..c5c510388 100644
--- a/CCache/ccache.c
+++ b/CCache/ccache.c
@@ -130,6 +130,7 @@ static void failed(void)
exit(1);
}
args_add_prefix(orig_args, p);
+ free(p);
}
if (ccache_verbose) {
@@ -490,7 +491,9 @@ static void find_hash(ARGS *args)
/* also include the hash of the compiler name - as some compilers
use hard links and behave differently depending on the real name */
if (st.st_nlink > 1) {
- hash_string(str_basename(args->argv[0]));
+ char *path = str_basename(args->argv[0]);
+ hash_string(path);
+ free(path);
}
hash_int(st.st_size);
@@ -523,6 +526,7 @@ static void find_hash(ARGS *args)
input_base, tmp_string(),
i_extension);
x_asprintf(&path_stderr, "%s/tmp.cpp_stderr.%s", temp_dir, tmp_string());
+ free(input_base);
if (!direct_i_file) {
/* run cpp on the input file to obtain the .i */
@@ -781,6 +785,7 @@ static void find_compiler(int argc, char **argv)
/* support user override of the compiler */
if ((path=getenv("CCACHE_CC"))) {
+ free(base);
base = x_strdup(path);
}
@@ -791,8 +796,10 @@ static void find_compiler(int argc, char **argv)
stats_update(STATS_COMPILER);
cc_log("could not find compiler (%s)\n", base);
perror(base);
+ free(base);
exit(1);
}
+ free(base);
}
@@ -1076,6 +1083,7 @@ static void process_args(int argc, char **argv)
if (strlen(p) < 2) {
cc_log("badly formed dependency file %s\n", output_file);
stats_update(STATS_ARGS);
+ free(default_depfile_name);
failed();
return;
}
@@ -1093,6 +1101,7 @@ static void process_args(int argc, char **argv)
strcat(default_depfile_name, ".d");
args_add(stripped_args, "-MF");
args_add(stripped_args, default_depfile_name);
+ free(default_depfile_name);
}
if (!dependency_target_specified) {
@@ -1117,6 +1126,7 @@ static void process_args(int argc, char **argv)
exit(1);
}
args_add_prefix(stripped_args, p);
+ free(p);
}
}
@@ -1305,6 +1315,7 @@ static void setup_uncached_err(void)
if (putenv(buf) == -1) {
cc_log("putenv failed\n");
+ close(uncached_fd);
stats_update(STATS_ERROR);
failed();
}
diff --git a/CCache/ccache.h b/CCache/ccache.h
index dcbb03f0c..a79d88322 100644
--- a/CCache/ccache.h
+++ b/CCache/ccache.h
@@ -20,7 +20,9 @@
#include
#include
#else
-#define _WIN32_WINNT 0x0500
+#ifndef _WIN32_WINNT
+ #define _WIN32_WINNT 0x0500
+#endif
#include
#include
#endif
diff --git a/CCache/execute.c b/CCache/execute.c
index 165b91e66..6df025e95 100644
--- a/CCache/execute.c
+++ b/CCache/execute.c
@@ -267,6 +267,7 @@ char *find_executable(const char *name, const char *exclude_name)
}
free(fname);
}
+ free(path);
return NULL;
#endif
diff --git a/CCache/stats.c b/CCache/stats.c
index d2122bcd3..4d01d2afa 100644
--- a/CCache/stats.c
+++ b/CCache/stats.c
@@ -138,7 +138,10 @@ static void stats_update_size(enum stats stat, size_t size, size_t numfiles)
memset(counters, 0, sizeof(counters));
- if (lock_fd(fd) != 0) return;
+ if (lock_fd(fd) != 0) {
+ close(fd);
+ return;
+ }
/* read in the old stats */
stats_read_fd(fd, counters);
diff --git a/CCache/test.sh b/CCache/test.sh
index 6e5d26703..438e782cd 100755
--- a/CCache/test.sh
+++ b/CCache/test.sh
@@ -15,6 +15,11 @@ else
SWIG=swig
fi
+# fix: Remove ccache from $PATH if it exists
+# as it will influence the unit tests
+PATH="`echo $PATH | \
+ sed -e 's!:/usr\(/local\)*/lib\([0-9]\)*/ccache\(/\)*!!g'`"
+
CCACHE=../ccache-swig
TESTDIR=test.$$
diff --git a/CCache/unify.c b/CCache/unify.c
index a93d48a02..7a36476a1 100644
--- a/CCache/unify.c
+++ b/CCache/unify.c
@@ -281,6 +281,7 @@ int unify_hash(const char *fname)
fd = open(fname, O_RDONLY|O_BINARY);
if (fd == -1 || fstat(fd, &st) != 0) {
cc_log("Failed to open preprocessor output %s\n", fname);
+ if (fd != -1) close(fd);
stats_update(STATS_PREPROCESSOR);
return -1;
}
@@ -289,12 +290,12 @@ int unify_hash(const char *fname)
lines in preprocessor output. I have seen lines of over
100k in length, so this is well worth it */
map = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
+ close(fd);
if (map == (char *)-1) {
cc_log("Failed to mmap %s\n", fname);
stats_update(STATS_PREPROCESSOR);
return -1;
}
- close(fd);
/* pass it through the unifier */
unify((unsigned char *)map, st.st_size);
diff --git a/CCache/util.c b/CCache/util.c
index 66f9823b9..ef90e2336 100644
--- a/CCache/util.c
+++ b/CCache/util.c
@@ -189,9 +189,11 @@ void copy_fd(int fd_in, int fd_out) {
while ((n = gzread(gz_in, buf, sizeof(buf))) > 0) {
if (write(fd_out, buf, n) != n) {
+ gzclose(gz_in);
fatal("Failed to copy fd");
}
}
+ gzclose(gz_in);
}
static int _copy_file(const char *src, const char *dest, int mode) {
@@ -248,9 +250,11 @@ static int _copy_file(const char *src, const char *dest, int mode) {
}
if (mode == COPY_TO_CACHE) {
- gz_out = gzdopen(dup(fd_out), "wb");
+ int dup_fd_out = dup(fd_out);
+ gz_out = gzdopen(dup_fd_out, "wb");
if (!gz_out) {
gzclose(gz_in);
+ close(dup_fd_out);
close(fd_out);
free(tmp_name);
return -1;
@@ -459,6 +463,7 @@ int create_cachedirtag(const char *dir)
f = fopen(filename, "w");
if (!f) goto error;
if (fwrite(CACHEDIR_TAG, sizeof(CACHEDIR_TAG)-1, 1, f) != 1) {
+ fclose(f);
goto error;
}
if (fclose(f)) goto error;
@@ -485,7 +490,7 @@ void x_asprintf(char **ptr, const char *format, ...)
}
va_end(ap);
- if (!ptr) fatal("out of memory in x_asprintf");
+ if (!*ptr) fatal("out of memory in x_asprintf");
}
/*
diff --git a/CHANGES b/CHANGES
index eb500e5f4..0146ac7ac 100644
--- a/CHANGES
+++ b/CHANGES
@@ -3,6 +3,519 @@ SWIG (Simplified Wrapper and Interface Generator)
See the CHANGES.current file for changes in the current version.
See the RELEASENOTES file for a summary of changes in each release.
+Version 3.0.10 (12 Jun 2016)
+============================
+
+2016-06-06: mromberg
+ [Python] Patch #698. Add support for -relativeimport for python 2.7, so -py3 is no
+ longer also required for relative import support.
+
+2016-06-05: mromberg
+ [Python] Patch #694 - Fix package import regressions introduced in swig-3.0.9.
+
+ 1) The code in 3.0.9 did not fall back to 'import _foo' if 'import bar._foo' failed
+ (assuming bar.foo was the main module). Every place _foo is imported now first tries
+ it from the package where foo was found and if that fails tries _foo as a global module.
+
+ 2) The separate block of Python code that injected code to pull in the attributes
+ from _foo when -builtin is used made use of the -py3 switch to either do
+ 'from ._foo import *' or "from _foo import *". This block of code no longer does this
+ and instead checks the Python version at runtime to switch between the two syntaxes.
+
+ In summary, swig-3.0.10 has been modified to ease the creation of wrapper modules
+ that can be fully made part of a Python package. SWIG no longer
+ assumes the dynamically linked C module is a global module.
+ The dynamic module can now be placed into either the same package as the pure Python
+ module or as a global module. Both locations are used by the Python wrapper to
+ locate the C module.
+
+ However, this could cause a backwards incompatibility with some code
+ that was relying on the ability of "from package import _module" to
+ pull attributes out of the package directly. If your code populates a
+ module (which is also a package) with attributes that are SWIG
+ generated modules which were not loaded in a conventional way,
+ swig-3.0.8 and earlier may have worked due to 'from package import
+ _module' bypassing a real import and pulling your module in as an
+ attribute. This will no longer work. Since this is not a common (or
+ even recommended) practice, most folk should not be affected.
+
+ *** POTENTIAL INCOMPATIBILITY ***
+
+2016-05-31: wsfulton
+ Fix #690 - Smart pointer to %ignored class doesn't expose inherited methods.
+ Regression introduced in swig-3.0.9.
+
+Version 3.0.9 (29 May 2016)
+===========================
+
+2016-05-24: mromberg
+ [Python] Patch #612 - Add support for Python's implicit namespace packages.
+
+2016-05-23: wsfulton
+ [Ruby] Fix #602 - Error handling regression of opaque pointers introduced
+ in swig-3.0.8 when C functions explicitly reset a pointer using 'DATA_PTR(self) = 0'.
+ An ObjectPreviouslyDeleted error was incorrectly thrown when the pointer was used
+ as a parameter.
+
+2016-05-17: tamuratak
+ [Ruby] Patch #651 - Correct overloaded function error message when function is
+ using %newobject.
+
+2016-05-17: aurelj
+ [Ruby] Patch #582 - add support for docstring option in %module()
+
+2016-05-14: wsfulton
+ Fix #434 - Passing classes by value as parameters in director methods did not create
+ a copy of the argument leading to invalid memory accesses if the object was used
+ after the upcall into the target language. Passing arguments by value shouldn't give
+ rise to these sorts of memory problems and so the objects are now copied and ownership
+ of their lifetime is controlled by the target language.
+
+2016-05-07: wsfulton
+ Fix #611. Fix assertion handling defaultargs when using %extend for a template
+ class and the extended methods contain default arguments.
+
+2016-05-05: ejulian
+ [Python] Patch #617. Fix operator/ wrappers.
+
+2016-05-02: wsfulton
+ Fix #669. Don't issue warning about ignoring base classes when the derived class is
+ itself ignored.
+
+2016-04-18: ianlancetaylor
+ [Go] Fix use of goout typemap when calling base method by
+ forcing the "type" attribute to the value we need.
+
+2016-04-17: ianlancetaylor
+ [Go] Fixes for Go 1.6: avoid returning Go pointers from
+ directors that return string values; add a trailing 0 byte
+ when treating Go string as C char*.
+
+2016-04-06: smarchetto
+ [Scilab] #552 Make Scilab runtime keep track of pointer types
+ Instead of a Scilab pointer which has no type, SWIG Scilab maps a
+ pointer to a structure tlist containing the pointer adress and its type.
+
+2016-04-02: ahnolds
+ [Python] Apply #598. Fix misleading error message when attempting to read a non-existent
+ attribute. The previous cryptic error message:
+ AttributeError: type object 'object' has no attribute '__getattr__'
+ is now replaced with one mentioning the attribute name, eg:
+ AttributeError: 'Foo' object has no attribute 'bar'
+
+2016-04-02: derkuci
+ [Python] Patch #610 to fix #607.
+ Fix single arguments when using python -builtin -O with %feature("compactdefaultargs")
+
+2016-03-31: wsfulton
+ Fixes #594. Fix assertion for some languages when wrapping a C++11 enum class that
+ is private in a class.
+
+ Also don't wrap private enums for a few languages that attempted to do so.
+
+2016-03-31: wsfulton
+ [Java] unsigned long long marshalling improvements when a negative number
+ is passed from Java to C. A cast to signed long long in the C layer will now
+ result in the expected value. No change for positive numbers passed to C.
+ Fixes #623.
+
+2016-03-22: alexwarg
+ [Lua] #398 Fix lua __getitem + inheritance
+ The new handling of classes in Lua (not merging methods into the derived classes)
+ breaks for classes that provide a __getitem function. The __getitem function
+ prevents method calls to any method defined in a base class. This fix calls
+ __getitem only if the member is not found using recursive lookup.
+
+2016-03-18: ptomulik
+ [Python] #563 Stop generating unnecessary _swigconstant helpers.
+
+2016-03-16: richardbeare
+ [R] #636 Add extra std::vector numeric types
+
+2016-03-14: wsfulton
+ [Java] Add std_array.i for C++11 std::array support.
+
+2016-03-12: wsfulton
+ [Java, C#, D] Fix static const char member variables wrappers with %javaconst(1)
+ %csconst(1) or %dmanifestconst.
+ This fixes the case when an integer is used as the initializer, such as:
+
+ struct W { static const char w = 100; };
+
+ Fix generated code parsing enum values using char escape sequences
+ when these values appear in the Java code (usually when using %javaconst(1))
+ such as:
+
+ enum X { x1 = '\n', x2 = '\1' };
+
+ Similarly for static const member char variables such as:
+
+ struct Y { static const char y = '\n'; }
+
+ Likewise for D and %dmanifestconstant. For C# and %csconst(1), char
+ values in C# are now hex escaped as C# doesn't support C octal escaping.
+
+2016-03-11: wsfulton
+ [Java C#] Add support for treating C++ base classes as Java interfaces
+ instead of Java proxy classes. This enable some sort of support for
+ multiple inheritance. The implementation is in swiginterface.i and
+ provides additional macros (see Java.html for full documentation):
+
+ %interface(CTYPE)
+ %interface_impl(CTYPE)
+ %interface_custom("PROXY", "INTERFACE", CTYPE)
+
+2016-03-01: wsfulton
+ Add rstrip encoder for use in %rename. This is like the strip encoder but
+ strips the symbol's suffix instead of the prefix. The example below
+ will rename SomeThingCls to SomeThing and AnotherThingCls to AnotherThing:
+
+ %rename("%(rstrip:[Cls])s") "";
+
+ class SomeThingCls {};
+ struct AnotherThingCls {};
+
+2016-03-01: olly
+ Fix isfinite() check to work with GCC6. Fixes
+ https://github.com/swig/swig/issues/615 reported by jplesnik.
+
+2016-02-17: olly
+ [Python] Add missing keywords 'as' and 'with' to pythonkw.swg.
+
+2016-02-07: kwwette
+ [Octave] recognise various unary functions
+ * Use __float__() for numeric conversions, e.g. when calling double()
+ * Map various unary functions, e.g. abs() to __abs__(), see full list
+ in section 32.3.10 of manual; only available in Octave 3.8.0 or later
+
+2016-02-07: kwwette
+ [Octave] export function swig_octave_prereq() for testing Octave version
+
+2016-02-06: pjohangustavsson
+ [C#] Fix duplicate symbol problems when linking the source generated
+ from multiple SWIG modules into one shared library for the -namespace
+ option. The namespace is now mangled into the global PInvoke function
+ names.
+
+ *** POTENTIAL INCOMPATIBILITY ***
+
+2016-01-27: ahnolds
+ [Python] Added support for differentiating between Python Bytes
+ and Unicode objects using by defining SWIG_PYTHON_STRICT_BYTE_CHAR
+ and SWIG_PYTHON_STRICT_UNICODE_WCHAR.
+
+2016-01-27: steeve
+ [Go] Ensure structs are properly packed between gc and GCC/clang.
+
+2016-01-25: ahnolds
+ [Python] Support the full Python test suite in -classic mode
+ * Convert long/unsigned long/long long/unsigned long long to PyInt
+ rather than PyLong when possible. Certain python functions like
+ len() require a PyInt when operating on old-style classes.
+ * Add support for static methods in classic mode, including support
+ for pythonappend, pythonprepend, and docstrings.
+ * Removing the use of __swig_getmethods__ for static member methods
+ since they will always be found by the standard argument lookup
+ * Fix a bug where the wrong type of exception was caught when
+ checking for new-style class support
+
+2016-01-23: ahnolds
+ [Go] Enable support for the Go test-suite on OSX:
+ * The linker on OSX requires that all symbols (even weak symbols)
+ are defined at link time. Because the function _cgo_topofstack is
+ only defined starting in Go version 1.4, we explicitly mark it as
+ undefined for older versions of Go on OSX.
+ * Avoid writing empty swigargs structs, since empty structs are not
+ allowed in extern "C" blocks.
+
+2016-01-12: olly
+ [Javascript] Look for "nodejs" as well as "node", as it's packaged
+ as the former on Debian.
+
+2016-01-12: olly
+ [Javascript] For v8 >= 4.3.0, use V8_MAJOR_VERSION.
+ Fixes https://github.com/swig/swig/issues/561.
+
+2016-01-10: ahnolds
+ Improved size_t and ptrdiff_t typemaps to support large values
+ on platforms where sizeof(size_t) > sizeof(unsigned long) and
+ sizeof(ptrdiff_t) > sizeof(long).
+
+Version 3.0.8 (31 Dec 2015)
+===========================
+
+2015-12-30: wsfulton
+ The pdf documentation is now generated by wkhtmltopdf and has colour
+ for the code snippets just like the html documentation!
+
+2015-12-23: ahnolds
+ [Python] Fixes for conversion of signed and unsigned integer types:
+
+ No longer check for PyInt objects in Python3. Because PyInt_Check
+ and friends are #defined to the corresponding PyLong methods, this
+ had caused errors in Python3 where values greater than what could be
+ stored in a long were incorrectly interpreted as the value -1 with
+ the Python error indicator set to OverflowError. This applies to
+ both the conversions PyLong->long and PyLong->double.
+
+ Conversion from PyLong to long, unsigned long, long long, and
+ unsigned long long now raise OverflowError instead of TypeError in
+ both Python2 and Python3 for PyLong values outside the range
+ expressible by the corresponding C type. This matches the existing
+ behavior for other integral types (signed and unsigned ints, shorts,
+ and chars), as well as the conversion for PyInt to all numeric
+ types. This also indirectly applies to the size_t and ptrdiff_t
+ types, which depend on the conversions for unsigned long and long.
+
+2015-12-19: wsfulton
+ [Python] Python 2 Unicode UTF-8 strings can be used as inputs to char * or
+ std::string types if the generated C/C++ code has SWIG_PYTHON_2_UNICODE defined.
+
+2015-12-17: wsfulton
+ Issues #286, #128
+ Remove ccache-swig.1 man page - please use the CCache.html docs instead.
+ The yodl2man and yodl2html tools are no longer used and so SWIG no
+ longer has a dependency on these packages which were required when
+ building from git.
+
+2015-12-16: zturner/coleb
+ [Python] Fix Python3.5 interpreter assertions when objects are being
+ deleted due to an existing exception. Most notably in generators
+ which terminate using a StopIteration exception. Fixes #559 #560 #573.
+ If a further exception is raised during an object destruction,
+ PyErr_WriteUnraisable is used on this second exception and the
+ original exception bubbles through.
+
+2015-12-14: ahnolds/wsfulton
+ [Python] Add in missing initializers for tp_finalize,
+ nb_matrix_multiply, nb_inplace_matrix_multiply, ht_qualname
+ ht_cached_keys and tp_prev.
+
+2015-12-12: wsfulton
+ Fix STL wrappers to not generate <: digraphs.
+ For example std::vector<::X::Y> was sometimes generated, now
+ corrected to std::vector< ::X::Y >.
+
+2015-11-25: wsfulton
+ [Ruby] STL ranges and slices fixes.
+
+ Ruby STL container setting slices fixes:
+
+ Setting an STL container wrapper slice better matches the way Ruby
+ arrays work. The behaviour is now the same as Ruby arrays. The only
+ exception is the default value used when expanding a container
+ cannot be nil as this is not a valid type/value for C++ container
+ elements.
+
+ Obtaining a Ruby STL container ranges and slices fixes:
+
+ Access via ranges and slices now behave identically to Ruby arrays.
+ The fixes are mostly for out of range indices and lengths.
+ - Zero length slice requests return an empty container instead of nil.
+ - Slices which request a length greater than the size of the container
+ no longer chop off the last element.
+ - Ranges which used to return nil now return an empty array when the
+ the start element is a valid index.
+
+ Ruby STL container negative indexing support improved.
+
+ Using negative indexes to set values works the same as Ruby arrays, eg
+
+ %template(IntVector) std::vector;
+
+ iv = IntVector.new([1,2,3,4])
+ iv[-4] = 9 # => [1,2,3,9]
+ iv[-5] = 9 # => IndexError
+
+2015-11-21: wsfulton
+ [Ruby, Python] Add std::array container wrappers.
+
+ These work much like any of the other STL containers except Python/Ruby slicing
+ is somewhat limited because the array is a fixed size. Only slices of
+ the full size are supported.
+
+2015-10-10: wsfulton
+ [Python] #539 - Support Python 3.5 and -builtin. PyAsyncMethods is a new
+ member in PyHeapTypeObject.
+
+2015-10-06: ianlancetaylor
+ [Go] Don't emit a constructor function for a director
+ class with an abstract method, since the function will
+ always panic.
+
+2015-10-01: wsfulton
+ Fix %shared_ptr support for private and protected inheritance.
+ - Remove unnecessary Warning 520: Derived class 'Derived' of 'Base'
+ is not similarly marked as a smart pointer
+ - Do not generate code that attempts to cast up the inheritance chain in the
+ type system runtime in such cases as it doesn't compile and can't be used.
+ Remove unnecessary warning 520 for %shared_ptr when the base class is ignored.
+
+2015-10-01: vkalinin
+ Fix #508: Fix segfault parsing anonymous typedef nested classes.
+
+2015-09-26: wsfulton
+ [Ruby] Add shared_ptr support
+
+2015-09-13: kkaempf
+ [Ruby] Resolve tracking bug - issue #225.
+ The bug is that the tracking code uses a ruby hash and thus may
+ allocate objects (Bignum) while running the GC. This was tolerated in
+ 1.8 but is invalid (raises an exception) in 1.9.
+ The patch uses a C hash (also used by ruby) instead.
+
+2015-09-09: lyze
+ [CFFI] Extend the "export" feature in the CFFI module to support
+ exporting to a specified package.
+
+2015-09-04: olly
+ [Python] Fix docstrings for %callback functions.
+
+2015-09-03: demi-rluddy
+ [Go] Removed golang stringing for signed/unsigned char
+
+ Changed default handling of signed char* and unsigned char* to be
+ opaque pointers rather than strings, similarly to how other
+ languages work.
+
+ Any existing code relying on treating signed char* or unsigned
+ char* as a string can restore the old behavior with typemaps.i by
+ using %apply to copy the [unchanged] char* behavior.
+
+ *** POTENTIAL INCOMPATIBILITY ***
+
+2015-08-07: talby
+ [Perl] tidy -Wtautological-constant-out-of-range-compare warnings when building generated code under clang
+
+2015-08-07: xantares
+ [Python] pep257 & numpydoc conforming docstrings:
+ - Mono-line module docsstring
+ - Rewrite autodoc parameters section in numpydoc style:
+ https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt
+ - One line summary should end with "."
+ - Adds a blank line after class docstring
+
+2015-08-05: vadz
+ [Java] Make (char* STRING, size_t LENGTH) typemaps usable for
+ strings of other types, e.g. "unsigned char*".
+
+Version 3.0.7 (3 Aug 2015)
+==========================
+
+2015-08-02: wsfulton
+ [Java] Fix potential security exploit in generated Java classes.
+ The swigCPtr and swigCMemOwn member variables in the generated Java
+ classes are now declared 'transient' by default. Further details of the exploit
+ in Android is being published in an academic paper as part of USENIX WOOT '15:
+ https://www.usenix.org/conference/woot15/workshop-program/presentation/peles.
+
+ In the unlikely event that you are relying on these members being serializable,
+ then you will need to override the default javabody and javabody_derived typemaps
+ to generate the old generated code. The relevant typemaps are in the Lib directory
+ in the java.swg, boost_shared_ptr.i and boost_intrusive_ptr.i files. Copy the
+ relevant default typemaps into your interface file and remove the 'transient' keyword.
+
+ *** POTENTIAL INCOMPATIBILITY ***
+
+2015-08-01: vadz
+ Make configure --without-alllang option more useful: it can now be overridden by the following
+ --with-xxx options, allowing to easily enable just one or two languages.
+
+2015-07-30: wsfulton
+ Fix #440 - Initialise all newly created arrays when using %array_functions and %array_class
+ in the carrays.i library - bug is only relevant when using C++.
+
+2015-07-29: wsfulton
+ [Python] Improve indentation warning and error messages for code in the following directives:
+
+ %pythonprepend
+ %pythonappend
+ %pythoncode
+ %pythonbegin
+ %feature("shadow")
+
+ Old error example:
+ Error: Line indented less than expected (line 3 of pythoncode)
+
+ New error example:
+ Error: Line indented less than expected (line 3 of %pythoncode or %insert("python") block)
+ as no line should be indented less than the indentation in line 1
+
+ Old warning example:
+ Warning 740: Whitespace prefix doesn't match (line 2 of %pythoncode or %insert("python") block)
+
+ New warning example:
+ Warning 740: Whitespace indentation is inconsistent compared to earlier lines (line 3 of
+ %pythoncode or %insert("python") block)
+
+
+2015-07-28: wsfulton
+ [Python] Fix #475. Improve docstring indentation handling.
+
+ SWIG-3.0.5 and earlier sometimes truncated text provided in the docstring feature.
+ This occurred when the indentation (whitespace) in the docstring was less in the
+ second or later lines when compared to the first line.
+ SWIG-3.0.6 gave a 'Line indented less than expected' error instead of truncating
+ the docstring text.
+ Now the indentation for the 'docstring' feature is smarter and is appropriately
+ adjusted so that no truncation occurs.
+
+2015-07-22: wsfulton
+ Support for special variable expansion in typemap attributes. Example usage expansion
+ in the 'out' attribute (C# specific):
+
+ %typemap(ctype, out="$*1_ltype") unsigned int& "$*1_ltype"
+
+ is equivalent to the following as $*1_ltype expands to 'unsigned int':
+
+ %typemap(ctype, out="unsigned int") unsigned int& "unsigned int"
+
+ Special variables can be used within special variable macros too. Example usage expansion:
+
+ %typemap(cstype) unsigned int "uint"
+ %typemap(cstype, out="$typemap(cstype, $*1_ltype)") unsigned int& "$typemap(cstype, $*1_ltype)"
+
+ Special variables are expanded first and hence the above is equivalent to:
+
+ %typemap(cstype, out="$typemap(cstype, unsigned int)") unsigned int& "$typemap(cstype, unsigned int)"
+
+ which then expands to:
+
+ %typemap(cstype, out="uint") unsigned int& "uint"
+
+2015-07-22: lindleyf
+ Apply patch #439 - support for $typemap() (aka embedded typemaps or special variable
+ macros) in typemap attributes. A simple example where $typemap() is expanded in the
+ 'out' attribute (C# specific):
+
+ %typemap(cstype) unsigned int "uint"
+ %typemap(cstype, out="$typemap(cstype, unsigned int)") unsigned int& "$typemap(cstype, unsigned int)"
+
+ is equivalent to:
+
+ %typemap(cstype, out="uint") unsigned int& "uint"
+
+2015-07-18: m7thon
+ [Python] Docstrings provided via %feature("docstring") are now quoted and added to
+ the tp_doc slot when using python builtin classes (-builtin). When no docstring is
+ provided, the tp_doc slot is set to the fully qualified C/C++ class name.
+ Github issues #445 and #461.
+
+2015-07-17: kwwette
+ [octave] Support Octave version 4.0.0 (thanks to patches from Orion Poplawski).
+
+2015-07-07: wsfulton
+ SWIG no longer generates a wrapper for a class' constructor if that class has
+ any base class with a private destructor. This is because your compiler should
+ not allow a class to be instantiated if a base has a private destructor. Some
+ compilers do, so if you need the old behaviour, use the "notabstract" feature, eg:
+
+ %feature("notabstract") Derived;
+ class Base {
+ ~Base() {}
+ };
+ struct Derived : Base {};
+
Version 3.0.6 (5 Jul 2015)
==========================
@@ -312,7 +825,7 @@ Version 3.0.3 (30 Dec 2014)
2014-10-21: wsfulton
Fix issue #242 - Use of the "kwargs" feature no longer automatically turns on the
"compactdefaultargs" feature if the target language does not support kwargs.
- Only Java and Python support kwargs, so this affects all the other languages.
+ This change affects all languages except Python and Ruby.
*** POTENTIAL INCOMPATIBILITY ***
@@ -1726,7 +2239,7 @@ Version 2.0.6 (30 April 2012)
[Lua] Fix uninitialised variable in SWIGTYPE **OUTPUT typemaps as reported by Jim Anderson.
2012-04-28: wsfulton
- [Python] Fix compilation errors when wrapping STL containers on Mac OSX and possibly other systems.
+ [Python] Fix compilation errors when wrapping STL containers on Mac OS X and possibly other systems.
2012-04-28: wsfulton
[Java] Patch 3521811 from Leo Davis - char **STRING_ARRAY typemaps fixed to handle
@@ -2421,7 +2934,7 @@ Version 2.0.2 (20 February 2011)
Update chapter name to MzScheme/Racket accounting for the rename of MzScheme to Racket.
2011-02-05: wsfulton
- [C#] SF #3085906 - Possible fix running test-suite on Mac OSX.
+ [C#] SF #3085906 - Possible fix running test-suite on Mac OS X.
2011-02-05: wsfulton
SF #3173367 Better information during configure about Boost prerequisite for running
@@ -4074,7 +4587,7 @@ Version 1.3.37 (13 January 2009)
in Allegro CL
2008-07-19: wsfulton
- Fix building of Tcl examples/test-suite on Mac OSX reported by Gideon Simpson.
+ Fix building of Tcl examples/test-suite on Mac OS X reported by Gideon Simpson.
2008-07-17: wsfulton
Fix SF #2019156 Configuring with --without-octave or --without-alllang
@@ -7578,7 +8091,7 @@ Version 1.3.28 (February 12, 2006)
12/10/2005: mmatus
[UTF]
- - Fix unneccessary calls to SWIG_TypeQuery for 'char *'
+ - Fix unnecessary calls to SWIG_TypeQuery for 'char *'
and 'wchar_t *', problem found by Clay Culver while
profiling the PyOgre project.
@@ -12895,7 +13408,7 @@ Version 1.3.20 (December 17, 2003)
Suggested by Kerim Borchaev.
11/11/2003: beazley
- Configuration changes to make SWIG work on Mac OSX 10.3.x (Panther).
+ Configuration changes to make SWIG work on Mac OS X 10.3.x (Panther).
Tested with Python, Tcl, Perl, and Ruby---all of which seem to work.
11/08/2003: cheetah (William Fulton)
@@ -23301,7 +23814,7 @@ Version 1.1b5 (March 12, 1997)
2/23/97 : Modified Python module to be better behaved under Windows
- Module initialization function is now properly exported.
- It should not be neccessary to explicitly export this function
+ It should not be necessary to explicitly export this function
yourself.
- Bizarre compilation problems when compiling the SWIG wrapper
diff --git a/CHANGES.current b/CHANGES.current
index 0c56946f8..27194fba2 100644
--- a/CHANGES.current
+++ b/CHANGES.current
@@ -2,27 +2,246 @@ Below are the changes for the current release.
See the CHANGES file for changes in older releases.
See the RELEASENOTES file for a summary of changes in each release.
-Version 3.0.7 (in progress)
-===========================
+Version 3.0.11 (in progress)
+============================
-2015-07-18: m7thon
- [Python] Docstrings provided via %feature("docstring") are now quoted and added to
- the tp_doc slot when using python builtin classes (-builtin). When no docstring is
- provided, the tp_doc slot is set to the fully qualified C/C++ class name.
- Github issues #445 and #461.
+2016-12-01: wsfulton
+ [Python] Issue https://github.com/swig/swig/issues/769
+ Add optional moduleimport attribute to %module so that the
+ default module import code can be overridden. See the "Searching for the wrapper module"
+ documentation in Python.html. Example:
-2015-07-17: kwwette
- [octave] Support Octave version 4.0.0 (thanks to patches from Orion Poplawski).
+ %module(moduleimport="import _foo") foo
-2015-07-07: wsfulton
- SWIG no longer generates a wrapper for a class' constructor if that class has
- any base class with a private destructor. This is because your compiler should
- not allow a class to be instantiated if a base has a private destructor. Some
- compilers do, so if you need the old behaviour, use the "notabstract" feature, eg:
+ $module also expands to the low-level C/C++ module name, so the following is the
+ same as above
- %feature("notabstract") Derived;
- class Base {
- ~Base() {}
+ %module(moduleimport="import $module") foo
+
+2016-11-30: olly
+ [PHP] Add support for PHP7. PHP5's C extension API has changed substantially
+ so you need to use -php7 to specify you want PHP7 compatible wrappers. The
+ default extension for generated wrappers is now .cxx (to match SWIG's default
+ for every other language - to generate foo_wrap.cpp you can run SWIG with
+ -cppext cpp). Fixes https://github.com/swig/swig/issues/571
+
+2016-11-30: olly
+ [PHP] Only emit one copy of each distinct arginfo. Previously we
+ emitted a separate one for every wrapped function, but typically
+ many functions have the same number of parameters and combinations
+ of parameters passed by reference or not.
+
+ This change significantly reduces both the size of the generated
+ wrapper, and of the compiled PHP extension module (e.g. by ~6% for
+ the stripped extension module for Xapian's PHP7 bindings).
+
+2016-11-28: wsfulton
+ Fix %rename override of wildcard %rename for templates. For example:
+
+ %rename(GlobalIntOperator) *::operator bool; // wildcard %rename
+
+ %rename(XIntOperator) X::operator bool; // fix now overrides first %rename above
+ OR
+ %rename(XIntOperator) X::operator bool; // fix now overrides first %rename above
+
+ template struct X {
+ operator bool();
+ ...
};
- struct Derived : Base {};
+ %template(Xint) X;
+2016-11-26: m7thon
+ [Python] Issue #709 - improved wrapping of division operators
+ 'from __future__ import division' now works in Python 2 whether or not the
+ -py3 flag is used.
+
+2016-11-12: joequant
+ [R] Issue #697 - fix comma issue with overload methods
+
+2016-11-12: joequant
+ [R] Issue #555 - R runtime needs stdio.h
+
+2016-11-02: wsfulton
+ [Python] Issue #816 - fix compilation error when using -extranative and -builtin.
+
+2016-11-02: liorgold
+ Patch #741 - Add support for C++11 alias templates, see updated CPlusPlus11.html
+ documentation.
+
+2016-10-30: myd7349
+ [C#] Patch #740 Add std_array.i for C# for wrapping std::array.
+
+ Patch also enhances std::vector C# wrappers with additional functions
+ (Contains, IndexOf, LastIndexOf and Remove).
+
+2016-10-30: tobilau
+ [Java] Fix wrappers for wstring parameters in director methods to cleanup local
+ ref after director callback has finished.
+
+2016-10-23: wsfulton
+ [C#] Add missing csdirectorin VOID_INT_PTR and csdirectorout VOID_INT_PTR typemaps.
+
+2016-10-23: jiulongw
+ Patch #781 - Fix wrapping of C compound expressions containing char constants
+ in quotes such as:
+
+ #define H_SUPPRESS_SCALING_MAGIC (('s'<<24) | ('u'<<16) | ('p'<<8) | 'p')
+
+ enum DifferentTypes {
+ typecharcompound='A'+1,
+ typecharcompound2='B' << 2
+ };
+
+2016-10-13: wsfulton
+ [Python] Issue #808 - fix Python pickling and metaclass for builtin wrappers.
+
+ The metaclass (SwigPyObjectType) for SWIG objects was not defined in
+ a way that let importlib successfully import the Python wrappers.
+ The pickle module previously failed to pickle objects because it couldn't
+ determine what module the SWIG wrapped objects were in.
+
+2016-09-29: wsfulton
+ [Allegrocl, CFFI, GO, Javascript, Ocaml, R, Scilab]
+ Add missing support for the "ret" typemap in a few target languages.
+ The documentation also now has info on the "ret" typemap.
+
+2016-09-27: ahmed-usman
+ [xml] Handle template parameters correctly.
+
+2016-09-27: dontpanic92
+ [Go] Fix argument names in inherited functions taking more than 8
+ parameters. Fixes #795.
+
+2016-09-26: smarchetto
+ [Scilab] mlists that map pointers can be given a custom type name.
+
+2016-09-25: wsfulton
+ Patch #793 from q-p to expand exception handling to include std::bad_cast
+ in std_except.i.
+
+2016-09-24: olly
+ [PHP] Fix code generated for feature("director:except") -
+ previously the return value of call_user_function() was ignored and
+ we checked an uninitialised value instead. Fixes #627. Based on
+ patch from Sergey Seroshtan.
+
+2016-09-22: wsfulton
+ [Python] More flexible python builtin slots for overloaded C++ function.
+
+ The closure names used for builtin slots are mangled with their functype so
+ that overloaded C++ method names can be used for multiple slots.
+ For example:
+
+ %feature("python:slot", "mp_subscript", functype="binaryfunc") SimpleArray::__getitem__;
+ %feature("python:slot", "sq_item", functype="ssizeargfunc") SimpleArray::__getitem__(Py_ssize_t n);
+
+ will generate closures:
+
+ SWIGPY_SSIZEARGFUNC_CLOSURE(_wrap_SimpleArray___getitem__) /* defines _wrap_SimpleArray___getitem___ssizeargfunc_closure */
+ SWIGPY_BINARYFUNC_CLOSURE(_wrap_SimpleArray___getitem__) /* defines _wrap_SimpleArray___getitem___binaryfunc_closure */
+
+ Previously only one name was defined: _wrap_SimpleArray___getitem___closure.
+ Hence the overloaded __getitem__ method can be used to support both mp_subscript and sq_item slots.
+
+2016-09-17: wsfulton
+ [Python] Fix iterators for containers of NULL pointers (or Python None) when using
+ -builtin. Previously iteration would stop at the first element that was NULL.
+
+2016-09-16: olly
+ [Javascript] Fix SWIG_exception() macro to return from the current
+ function. Fixes #789, reported by Julien Dutriaux.
+
+2016-09-16: olly
+ [PHP] Fix SWIG_exception() macro to return from the current function.
+ Fixes #240, reported by Sergey Seroshtan.
+
+2016-09-12: xypron
+ [C#] Patch #786 Keyword rename to be CLS compliant by adding an underscore
+ suffix instead of an underscore suffix to the C symbol name. Please use an explicit
+ %rename to rename the symbol with a _ prefix if you want the old symbol name.
+
+ *** POTENTIAL INCOMPATIBILITY ***
+
+2016-09-09: olly
+ [Python] Fix import handling for Python 2.6 to work in a frozen
+ application. Fixes #145, reported by Thomas Kluyver.
+
+2016-09-02: smarchetto
+ [Scilab] Pointers are mapped to mlist instead of tlist
+ (mlist better for scilab overloading)
+
+2016-09-02: olly
+ [PHP] Fix "out" typemap for member function pointers and "in"
+ typemap for char INPUT[ANY].
+
+2016-09-01: wsfulton
+ [Python] More efficient Python slicing.
+ Call reserve for container types that support it to avoid repeated
+ memory reallocations for new slices or slices that grow in size.
+
+2016-09-01: wsfulton
+ [Python] #771 - Make builtin types hashable by default.
+ Default hash is the underlying C/C++ pointer. This matches up with testing for
+ equivalence (Py_EQ in SwigPyObject_richcompare) which compares the pointers.
+
+2016-08-22: wsfulton
+ [Python] The following builtin slots can be customized like other slots via the
+ "python:" and "python:slot" features where is the appropriate slot name:
+ tp_allocs
+ tp_bases
+ tp_basicsize
+ tp_cache
+ tp_del
+ tp_dealloc
+ tp_flags
+ tp_frees
+ tp_getset
+ tp_is_gc
+ tp_maxalloc
+ tp_methods
+ tp_mro
+ tp_new
+ tp_next
+ tp_prev
+ tp_richcompare
+ tp_subclasses
+ tp_weaklist
+ was_sq_ass_slice
+ was_sq_slice
+
+ A few documentation improvements for slot customization.
+
+2016-08-09: joequant
+ [R] Patch #765 Fix extern "C" header includes for C++ code.
+
+2016-08-05: olly
+ [xml] Fix how the output filename is built to avoid problems when
+ it contains the embedded strings ".c", ".cpp" or ".cxx".
+ Fixes #540 reported by djack42.
+
+2016-07-01: wsfulton
+ Fix corner case of wrapping std::vector of T pointers where a pointer to a pointer of T
+ also exists in the wrapped code. SF Bug 2359417 (967).
+
+2016-06-26: wkalinin
+ [Java, C#] Patch #681 Fix seg fault when ignoring nested classes.
+
+2016-06-25: mromberg
+ [Python] #711 Fix -castmode and conversion of signed and unsigned integer types.
+ See 2015-12-23 CHANGES entry for details of these improvements when they were
+ implemented for the default options (ie not using -castmode).
+
+2016-06-25: ahnolds
+ Patch #730 - Fix %implicitconv for overloaded functions when using
+ -castmode or -fastdispatch options.
+
+ The result is that in all overload cases where there are multiple possibilities
+ with the same number of arguments, the dispatch function will first check for
+ exact (aka non implicit) matches, and then subsequently check for implicit
+ casting matches. This was already happening in the normal dispatch situation,
+ and in the -fastdispatch case two passes through the candidates were happening,
+ just with SWIG_POINTER_IMPLICIT_CONV always set. After this patch, it is not set
+ on the first pass, and then set on the second pass.
+
+2016-06-25: liorgold
+ Patch #727 - Add support for C++11 type aliasing.
diff --git a/Doc/Manual/Allegrocl.html b/Doc/Manual/Allegrocl.html
index 8295bad1c..664e720c8 100644
--- a/Doc/Manual/Allegrocl.html
+++ b/Doc/Manual/Allegrocl.html
@@ -1,14 +1,14 @@
-
-
+
SWIG and Allegro Common Lisp
+
-
@@ -324,7 +324,7 @@ what is generated when parsing C code:
- ...
+ ...
(swig-in-package ())
@@ -360,7 +360,7 @@ need to link in the Allegro shared library. The library you create from
the C++ wrapper will be what you then load into Allegro CL.
-
@@ -373,21 +373,21 @@ swig -allegrocl [ options ] filename
-identifier-converter [name] - Binds the variable swig:*swig-identifier-convert*
in the generated .cl file to name.
- This function is used to generate symbols
- for the lisp side of the interface.
+ This function is used to generate symbols
+ for the lisp side of the interface.
-cwrap - [default] Generate a .cxx file containing C wrapper function when
wrapping C code. The interface generated is similar to what is
- done for C++ code.
+ done for C++ code.
-nocwrap - Explicitly turn off generation of .cxx wrappers for C code. Reasonable
for modules with simple interfaces. Can not handle all legal enum
- and constant constructs, or take advantage of SWIG customization features.
+ and constant constructs, or take advantage of SWIG customization features.
-isolate - With this command-line argument, all lisp helper functions are defined
in a unique package named swig.<module-name> rather than
- swig. This prevents conflicts when the module is
- intended to be used with other swig generated interfaces that may,
- for instance, make use of different identifier converters.
+ swig. This prevents conflicts when the module is
+ intended to be used with other swig generated interfaces that may,
+ for instance, make use of different identifier converters.
- Users are cautioned to get to know their constants before use, or
- not use the -nocwrap command-line option.
+ Users are cautioned to get to know their constants before use, or
+ not use the -nocwrap command-line option.
- SWIG provides support for dealing with templates, but by
- default, it will not generate any member variable or function
- wrappers for templated classes. In order to create these
- wrappers, you need to explicitly tell SWIG to instantiate
- them. This is done via the
- %template
- directive.
-
+
+SWIG provides support for dealing with templates, but by
+default, it will not generate any member variable or function
+wrappers for templated classes. In order to create these
+wrappers, you need to explicitly tell SWIG to instantiate
+them. This is done via the
+%template
+directive.
+
- While no wrapper code is generated for accessing member
- variables, or calling member functions, type code is generated
- to include these templated classes in the foreign-type and CLOS
- class schema.
-
+
+While no wrapper code is generated for accessing member
+variables, or calling member functions, type code is generated
+to include these templated classes in the foreign-type and CLOS
+class schema.
+
class A {
- int x;
- int y;
+ int x;
+ int y;
};
typedef A Foo;
@@ -1243,7 +1243,7 @@ int zzz(A *inst = 0); /* return inst->x + inst->y */
definition, we generate a form that expands to:
The LIN typemap accepts the following $variable references.
-
$in - expands to the name of the parameter being
- applied to this typemap
-
-
$out - expands to the name of the local variable
- assigned to this typemap
-
-
$in_fftype - the foreign function type of the C type.
-
$*in_fftype - the foreign function type of the C type
- with one pointer removed. If there is no pointer, then $*in_fftype
- is the same as $in_fftype.
-
-
$body - very important. Instructs SWIG where
- subsequent code generation steps should be inserted into the
- current typemap. Leaving out a $body reference
- will result in lisp wrappers that do very little by way of
- calling into foreign code. Not recommended.
-
+
$in - expands to the name of the parameter being
+ applied to this typemap
+
+
$out - expands to the name of the local variable
+ assigned to this typemap
+
+
$in_fftype - the foreign function type of the C type.
+
$*in_fftype - the foreign function type of the C type
+ with one pointer removed. If there is no pointer, then $*in_fftype
+ is the same as $in_fftype.
+
+
$body - very important. Instructs SWIG where
+ subsequent code generation steps should be inserted into the
+ current typemap. Leaving out a $body reference
+ will result in lisp wrappers that do very little by way of
+ calling into foreign code. Not recommended.
+
$lclass - Expands to the CLOS class that
- represents foreign-objects of the return type matching this
- typemap.
-
-
$body - Same as for the LIN map. Place this
- variable where you want the foreign-function call to occur.
-
-
$ldestructor - Expands to the symbol naming the destructor for this
- class ($lclass) of object. Allows you to insert finalization or automatic garbage
- collection into the wrapper code (see default mappings below).
-
+
$lclass - Expands to the CLOS class that
+ represents foreign-objects of the return type matching this
+ typemap.
+
+
$body - Same as for the LIN map. Place this
+ variable where you want the foreign-function call to occur.
+
+
$ldestructor - Expands to the symbol naming the destructor for this
+ class ($lclass) of object. Allows you to insert finalization or automatic garbage
+ collection into the wrapper code (see default mappings below).
+
The Android chapter is fairly short as support for Android is the same as for Java, where the Java Native Interface (JNI) is
used to call from Android Java into C or C++ compiled code.
-Everything in the Java chapter applies to generating code for access from Android Java code.
+Everything in the Java chapter applies to generating code for access from Android Java code.
This chapter contains a few Android specific notes and examples.
-The examples require the Android SDK and Android NDK which can be installed as per instructions in the links.
+The examples require the Android SDK and Android NDK which can be installed as per instructions in the links.
The Eclipse version is not required for these examples as just the command line tools are used (shown for Linux as the host, but Windows will be very similar, if not identical in most places).
Add the SDK tools and NDK tools to your path and create a directory somewhere for your Android projects (adjust PATH as necessary to where you installed the tools):
@@ -76,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.
-
@@ -758,7 +759,7 @@ Note that the 'extend' example is demonstrates the directors feature.
Normally C++ exception handling and the STL is not available by default in the version of g++ shipped with Android, but this example turns these features on as described in the next section.
@@ -379,7 +380,7 @@ rather than directly overwriting the value of the original input object.
SWIG. Backwards compatibility is preserved, but deprecated.
@@ -449,7 +450,7 @@ the arguments violate the constraint condition, a scripting language
exception will be raised. As a result, it is possible to catch bad
values, prevent mysterious program crashes and so on.
+ccache-swig is a compiler cache. It speeds up re-compilation of C/C++/SWIG code
+by caching previous compiles and detecting when the same compile is
+being done again. ccache-swig is ccache plus support for SWIG. ccache
+and ccache-swig are used interchangeably in this document.
+
+Here is a summary of the options to ccache-swig.
+
+
+
+-s show statistics summary
+-z zero statistics
+-c run a cache cleanup
+-C clear the cache completely
+-F <n> set maximum files in cache
+-M <n> set maximum size of cache (use G, M or K)
+-h this help page
+-V print version number
+
+
+These options only apply when you invoke ccache as "ccache-swig". When
+invoked as a compiler none of these options apply. In that case your
+normal compiler options apply and you should refer to your compilers
+documentation.
+
+
+
-h
Print a options summary page
+
+
-s
Print the current statistics summary for the cache. The
+statistics are stored spread across the subdirectories of the
+cache. Using "ccache-swig -s" adds up the statistics across all
+subdirectories and prints the totals.
+
+
-z
Zero the cache statistics.
+
+
-V
Print the ccache version number
+
+
-c
Clean the cache and re-calculate the cache file count and
+size totals. Normally the -c option should not be necessary as ccache
+keeps the cache below the specified limits at runtime and keeps
+statistics up to date on each compile. This option is mostly useful
+if you manually modify the cache contents or believe that the cache
+size statistics may be inaccurate.
+
+
-C
Clear the entire cache, removing all cached files.
+
+
-F <maxfiles>
This sets the maximum number of files allowed in
+the cache. The value is stored inside the cache directory and applies
+to all future compiles. Due to the way the value is stored the actual
+value used is always rounded down to the nearest multiple of 16.
+
+
-M <maxsize>
This sets the maximum cache size. You can specify
+a value in gigabytes, megabytes or kilobytes by appending a G, M or K
+to the value. The default is gigabytes. The actual value stored is
+rounded down to the nearest multiple of 16 kilobytes.
+
+There are two ways to use ccache. You can either prefix your compile
+commands with "ccache-swig" or you can create a symbolic link between
+ccache-swig and the names of your compilers. The first method is most
+convenient if you just want to try out ccache or wish to use it for
+some specific projects. The second method is most useful for when you
+wish to use ccache for all your compiles.
+
+To install for usage by the first method just copy ccache-swig to somewhere
+in your path.
+
+To install for the second method do something like this:
+
+
+This will work as long as /usr/local/bin comes before the path to gcc
+(which is usually in /usr/bin). After installing you may wish to run
+"which gcc" to make sure that the correct link is being used.
+
+Note! Do not use a hard link, use a symbolic link. A hardlink will
+cause "interesting" problems.
+
+When run as a compiler front end ccache usually just takes the same
+command line options as the compiler you are using. The only exception
+to this is the option '--ccache-skip'. That option can be used to tell
+ccache that the next option is definitely not a input filename, and
+should be passed along to the compiler as-is.
+
+The reason this can be important is that ccache does need to parse the
+command line and determine what is an input filename and what is a
+compiler option, as it needs the input filename to determine the name
+of the resulting object file (among other things). The heuristic
+ccache uses in this parse is that any string on the command line that
+exists as a file is treated as an input file name (usually a C
+file). By using --ccache-skip you can force an option to not be
+treated as an input file name and instead be passed along to the
+compiler as a command line option.
+
+ccache uses a number of environment variables to control operation. In
+most cases you won't need any of these as the defaults will be fine.
+
+
+
+
CCACHE_DIR
the CCACHE_DIR environment variable specifies
+where ccache will keep its cached compiler output. The default is
+"$HOME/.ccache".
+
+
CCACHE_TEMPDIR
the CCACHE_TEMPDIR environment variable specifies
+where ccache will put temporary files. The default is the same as
+CCACHE_DIR. Note that the CCACHE_TEMPDIR path must be on the same
+filesystem as the CCACHE_DIR path, so that renames of files between
+the two directories can work.
+
+
CCACHE_LOGFILE
If you set the CCACHE_LOGFILE environment
+variable then ccache will write some log information on cache hits
+and misses in that file. This is useful for tracking down problems.
+
+
CCACHE_VERBOSE
If you set the CCACHE_VERBOSE environment
+variable then ccache will display on stdout all the compiler invocations
+that it makes. This can useful for debugging unexpected problems.
+
+
CCACHE_PATH
You can optionally set CCACHE_PATH to a colon
+separated path where ccache will look for the real compilers. If you
+don't do this then ccache will look for the first executable matching
+the compiler name in the normal PATH that isn't a symbolic link to
+ccache itself.
+
+
CCACHE_CC
You can optionally set CCACHE_CC to force the name
+of the compiler to use. If you don't do this then ccache works it out
+from the command line.
+
+
CCACHE_PREFIX
This option adds a prefix to the command line
+that ccache runs when invoking the compiler. Also see the section
+below on using ccache with distcc.
+
+
CCACHE_DISABLE
If you set the environment variable
+CCACHE_DISABLE then ccache will just call the real compiler,
+bypassing the cache completely.
+
+
CCACHE_READONLY
the CCACHE_READONLY environment variable
+tells ccache to attempt to use existing cached object files, but not
+to try to add anything new to the cache. If you are using this because
+your CCACHE_DIR is read-only, then you may find that you also need to
+set CCACHE_TEMPDIR as otherwise ccache will fail to create the
+temporary files.
+
+
CCACHE_CPP2
If you set the environment variable CCACHE_CPP2
+then ccache will not use the optimisation of avoiding the 2nd call to
+the pre-processor by compiling the pre-processed output that was used
+for finding the hash in the case of a cache miss. This is primarily a
+debugging option, although it is possible that some unusual compilers
+will have problems with the intermediate filename extensions used in
+this optimisation, in which case this option could allow ccache to be
+used.
+
+
CCACHE_NOCOMPRESS
If you set the environment variable
+CCACHE_NOCOMPRESS then there is no compression used on files that go
+into the cache. However, this setting has no effect on how files are
+retrieved from the cache, compressed results will still be usable.
+
+
CCACHE_NOSTATS
If you set the environment variable
+CCACHE_NOSTATS then ccache will not update the statistics files on
+each compile.
+
+
CCACHE_NLEVELS
The environment variable CCACHE_NLEVELS allows
+you to choose the number of levels of hash in the cache directory. The
+default is 2. The minimum is 1 and the maximum is 8.
+
+
CCACHE_HARDLINK
If you set the environment variable
+CCACHE_HARDLINK then ccache will attempt to use hard links from the
+cache directory when creating the compiler output rather than using a
+file copy. Using hard links is faster, but can confuse programs like
+'make' that rely on modification times. Hard links are never made for
+compressed cache files.
+
+
CCACHE_RECACHE
This forces ccache to not use any cached
+results, even if it finds them. New results are still cached, but
+existing cache entries are ignored.
+
+
CCACHE_UMASK
This sets the umask for ccache and all child
+processes (such as the compiler). This is mostly useful when you wish
+to share your cache with other users. Note that this also affects the
+file permissions set on the object files created from your
+compilations.
+
+
CCACHE_HASHDIR
This tells ccache to hash the current working
+directory when calculating the hash that is used to distinguish two
+compiles. This prevents a problem with the storage of the current
+working directory in the debug info of a object file, which can lead
+ccache to give a cached object file that has the working directory in
+the debug info set incorrectly. This option is off by default as the
+incorrect setting of this debug info rarely causes problems. If you
+strike problems with gdb not using the correct directory then enable
+this option.
+
+
CCACHE_UNIFY
If you set the environment variable CCACHE_UNIFY
+then ccache will use the C/C++ unifier when hashing the pre-processor
+output if -g is not used in the compile. The unifier is slower than a
+normal hash, so setting this environment variable loses a little bit
+of speed, but it means that ccache can take advantage of not
+recompiling when the changes to the source code consist of
+reformatting only. Note that using CCACHE_UNIFY changes the hash, so
+cached compiles with CCACHE_UNIFY set cannot be used when
+CCACHE_UNIFY is not set and vice versa. The reason the unifier is off
+by default is that it can give incorrect line number information in
+compiler warning messages.
+
+
CCACHE_EXTENSION
Normally ccache tries to automatically
+determine the extension to use for intermediate C pre-processor files
+based on the type of file being compiled. Unfortunately this sometimes
+doesn't work, for example when using the aCC compiler on HP-UX. On
+systems like this you can use the CCACHE_EXTENSION option to override
+the default. On HP-UX set this environment variable to "i" if you use
+the aCC compiler.
+
+
CCACHE_STRIPC
If you set the environment variable
+CCACHE_STRIPC then ccache will strip the -c option when invoking
+the preprocessor. This option is primarily for the Sun Workshop
+C++ compiler as without this option an unwarranted warning is displayed:
+CC: Warning: "-E" redefines product from "object" to "source (stdout)"
+when -E and -c is used together.
+
+
CCACHE_SWIG
When using SWIG as the compiler and it does not
+have 'swig' in the executable name, then the CCACHE_SWIG environment
+variable needs to be set in order for ccache to work correctly with
+SWIG. The use of CCACHE_CPP2 is also recommended for SWIG due to some
+preprocessor quirks, however, use of CCACHE_CPP2 can often be skipped
+-- check your generated code with and without this option set. Known
+problems are using preprocessor directives within %inline blocks and
+the use of '#pragma SWIG'.
+
+By default ccache has a one gigabyte limit on the cache size and no
+maximum number of files. You can set a different limit using the
+"ccache -M" and "ccache -F" options, which set the size and number of
+files limits.
+
+When these limits are reached ccache will reduce the cache to 20%
+below the numbers you specified in order to avoid doing the cache
+clean operation too often.
+
+By default on most platforms ccache will compress all files it puts
+into the cache
+using the zlib compression. While this involves a negligible
+performance slowdown, it significantly increases the number of files
+that fit in the cache. You can turn off compression setting the
+CCACHE_NOCOMPRESS environment variable.
+
+The basic idea is to detect when you are compiling exactly the same
+code a 2nd time and use the previously compiled output. You detect
+that it is the same code by forming a hash of:
+
+
+
the pre-processor output from running the compiler with -E
+
the command line options
+
the real compilers size and modification time
+
any stderr output generated by the compiler
+
+
+These are hashed using md4 (a strong hash) and a cache file is formed
+based on that hash result. When the same compilation is done a second
+time ccache is able to supply the correct compiler output (including
+all warnings etc) from the cache.
+
+ccache has been carefully written to always produce exactly the same
+compiler output that you would get without the cache. If you ever
+discover a case where ccache changes the output of your compiler then
+please let me know.
+
+distcc is a very useful program for distributing compilation across a
+range of compiler servers. It is often useful to combine distcc with
+ccache, so that compiles that are done are sped up by distcc, but that
+ccache avoids the compile completely where possible.
+
+To use distcc with ccache I recommend using the CCACHE_PREFIX
+option. You just need to set the environment variable CCACHE_PREFIX to
+'distcc' and ccache will prefix the command line used with the
+compiler with the command 'distcc'.
+
+A group of developers can increase the cache hit rate by sharing a
+cache directory. The hard links however cause unwanted side effects,
+as all links to a cached file share the file's modification timestamp.
+This results in false dependencies to be triggered by timestamp-based
+build systems whenever another user links to an existing
+file. Typically, users will see that their libraries and binaries are
+relinked without reason. To share a cache without side effects, the
+following conditions need to be met:
+
+
+
Use the same CCACHE_DIR environment variable setting
+
Unset the CCACHE_HARDLINK environment variable
+
Make sure everyone sets the CCACHE_UMASK environment variable
+ to 002, this ensures that cached files are accessible to everyone in
+ the group.
+
Make sure that all users have write permission in the entire
+ cache directory (and that you trust all users of the shared cache).
+
Make sure that the setgid bit is set on all directories in the
+ cache. This tells the filesystem to inherit group ownership for new
+ directories. The command "chmod g+s `find $CCACHE_DIR -type d`" might
+ be useful for this.
+
Set CCACHE_NOCOMPRESS for all users, if there are users with
+ versions of ccache that do not support compression.
+
+ccache was inspired by the compilercache shell script script written
+by Erik Thiele and I would like to thank him for an excellent piece of
+work. See
+http://www.erikyyy.de/compilercache/
+for the Erik's scripts.
+ccache-swig is a port of the original ccache with support added for use
+with SWIG.
+
+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.
+
+ccache was written by Andrew Tridgell
+http://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
+the SWIG developers on the swig-devel mailing list, see
+http://www.swig.org/mail.html
+
+ccache is released under the GNU General Public License version 2 or
+later. Please see the file COPYING for license details.
+
This chapter gives you a brief overview about the SWIG
@@ -76,10 +77,10 @@ users are welcome to help by adapting the existing container interface files and
as a patch for inclusion in future versions of SWIG.
SWIG parses and identifies the keyword constexpr, but cannot fully utilise it.
@@ -138,7 +139,7 @@ constexpr int YYY = XXX() + 100;
When either of these is used from a target language, a runtime call is made to obtain the underlying constant.
@@ -283,7 +284,7 @@ Note that the default typemap for std::initializer_list does nothing bu
and hence any user supplied typemaps will override it and suppress the warning.
SWIG correctly parses the keyword explicit for operators in addition to constructors now.
@@ -602,37 +603,11 @@ Conversion operators either with or without explicit need renaming to a
them available as a normal proxy method.
-These are partially supported as SWIG will parse these and identify them, however, they are ignored as they are not added to the type system. A warning such as the following is issued:
-
-
-
-
-example.i:13: Warning 342: The 'using' keyword in template aliasing is not fully supported yet.
-
-
-
-
-Similarly for non-template type aliasing:
+A type alias is a statement of the form:
@@ -640,23 +615,44 @@ using PFD = void (*)(double); // New introduced syntax
-A warning will be issued:
+which is equivalent to the old style typedef:
-
-
-example.i:17: Warning 341: The 'using' keyword in type aliasing is not fully supported yet.
-
-
-
-
-
The equivalent old style typedefs can be used as a workaround:
-
typedef void (*PFD)(double); // The old style
-
7.2.17 Unrestricted unions
+
+The following is an example of an alias template:
+
+
Firstly, the actual template is instantiated with a name to be used by the target language, as per any template being wrapped.
+Secondly, the empty template instantiation, %template(), is required for the alias template.
+This second requirement is necessary to add the appropriate instantiated template type into the type system as SWIG does not automatically instantiate templates.
+See the Templates section for more general information on wrapping templates.
+
+
SWIG supports the variadic templates syntax (inside the <>
@@ -692,7 +688,7 @@ initializers) with some limitations. The following code is correctly parsed:
SWIG correctly parses the thread_local keyword. For example, variables
@@ -822,7 +818,7 @@ reachable by the current thread can be defined as:
struct A {
- static thread_local int val;
+ static thread_local int val;
};
thread_local int global_val;
@@ -834,7 +830,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
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.
@@ -862,8 +858,8 @@ For example, the C++ compiler will not compile any code which attempts to use an
@@ -872,12 +868,12 @@ 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.
-
SWIG does not currently wrap or use any of the new threading
@@ -985,7 +981,7 @@ classes introduced (thread, mutex, locks, condition variables, task). The main r
SWIG target languages offer their own threading facilities so there is limited use for them.
@@ -993,7 +989,7 @@ SWIG does not provide library files for the new tuple types yet.
Variadic template support requires further work to provide substantial tuple wrappers.
@@ -1001,14 +997,14 @@ The new hash tables in the STL are unordered_set, unordered_multise
These are not available in SWIG, but in principle should be easily implemented by adapting the current STL containers.
While SWIG could provide wrappers for the new C++11 regular expressions classes, there is little need as the target languages have their own regular expression facilities.
@@ -70,10 +71,10 @@ SWIG C# works equally well on non-Microsoft operating systems such as Linux, Sol
To get the most out of this chapter an understanding of interop is required.
The Microsoft Developer Network (MSDN) has a good reference guide in a section titled "Interop Marshaling".
-Monodoc, available from the Mono project, has a very useful section titled Interop with native libraries.
+Monodoc, available from the Mono project, has a very useful section titled Interop with native libraries.
@@ -133,7 +134,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.
@@ -299,6 +301,9 @@ $*javaclassname -> $*csclassname
$javaclazzname -> $csclazzname
$javainput -> $csinput
$jnicall -> $imcall
+$javainterfacename -> $csinterfacename
+$&javainterfacename -> $&csinterfacename
+$*javainterfacename -> $*csinterfacename
@@ -539,14 +544,18 @@ unless the imclassname attribute is specified in the Cygwin or MinGW environment for automatic configuration of the example makefiles.
-Any one of the three C# compilers (Portable.NET, Mono or Microsoft) can be detected from within a Cygwin or Mingw environment if installed in your path.
+Any one of the C# compilers (Mono or Microsoft) can be detected from within a Cygwin or Mingw environment if installed in your path.
-
@@ -1114,7 +1123,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.
-
@@ -1237,7 +1244,7 @@ SWIGEXPORT void SWIGSTDCALL CSharp_evensonly(int jarg1) {
Multiple catch handlers are generated should there be more than one exception specifications declared.
-
@@ -1384,7 +1391,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.
@@ -1736,11 +1743,11 @@ However, a call from C# to CSharpDefaults.DefaultMethod() will of cours
should pass the call on to CSharpDefaults.DefaultMethod(int)using the C++ default value, as shown above.
-When using multiple modules it is is possible to compile each SWIG generated wrapper
+When using multiple modules it is is possible to compile each SWIG generated wrapper
into a different assembly.
However, by default the generated code may not compile if
generated classes in one assembly use generated classes in another assembly.
@@ -1771,7 +1778,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.
This section includes a few examples of typemaps. For more examples, you
@@ -1779,7 +1786,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
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
@@ -2570,7 +2577,7 @@ demonstrating that the class contains methods calling both unmanaged code -
The following example is an alternative approach to adding managed code to the generated proxy class.
-
20.8.7 Extending proxy classes with additional C# code
The author of TinyCLOS, Gregor Kiczales, describes TinyCLOS as:
- "Tiny CLOS is a Scheme implementation of a `kernelized' CLOS, with a
- metaobject protocol. The implementation is even simpler than
- the simple CLOS found in `The Art of the Metaobject Protocol,'
- weighing in at around 850 lines of code, including (some)
- comments and documentation."
+ "Tiny CLOS is a Scheme implementation of a `kernelized' CLOS, with a
+ metaobject protocol. The implementation is even simpler than
+ the simple CLOS found in `The Art of the Metaobject Protocol,'
+ weighing in at around 850 lines of code, including (some)
+ comments and documentation."
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
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.
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 839c0ec42..74d21960e 100644
--- a/Doc/Manual/Contents.html
+++ b/Doc/Manual/Contents.html
@@ -1,10 +1,12 @@
-
+
@@ -38,7 +39,7 @@ When one of the rules is violated by a script, a runtime exception is
generated rather than having the program continue to execute.
-
@@ -105,20 +106,20 @@ The %contract directive can also be applied to class methods and constr
%contract Foo::bar(int x, int y) {
require:
- x > 0;
+ x > 0;
ensure:
- bar > 0;
+ bar > 0;
}
%contract Foo::Foo(int a) {
require:
- a > 0;
+ a > 0;
}
class Foo {
public:
- Foo(int);
- int bar(int, int);
+ Foo(int);
+ int bar(int, int);
};
@@ -132,7 +133,7 @@ Thus, any contract that you specified for a base class will also be attached to
class Spam : public Foo {
public:
- int bar(int,int); // Gets contract defined for Foo::bar(int,int)
+ int bar(int,int); // Gets contract defined for Foo::bar(int,int)
};
@@ -145,22 +146,22 @@ In addition to this, separate contracts can be applied to both the base class an
%contract Foo::bar(int x, int) {
require:
- x > 0;
+ x > 0;
}
%contract Spam::bar(int, int y) {
require:
- y > 0;
+ y > 0;
}
class Foo {
public:
- int bar(int,int); // Gets Foo::bar contract.
+ int bar(int,int); // Gets Foo::bar contract.
};
class Spam : public Foo {
public:
- int bar(int,int); // Gets Foo::bar and Spam::bar contract
+ int bar(int,int); // Gets Foo::bar and Spam::bar contract
};
@@ -173,7 +174,7 @@ specified for the derived class all must hold. In the above example,
this means that both the arguments to Spam::bar must be positive.
-
@@ -224,7 +225,7 @@ function can be used in contracts. For example:
%contract move(SomeObject *, int direction, in) {
require:
- check_direction(direction);
+ check_direction(direction);
}
#define UP 1
@@ -245,7 +246,7 @@ Alternatively, it can be used in typemaps and other directives. For example:
%aggregate_check(int, check_direction, UP, DOWN, RIGHT, LEFT);
%typemap(check) int direction {
- if (!check_direction($1)) SWIG_exception(SWIG_ValueError, "Bad direction");
+ if (!check_direction($1)) SWIG_exception(SWIG_ValueError, "Bad direction");
}
#define UP 1
@@ -262,7 +263,7 @@ Regrettably, there is no automatic way to perform similar checks with enums valu
release.
@@ -100,7 +101,7 @@ for exception handling. That directive is deprecated--%exception
provides the same functionality, but is substantially more flexible.
-
@@ -319,7 +324,7 @@ critical pieces of code. For example:
%exception {
- ... your exception handler ...
+ ... your exception handler ...
}
/* Define critical operations that can throw exceptions here */
@@ -336,12 +341,12 @@ to specific declaration name. For example:
@@ -405,21 +410,21 @@ to attach exceptions to specific parts of a header file. For example:
// Define a few exception handlers for specific declarations
%exception Object::allocate(int) {
- try {
- $action
- }
- catch (MemoryError) {
- croak("Out of memory");
- }
+ try {
+ $action
+ }
+ catch (MemoryError) {
+ croak("Out of memory");
+ }
}
%exception Object::getitem {
- try {
- $action
- }
- catch (RangeError) {
- croak("Index out of range");
- }
+ try {
+ $action
+ }
+ catch (RangeError) {
+ croak("Index out of range");
+ }
}
...
// Read a raw header file
@@ -437,7 +442,7 @@ declarations. However, it never really worked that well and the new
%exception directive is much better.
-
/* Define a global exception handler */
%feature("except") {
- try {
- $action
- }
- ...
+ try {
+ $action
+ }
+ ...
}
... bunch of declarations ...
@@ -834,7 +839,7 @@ The following are all equivalent:
The syntax in the first variation will generate the { } delimiters used whereas the other variations will not.
-
@@ -875,7 +880,7 @@ In the following example, MyExceptionClass is the name of the Java clas
Further details can be obtained from the Java exception handling section.
-
@@ -1141,7 +1146,7 @@ specifying or not specifying default arguments in a feature is not applicable as
in SWIG-1.3.23 when the approach to wrapping methods with default arguments was changed.
From the D Programming Language web site: D is a systems programming language. Its focus is on combining the power and high performance of C and C++ with the programmer productivity of modern languages like Ruby and Python. [...] The D language is statically typed and compiles directly to machine code. As such, it is not very surprising that D is able to directly interface with C libraries. Why would a SWIG module for D be needed then in the first place?
@@ -50,10 +50,10 @@
While these issues can be worked around relatively easy by hand-coding a thin wrapper layer around the C library in question, there is another issue where writing wrapper code per hand is not feasible: C++ libraries. D did not support interfacing to C++ in version 1 at all, and even if extern(C++) has been added to D2, the support is still very limited, and a custom wrapper layer is still required in many cases.
-
To help addressing these issues, the SWIG C# module has been forked to support D. Is has evolved quite a lot since then, but there are still many similarities, so if you do not find what you are looking for on this page, it might be worth having a look at the chapter on C# (and also on Java, since the C# module was in turn forked from it).
+
To help addressing these issues, the SWIG C# module has been forked to support D. Is has evolved quite a lot since then, but there are still many similarities, so if you do not find what you are looking for on this page, it might be worth having a look at the chapter on C# (and also on Java, since the C# module was in turn forked from it).
To activate the D module, pass the -d option to SWIG at the command line. The same standard command line switches as with any other language module are available, plus the following D specific ones:
@@ -64,7 +64,7 @@
By default, SWIG generates code for D1/Tango. Use the -d2 flag to target D2/Phobos instead.
-
-splitproxy
+
-splitproxy
By default, SWIG generates two D modules: the proxy module, named like the source module (either specified via the %module directive or via the module command line switch), which contains all the proxy classes, functions, enums, etc., and the intermediary module (named like the proxy module, but suffixed with _im), which contains all the extern(C) function declarations and other private parts only used internally by the proxy module.
If the split proxy mode is enabled by passing this switch at the command line, all proxy classes and enums are emitted to their own D module instead. The main proxy module only contains free functions and constants in this case.
Mapping of types between the C/C++ library, the C/C++ library wrapper exposing the C functions, the D wrapper module importing these functions and the D proxy code.
@@ -120,26 +120,26 @@
The ctype typemap is used to determine the types to use in the C wrapper functions. The types from the imtype typemap are used in the extern(C) declarations of these functions in the intermediary D module. The dtype typemap contains the D types used in the D proxy module/class.
Used for converting between the types for C/C++ and D when generating the code for the wrapper functions (on the C++ side).
-
The code from the in typemap is used to convert arguments to the C wrapper function to the type used in the wrapped code (ctype->original C++ type), the out typemap is utilized to convert values from the wrapped code to wrapper function return types (original C++ type->ctype).
+
The code from the in typemap is used to convert arguments to the C wrapper function to the type used in the wrapped code (ctype->original C++ type), the out typemap is utilized to convert values from the wrapped code to wrapper function return types (original C++ type->ctype).
The directorin typemap is used to convert parameters to the type used in the D director callback function, its return value is processed by directorout (see below).
Typemaps for code generation in D proxy and type wrapper classes.
-
The din typemap is used for converting function parameter types from the type used in the proxy module or class to the type used in the intermediary D module (the $dinput macro is replaced). To inject further parameter processing code before or after the call to the intermediary layer, the pre, post and terminator attributes can be used (please refer to the C# date marshalling example for more information on these).
+
The din typemap is used for converting function parameter types from the type used in the proxy module or class to the type used in the intermediary D module (the $dinput macro is replaced). To inject further parameter processing code before or after the call to the intermediary layer, the pre, post and terminator attributes can be used (please refer to the C# date marshalling example for more information on these).
-
The dout typemap is used for converting function return values from the return type used in the intermediary D module to the type returned by the proxy function. The $excode special variable in dout typemaps is replaced by the excode typemap attribute code if the method can throw any exceptions from unmanaged code, otherwise by nothing (the $imcall and $owner macros are replaced).
+
The dout typemap is used for converting function return values from the return type used in the intermediary D module to the type returned by the proxy function. The $excode special variable in dout typemaps is replaced by the excode typemap attribute code if the method can throw any exceptions from unmanaged code, otherwise by nothing (the $imcall and $owner macros are replaced).
-
The code from the ddirectorin and ddirectorout typemaps is used for conversion in director callback functions. Arguments are converted to the type used in the proxy class method they are calling by using the code from ddirectorin, the proxy class method return value is converted to the type the C++ code expects via the ddirectorout typemap (the $dcall and $winput macros are replaced).
+
The code from the ddirectorin and ddirectorout typemaps is used for conversion in director callback functions. Arguments are converted to the type used in the proxy class method they are calling by using the code from ddirectorin, the proxy class method return value is converted to the type the C++ code expects via the ddirectorout typemap (the $dcall and $winput macros are replaced).
The full chain of type conversions when a director callback is invoked looks like this:
@@ -157,13 +157,13 @@
dtype DClass.method(dtype a)
-
Because, unlike many scripting languages supported by SWIG, D does not need any dynamic dispatch helper to access an overloaded function, the purpose of these is merely to issue a warning for overloaded C++ functions that cannot be overloaded in D (as more than one C++ type maps to a single D type).
These typemaps are used for generating the skeleton of proxy classes for C++ types.
@@ -172,10 +172,10 @@
Using dcode and dimports, you can specify additional D code which will be emitted into the class body respectively the imports section of the D module the class is written to.
-
dconstructor, ddestructor, ddispose and ddispose_derived are used to generate the class constructor, destructor and dispose() method, respectively. The auxiliary code for handling the pointer to the C++ object is stored in dbody and dbody_derived. You can override them for specific types.
+
dconstructor, ddestructor, ddispose and ddispose_derived are used to generate the class constructor, destructor and dispose() method, respectively. The auxiliary code for handling the pointer to the C++ object is stored in dbody and dbody_derived. You can override them for specific types.
The standard SWIG special variables are available for use within typemaps as described in the Typemaps documentation, for example $1, $input, $result etc.
@@ -197,7 +197,7 @@
$null
In code inserted into the generated C/C++ wrapper functions, this variable is replaced by either 0 or nothing at all, depending on whether the function has a return value or not. It can be used to bail out early e.g. in case of errors (return $null;).
-
$dinput (C#: $csinput)
+
$dinput (C#: $csinput)
This variable is used in din typemaps and is replaced by the expression which is to be passed to C/C++.
These variables are used in dout typemaps. $imcall contains the call to the intermediary module which provides the value to be used, and $owner signals if the caller is responsible for managing the object lifetime (that is, if the called method is a constructor or has been marked via %newobject).
These variables are used in the director-specific typemaps ddirectorin and ddirectorout. They are more or less the reverse of the $imcall and $dinput macros: $dcall contains the invocation of the D proxy method of which the return value is to be passed back to C++, $winput contains the parameter value from C++.
+
These variables are used in the director-specific typemaps ddirectorin and ddirectorout. They are more or less the reverse of the $imcall and $dinput macros: $dcall contains the invocation of the D proxy method of which the return value is to be passed back to C++, $winput contains the parameter value from C++.
$excode
This variable is used in dout and dconstructor typemaps and is filled with the contents of the excode typemap attribute if an exception could be thrown from the C++ side. See the C# documentation for details.
@@ -263,7 +264,7 @@ SomeClass bar() {
-
$importtype(SomeDType)
+
$importtype(SomeDType)
This macro is used in the dimports typemap if a dependency on another D type generated by SWIG is added by a custom typemap.
Out of the box, C++ exceptions are fundamentally incompatible to their equivalent in the D world and cannot simply be propagated to a calling D method. There is, however, an easy way to solve this problem: Just catch the exception in the C/C++ wrapper layer, pass the contents to D, and make the wrapper code rethrow the exception in the D world.
@@ -374,7 +375,7 @@ struct A {
As this feature is implemented in exactly the same way it is for C#, please see the C# documentation for a more detailed explanation.
When the directors feature is activated, SWIG generates extra code on both the C++ and the D side to enable cross-language polymorphism. Essentially, this means that if you subclass a proxy class in D, C++ code can access any overridden virtual methods just as if you created a derived class in C++.
By default, SWIG flattens all C++ namespaces into a single target language namespace, but as for Java and C#, the nspace feature is supported for D. If it is active, C++ namespaces are mapped to D packages/modules. Note, however, that like for the other languages, free variables and functions are not supported yet; currently, they are all allows written to the main proxy D module.
Contrary to many of the scripting languages supported by SWIG, D fully supports C-style pointers. The D module thus includes a custom mechanism to wrap C pointers directly as D pointers where applicable, that is, if the type that is pointed to is represented the same in C and D (on the bit-level), dubbed a primitive type below.
@@ -404,7 +405,7 @@ struct A {
To determine if a type should be considered primitive, the cprimitive attribute on its dtype attribute is used. For example, the dtype typemap for float has cprimitive="1", so the code from the nativepointer attribute is taken into account e.g. for float ** or the function pointer float (*)(float *).
The D module comes with basic operator overloading support for both D1 and D2. There are, however, a few limitations arising from conceptual differences between C++ and D:
@@ -416,7 +417,7 @@ struct A {
There are also some cases where the operators can be translated to D, but the differences in the implementation details are big enough that a rather involved scheme would be required for automatic wrapping them, which has not been implemented yet. This affects, for example, the array subscript operator, [], in combination with assignments - while operator [] in C++ simply returns a reference which is then written to, D resorts to a separate opIndexAssign method -, or implicit casting (which was introduced in D2 via alias this). Despite the lack of automatic support, manually handling these cases should be perfectly possible.
As with any other language, the SWIG test-suite can be built for D using the *-d-test-suite targets of the top-level Makefile. By default, D1 is targeted, to build it with D2, use the optional D_VERSION variable, e.g. make check-d-test-suite D_VERSION=2.
@@ -424,14 +425,14 @@ struct A {
Note: If you want to use GDC on Linux or another platform which requires you to link libdl for dynamically loading the shared library, you might have to add -ldl manually to the d_compile target in Examples/Makefile, because GDC does not currently honor the pragma(lib,...) statement.
There are no D-specific typemap examples yet. However, with the above name comparison table, you should be able to get an idea what can be done by looking at the corresponding C# section.
There are a couple of features which are not implemented yet, but would be very useful and might be added in the near future:
diff --git a/Doc/Manual/Extending.html b/Doc/Manual/Extending.html
index 59c63403d..798a1adb9 100644
--- a/Doc/Manual/Extending.html
+++ b/Doc/Manual/Extending.html
@@ -1,12 +1,13 @@
-
+
Extending SWIG to support new languages
+
-
@@ -91,7 +92,7 @@ Also, this chapter is not meant to be a hand-holding tutorial. As a starting po
you should probably look at one of SWIG's existing modules.
@@ -158,7 +159,7 @@ role in making the system work. For example, both typemaps and declaration anno
based on pattern matching and interact heavily with the underlying type system.
To iterate over the elements of a list or a hash table, the following functions are used:
@@ -1380,21 +1381,21 @@ List *l = (some list);
Iterator i;
for (i = First(l); i.item; i = Next(i)) {
- Printf(stdout,"%s\n", i.item);
+ Printf(stdout,"%s\n", i.item);
}
Hash *h = (some hash);
Iterator j;
for (j = First(j); j.item; j= Next(j)) {
- Printf(stdout,"%s : %s\n", j.key, j.item);
+ Printf(stdout,"%s : %s\n", j.key, j.item);
}
-
Special I/O functions are used for all internal I/O. These operations
@@ -1516,7 +1517,7 @@ common to see small code fragments of code generated using code like this:
String *s = NewString("");
Printf(s,"Hello\n");
for (i = 0; i < 10; i++) {
- Printf(s,"%d\n", i);
+ Printf(s,"%d\n", i);
}
...
/* Print string into a file */
@@ -1528,7 +1529,7 @@ Printf(f, "%s\n", s);
Similarly, the preprocessor and parser all operate on string-files.
-
Parse trees are built as collections of hash tables. Each node is a hash table in which
@@ -1662,7 +1663,7 @@ Deletes a node from the parse tree. Deletion reconnects siblings and properly u
the parent so that sibling nodes are unaffected.
-
@@ -1788,7 +1789,7 @@ pointers, references, and pointers to members. A detailed discussion of
type theory is impossible here. However, let's cover the highlights.
@@ -2470,7 +2471,7 @@ the parsing of command line options, all aspects of code generation are controll
different methods of the Language that must be defined by your module.
@@ -2533,7 +2534,7 @@ also return a pointer to the base class (Language) so that only the int
-Save the code for your language module in a file named "python.cxx" and.
+Save the code for your language module in a file named "python.cxx" and
place this file in the Source/Modules directory of the SWIG distribution.
To ensure that your module is compiled into SWIG along with the other language modules,
modify the file Source/Modules/Makefile.am to include the additional source
@@ -2578,7 +2579,7 @@ that activates your module. For example, swig -python foo.i. The
messages from your new module should appear.
@@ -3306,7 +3307,7 @@ It is therefore essential that the runtime tests are written in a manner that di
but error/exception out with an error message on stderr on failure.
@@ -3498,7 +3499,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.
@@ -3611,7 +3612,7 @@ The generated C/C++ code should also follow this style as close as possible. How
should be avoided as unlike the SWIG developers, users will never have consistent tab settings.
@@ -3638,7 +3639,7 @@ There are various command line options which can aid debugging a SWIG interface
The complete list of command line options for SWIG are available by running swig -help.
-Go is a compiled language, not a scripting language. However, it does
-not support direct calling of functions written in C/C++. The cgo
-program may be used to generate wrappers to call C code from Go, but
-there is no convenient way to call C++ code. SWIG fills this gap.
+Go does not support direct calling of functions written in C/C++. The
+cgo program may be used to generate
+wrappers to call C code from Go, but there is no convenient way to call C++
+code. SWIG fills this gap.
-There are (at least) two different Go compilers. One is the gc
-compiler, normally invoked via the go tool. The other
-is the gccgo compiler, which is a frontend to the gcc compiler suite.
-The interface to C/C++ code is completely different for the two Go
-compilers. SWIG supports both, selected by a command line option.
+There are (at least) two different Go compilers. The first is the gc compiler
+of the Go distribution, normally
+invoked via the go tool.
+The second Go compiler is the
+gccgo compiler, which is a frontend to the GCC compiler suite.
+The interface to C/C++ code is completely different for the two Go compilers.
+SWIG supports both Go compilers, selected by the -gccgo command line
+option.
-Because Go is a type-safe compiled language, SWIG's runtime type
-checking and runtime library are not used with Go. This should be
-borne in mind when reading the rest of the SWIG documentation.
+Go is a type-safe compiled language and the wrapper code generated by SWIG is
+type-safe as well. In case of type issues the build will fail and hence SWIG's
+runtime library and
+runtime type checking
+are not used.
-The examples in the 2nd link are shipped with the SWIG distribution under the Examples/go directory.
+Please note that the examples in the SWIG source tree use makefiles with the .i
+SWIG interface file extension for backwards compatibility with Go 1.
-To generate Go code, use the -go option with SWIG. By
-default SWIG will generate code for the gc compilers. To generate
-code for gccgo, you should also use the -gccgo option.
+Most Go programs are built using the go
+tool. Since Go 1.1 the go tool has support for SWIG. To use it, give your
+SWIG interface file the extension .swig (for C code) or .swigcxx (for C++ code).
+Put that file in a GOPATH/src directory as usual for Go sources. Put other
+C/C++ code in the same directory with extensions of .c and .cxx. The
+go build and go install commands will automatically run SWIG
+for you and compile the generated wrapper code. To check the SWIG command line
+options the go tool uses run go build -x. To access the automatically
+generated files run go build -work. You'll find the files under the
+temporary WORK directory.
-
23.3.1 Additional Commandline Options
+
+To manually generate and compile C/C++ wrapper code for Go, use the -go
+option with SWIG. By default SWIG will generate code for the Go compiler of the
+Go distribution. To generate code for gccgo, you should also use the
+-gccgo option.
+
+
+
+When using the -cgo option, SWIG will generate files that can be used
+directly by go build. Starting with the Go 1.5 distribution the
+-cgo option has to be given. Put your SWIG interface file in a
+directory under GOPATH/src, and give it a name that does not end in the
+.swig or .swigcxx extension. Typically the SWIG interface file extension is .i
+in this case.
+
+
+
+% swig -go -cgo example.i
+% go install
+
+
+
+You will now have a Go package that you can import from other Go packages as
+usual.
+
+
+
+To use SWIG without the -cgo option, more steps are required. Recall
+that this only works with Go versions before 1.5. When using Go version 1.2 or
+later, or when using gccgo, the code generated by SWIG can be linked directly
+into the Go program. A typical command sequence when using the Go compiler of
+the Go distribution would look like this:
+
+
+
+% swig -go example.i
+% gcc -c code.c # The C library being wrapped.
+% gcc -c example_wrap.c
+% go tool 6g example.go
+% go tool 6c example_gc.c
+% go tool pack grc example.a example.6 example_gc.6 code.o example_wrap.o
+% go tool 6g main.go
+% go tool 6l main.6
+
+
+
+You can also put the wrapped code into a shared library, and when using the Go
+versions before 1.2 this is the only supported option. A typical command
+sequence for this approach would look like this:
+
+
+
+% swig -go -use-shlib example.i
+% gcc -c -fpic example.c
+% gcc -c -fpic example_wrap.c
+% gcc -shared example.o example_wrap.o -o example.so
+% go tool 6g example.go
+% go tool 6c example_gc.c
+% go tool pack grc example.a example.6 example_gc.6
+% go tool 6g main.go # your code, not generated by SWIG
+% go tool 6l main.6
+
@@ -106,9 +193,9 @@ also be seen by using:
swig -go -help
-
+
-
Go specific options
+
Go-specific options
@@ -134,7 +221,7 @@ swig -go -help
-gccgo
Generate code for gccgo. The default is to generate code for
- the gc compiler.
+ the Go compiler of the Go distribution.
@@ -146,8 +233,8 @@ swig -go -help
-use-shlib
Tell SWIG to emit code that uses a shared library. This is only
- meaningful for the gc compiler, which needs to know at compile time
- whether a shared library will be used.
+ meaningful for the Go compiler of the Go distribution, which needs to know at
+ compile time whether a shared library will be used.
@@ -155,9 +242,9 @@ swig -go -help
Set the runtime name of the shared library that the dynamic linker
should include at runtime. The default is the package name with
".so" appended. This is only used when generating code for
- the gc compiler; when using gccgo, the equivalent name will be taken from
- the -soname option passed to the linker. Using this
- option implies the -use-shlib option.
+ the Go compiler of the Go distribution; when using gccgo, the equivalent name
+ will be taken from the -soname option passed to the linker.
+ Using this option implies the -use-shlib option.
There are two different approaches to generating output files,
+
There are two different approaches to generating wrapper files,
controlled by SWIG's -cgo option. The -cgo option
works with Go version 1.2 or later. It is required when using Go
version 1.5 or later.
With or without the -cgo option, SWIG will generate the
- following files when generating Go code:
+ following files when generating wrapper code:
@@ -219,72 +307,8 @@ combined with the compiled MODULE.go using go tool pack.
-
-Most Go programs are built using the go tool. The go tool has limited
-support for SWIG. To use it, put your SWIG interface into a file with
-the extension .swig, or, if you are wrapping C++ code, .swigcxx. Put
-that file in a GOPATH/src directory as usual for Go sources. Put
-other interface code in the same directory with extensions of .c and
-.cxx. The go build and go install commands will
-automatically run SWIG for you and will build the interface code.
-
-
-You can also use SWIG directly yourself. When using
-the -cgo option, SWIG will generate files that can be used
-directly by go build. Put your SWIG input file in a
-directory under GOPATH/src, and give it a name that does not end in
-.swig or .swigcxx.
-
-
-
-% swig -go -cgo example.i
-% go install
-
-
-
-You will now have a Go package that you can import from other Go
-packages as usual.
-
-
-
-To use SWIG without the -cgo option, more steps are required.
-Recall that this only works with Go versions before 1.5. When using
-Go version 1.2 or later, or when using gccgo, the code generated by
-SWIG can be linked directly into the Go program. A typical command
-sequence when using the gc compiler would look like this:
-
-
-
-% swig -go example.i
-% gcc -c code.c # The C library being wrapped.
-% gcc -c example_wrap.c
-% go tool 6g example.go
-% go tool 6c example_gc.c
-% go tool pack grc example.a example.6 example_gc.6 code.o example_wrap.o
-% go tool 6g main.go
-% go tool 6l main.6
-
-
-
-You can also put the wrapped code into a shared library, and when
-using the Go versions before 1.2 this is the only supported option. A
-typical command sequence for this approach would look like this:
-
-
-
-% swig -go -use-shlib example.i
-% gcc -c -fpic example.c
-% gcc -c -fpic example_wrap.c
-% gcc -shared example.o example_wrap.o -o example.so
-% go tool 6g example.go
-% go tool 6c example_gc.c
-% go tool pack grc example.a example.6 example_gc.6
-% go tool 6g main.go # your code, not generated by SWIG
-% go tool 6l main.6
-
@@ -422,7 +446,7 @@ type MyClass interface {
MyMethod() int
}
-MyClassMyFactoryFunction() MyClass {
+func MyClassMyFactoryFunction() MyClass {
// swig magic here
}
@@ -432,7 +456,7 @@ returns a go interface. If the returned pointer can be null, you can check
for this by calling the Swigcptr() method.
func UseClassName(...) ... {
- o := NewClassName(...)
- defer DeleteClassName(o)
- // Use the ClassName object
- return ...
+ o := NewClassName(...)
+ defer DeleteClassName(o)
+ // Use the ClassName object
+ return ...
}
@@ -471,17 +495,17 @@ that creates a C++ object and functions called by this function. Example:
func WithClassName(constructor args, f func(ClassName, ...interface{}) error, data ...interface{}) error {
- o := NewClassName(constructor args)
- defer DeleteClassName(o)
- return f(o, data...)
+ o := NewClassName(constructor args)
+ defer DeleteClassName(o)
+ return f(o, data...)
}
func UseClassName(o ClassName, data ...interface{}) (err error) {
- // Use the ClassName object and additional data and return error.
+ // Use the ClassName object and additional data and return error.
}
func main() {
- WithClassName(constructor args, UseClassName, additional data)
+ WithClassName(constructor args, UseClassName, additional data)
}
@@ -523,38 +547,38 @@ problematic with C++ code that uses thread-local storage.
import (
- "runtime"
- "wrap" // SWIG generated wrapper code
+ "runtime"
+ "wrap" // SWIG generated wrapper code
)
type GoClassName struct {
- wcn wrap.ClassName
+ wcn wrap.ClassName
}
func NewGoClassName() *GoClassName {
- o := &GoClassName{wcn: wrap.NewClassName()}
- runtime.SetFinalizer(o, deleteGoClassName)
- return o
+ o := &GoClassName{wcn: wrap.NewClassName()}
+ runtime.SetFinalizer(o, deleteGoClassName)
+ return o
}
func deleteGoClassName(o *GoClassName) {
- // Runs typically in a different OS thread!
- wrap.DeleteClassName(o.wcn)
- o.wcn = nil
+ // Runs typically in a different OS thread!
+ wrap.DeleteClassName(o.wcn)
+ o.wcn = nil
}
func (o *GoClassName) Close() {
- // If the C++ object has a Close method.
- o.wcn.Close()
+ // If the C++ object has a Close method.
+ o.wcn.Close()
- // If the GoClassName object is no longer in an usable state.
- runtime.SetFinalizer(o, nil) // Remove finalizer.
- deleteGoClassName() // Free the C++ object.
+ // If the GoClassName object is no longer in an usable state.
+ runtime.SetFinalizer(o, nil) // Remove finalizer.
+ deleteGoClassName() // Free the C++ object.
}
@@ -574,50 +598,551 @@ In order to use C++ templates in Go, you must tell SWIG to create
wrappers for a particular template instantation. To do this, use
the %template directive.
-
-SWIG's director feature permits a Go type to act as the subclass of a
-C++ class with virtual methods. This is complicated by the fact that
-C++ and Go define inheritance differently. In Go, structs can inherit
-methods via anonymous field embedding. However, when a method is
-called for an embedded struct, if that method calls any other methods,
-they are called for the embedded struct, not for the original type.
-Therefore, SWIG must use Go interfaces to represent C++ inheritance.
+SWIG's director feature permits a Go type to act as the subclass of a C++ class.
+This is complicated by the fact that C++ and Go define inheritance differently.
+SWIG normally represents the C++ class inheritance automatically in Go via
+interfaces but with a Go type representing a subclass of a C++ class some manual
+work is necessary.
-In order to use the director feature in Go, you must define a type in
-your Go code. You must then add methods for the type. Define a
-method in Go for each C++ virtual function that you want to override.
-You must then create a value of your new type, and pass a pointer to
-it to the function NewDirectorClassName,
-where ClassName is the name of the C++ class. That will
-return a value of type ClassName.
+This subchapter gives a step by step guide how to properly sublass a C++ class
+with a Go type. In general it is strongly recommended to follow this guide
+completely to avoid common pitfalls with directors in Go.
+
+The step by step guide is based on two example C++ classes. FooBarAbstract is
+an abstract C++ class and the FooBarCpp class inherits from it. This guide
+explains how to implement a FooBarGo class similar to the FooBarCpp class.
+The director feature is disabled by default. To use directors you must make two
+changes to the interface file. First, add the "directors" option to the %module
+directive, like this:
+
+
+
+
+%module(directors="1") modulename
+
+
+
+
+Second, you must use the %feature("director") directive to tell SWIG which
+classes should get directors. In the example the FooBarAbstract class needs the
+director feature enabled so that the FooBarGo class can inherit from it, like
+this:
+
+
+
+
+%feature("director") FooBarAbstract;
+
+
+
+
+For a more detailed documentation of the director feature and how to enable or
+disable it for specific classes and virtual methods see SWIG's Java
+documentation on directors.
+
+SWIG creates an additional set of constructor and destructor functions once the
+director feature has been enabled for a C++ class.
+NewDirectorClassName allows overriding virtual methods on the new
+object instance and DeleteDirectorClassName needs to be used to free a
+director object instance created with NewDirectorClassName.
+More on overriding virtual methods follows later in this guide under
+overriding virtual methods.
+
+
+
+The default constructor and destructor functions NewClassName and
+DeleteClassName can still be used as before so that existing code
+doesn't break just because the director feature has been enabled for a C++
+class. The behavior is undefined if the default and director constructor and
+destructor functions get mixed and so great care needs to be taken that only one
+of the constructor and destructor function pairs is used for any object
+instance. Both constructor functions, the default and the director one, return
+the same interface type. This makes it potentially hard to know which
+destructor function, the default or the director one, needs to be called to
+delete an object instance.
+
+
+
+In theory the DirectorInterface method could be used to
+determine if an object instance was created via NewDirectorClassName:
+
-Any call in C++ code to the virtual function will wind up calling the
-method defined in Go. The Go code may of course call other methods on
-itself, and those methods may be defined either in Go or in C++.
+In practice it is strongly recommended to embed a director object
+instance in a Go struct so that a director object instance will be represented
+as a distinct Go type that subclasses a C++ class. For this Go type custom
+constructor and destructor functions take care of the director constructor and
+destructor function calls and the resulting Go class will appear to the user as
+any other SWIG wrapped C++ class. More on properly subclassing a C++ class
+follows later in this guide under subclass via
+embedding.
+In order to override virtual methods on a C++ class with Go methods the
+NewDirectorClassName constructor functions receives a
+DirectorInterface argument. The methods in the
+DirectorInterface are a subset of the public and protected virtual methods
+of the C++ class. If the DirectorInterface contains a method with a
+matching signature to a virtual method of the C++ class then the virtual C++
+method will be overwritten with the Go method. As Go doesn't support protected
+methods all overriden protected virtual C++ methods will be public in Go.
+
+The complete example, including the FooBarGoo class implementation, can
+be found in the end of the guide. In
+this part of the example the virtual methods FooBarAbstract::Foo and
+FooBarAbstract::Bar have been overwritten with Go methods similarly to
+how the FooBarAbstract virtual methods are overwritten by the
+FooBarCpp class.
+
+
+
+The DirectorInterface in the example is implemented by the
+overwrittenMethodsOnFooBarAbstract Go struct type. A pointer to a
+overwrittenMethodsOnFooBarAbstract struct instance will be given to the
+NewDirectorFooBarAbstract constructor function. The constructor return
+value implements the FooBarAbstract interface.
+overwrittenMethodsOnFooBarAbstract could in theory be any Go type but
+in practice a struct is used as it typically contains at least a value of the
+C++ class interface so that the overwritten methods can use the rest of the
+C++ class. If the FooBarGo class would receive additional constructor
+arguments then these would also typically be stored in the
+overwrittenMethodsOnFooBarAbstract struct so that they can be used by
+the Go methods.
+
+Often a virtual method will be overwritten to extend the original behavior of
+the method in the base class. This is also the case for the
+FooBarCpp::Foo method of the example code:
+
+To use base methods the DirectorClassNameMethodName wrapper functions
+are automatically generated by SWIG for public and protected virtual methods.
+The FooBarGo.Foo implementation in the example looks like this:
+
+As previously mentioned in this guide the
+default and director constructor functions return the same interface type. To
+properly subclass a C++ class with a Go type the director object instance
+returned by the NewDirectorClassName constructor function should be
+embedded into a Go struct so that it represents a distinct but compatible type
+in Go's type system. This Go struct should be private and the constructor and
+destructor functions should instead work with a public interface type so that
+the Go class that subclasses a C++ class can be used as a compatible drop in.
+
+
+
+The subclassing part of the FooBarGo class for an example looks like
+this:
+
+The complete example, including the FooBarGoo class implementation, can
+be found in the end of the guide. In
+this part of the example the private fooBarGo struct embeds
+FooBarAbstract which lets the fooBarGo Go type "inherit" all the
+methods of the FooBarAbstract C++ class by means of embedding. The
+public FooBarGo interface type includes the FooBarAbstract
+interface and hence FooBarGo can be used as a drop in replacement for
+FooBarAbstract while the reverse isn't possible and would raise a
+compile time error. Furthemore the constructor and destructor functions
+NewFooBarGo and DeleteFooBarGo take care of all the director
+specifics and to the user the class appears as any other SWIG wrapped C++
+class.
+
+In general all guidelines for C++ class memory
+management apply as well to director classes. One often overlooked
+limitation with runtime.SetFinalizer is that a finalizer doesn't run
+in case of a cycle and director classes typically have a cycle. The cycle
+in the FooBarGo class is here:
+
+In order to be able to use runtime.SetFinalizer nevertheless the
+finalizer needs to be set on something that isn't in a cycle and that references
+the director object instance. In the FooBarGo class example the
+FooBarAbstract director instance can be automatically deleted by setting
+the finalizer on fooBarGo:
+
+Furthermore if runtime.SetFinalizer is in use either the
+DeleteClassName destructor function needs to be removed or the
+fooBarGo struct needs additional data to prevent double deletion. Please
+read the C++ class memory management subchapter
+before using runtime.SetFinalizer to know all of its gotchas.
+
+The complete and annotated FooBarGo class looks like this:
+
+
+
+
+// FooBarGo is a superset of FooBarAbstract and hence FooBarGo can be used as a
+// drop in replacement for FooBarAbstract but the reverse causes a compile time
+// error.
+type FooBarGo interface {
+ FooBarAbstract
+ deleteFooBarAbstract()
+ IsFooBarGo()
+}
+
+// Via embedding fooBarGo "inherits" all methods of FooBarAbstract.
+type fooBarGo struct {
+ FooBarAbstract
+}
+
+func (fbgs *fooBarGo) deleteFooBarAbstract() {
+ DeleteDirectorFooBarAbstract(fbgs.FooBarAbstract)
+}
+
+// The IsFooBarGo method ensures that FooBarGo is a superset of FooBarAbstract.
+// This is also how the class hierarchy gets represented by the SWIG generated
+// wrapper code. For an instance FooBarCpp has the IsFooBarAbstract and
+// IsFooBarCpp methods.
+func (fbgs *fooBarGo) IsFooBarGo() {}
+
+// Go type that defines the DirectorInterface. It contains the Foo and Bar
+// methods that overwrite the respective virtual C++ methods on FooBarAbstract.
+type overwrittenMethodsOnFooBarAbstract struct {
+ // Backlink to FooBarAbstract so that the rest of the class can be used by
+ // the overridden methods.
+ fb FooBarAbstract
+
+ // If additional constructor arguments have been given they are typically
+ // stored here so that the overriden methods can use them.
+}
+
+func (om *overwrittenMethodsOnFooBarAbstract) Foo() string {
+ // DirectorFooBarAbstractFoo calls the base method FooBarAbstract::Foo.
+ return "Go " + DirectorFooBarAbstractFoo(om.fb)
+}
+
+func (om *overwrittenMethodsOnFooBarAbstract) Bar() string {
+ return "Go Bar"
+}
+
+func NewFooBarGo() FooBarGo {
+ // Instantiate FooBarAbstract with selected methods overridden. The methods
+ // that will be overwritten are defined on
+ // overwrittenMethodsOnFooBarAbstract and have a compatible signature to the
+ // respective virtual C++ methods. Furthermore additional constructor
+ // arguments will be typically stored in the
+ // overwrittenMethodsOnFooBarAbstract struct.
+ om := &overwrittenMethodsOnFooBarAbstract{}
+ fb := NewDirectorFooBarAbstract(om)
+ om.fb = fb // Backlink causes cycle as fb.v = om!
+
+ fbgs := &fooBarGo{FooBarAbstract: fb}
+ // The memory of the FooBarAbstract director object instance can be
+ // automatically freed once the FooBarGo instance is garbage collected by
+ // uncommenting the following line. Please make sure to understand the
+ // runtime.SetFinalizer specific gotchas before doing this. Furthemore
+ // DeleteFooBarGo should be deleted if a finalizer is in use or the fooBarGo
+ // struct needs additional data to prevent double deletion.
+ // runtime.SetFinalizer(fbgs, FooBarGo.deleteFooBarAbstract)
+ return fbgs
+}
+
+// Recommended to be removed if runtime.SetFinalizer is in use.
+func DeleteFooBarGo(fbg FooBarGo) {
+ fbg.deleteFooBarAbstract()
+}
+
+
+
+
+Returned string by the FooBarGo.FooBar method is:
+
+
+
+
+Go Foo, Go Bar
+
+
+
+
+For comparison the FooBarCpp class looks like this:
+
@@ -61,7 +61,7 @@ improved performance. This is currently not tested with swig
so your mileage may vary. To be safe set environment variable
GUILE_AUTO_COMPILE to 0 when using swig generated guile code.
-
@@ -69,7 +69,7 @@ There are three different concepts of "module" involved, defined
separately for SWIG, Guile, and Libtool. To avoid horrible confusion,
we explicitly prefix the context, e.g., "guile-module".
-
Guile 1.8 and older could be interfaced using two different api's, the SCM
@@ -80,7 +80,7 @@ or the GH API. The GH interface to guile is deprecated. Read more about why in
version of SWIG that can still generate guile GH wrapper code is 2.0.9. Please
use that version if you really need the GH wrapper code.
-
@@ -88,7 +88,7 @@ Guile support is complicated by a lack of user community cohesiveness,
which manifests in multiple shared-library usage conventions. A set of
policies implementing a usage convention is called a linkage.
-
@@ -193,7 +193,7 @@ placed between the define-module form and the
SWIG_init via a preprocessor define to avoid symbol
clashes. For this case, however, passive linkage is available.
-
Guile used to support an autoloading facility for object-code
@@ -270,7 +270,7 @@ option, SWIG generates an exported module initialization function with
an appropriate name.
-
@@ -295,7 +295,7 @@ my/lib/libfoo.so.X.Y.Z and friends. This scheme is still very
experimental; the (hobbit4d link) conventions are not well understood.
@@ -420,7 +420,7 @@ representing the expected pointer type. See also
If the Scheme object passed was not a SWIG smob representing a compatible
pointer, a wrong-type-arg exception is raised.
-
Garbage collection is a feature of Guile since version 1.6. As SWIG now requires Guile > 1.8,
@@ -453,7 +453,7 @@ is exactly like described in 24.8 Exception Handling
+
For global variables, SWIG creates a single wrapper procedure
@@ -542,7 +542,7 @@ struct members, the procedures (struct-member-get
pointer) and (struct-member-set pointer
value) are not generated.
-
SWIG can also generate classes and generic functions for use with
@@ -688,7 +688,7 @@ Notice that <Foo> is used before it is defined. The fix is to just put th
%import "foo.h" before the %inline block.
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 02a41169a..1c29f4760 100644
--- a/Doc/Manual/Introduction.html
+++ b/Doc/Manual/Introduction.html
@@ -1,12 +1,13 @@
-
+
@@ -71,7 +72,7 @@ small; especially the research and development work that is commonly found
in scientific and engineering projects. However, nowadays SWIG is known to be used in many
large open source and commercial projects.
-
@@ -143,7 +144,7 @@ it provides a wide variety of customization features that let you change almost
every aspect of the language bindings. This is the main reason why SWIG has such a large
user manual ;-).
-
@@ -157,14 +158,16 @@ following C code:
double My_variable = 3.0;
/* Compute factorial of n */
-int fact(int n) {
- if (n <= 1) return 1;
- else return n*fact(n-1);
+int fact(int n) {
+ if (n <= 1)
+ return 1;
+ else
+ return n*fact(n-1);
}
/* Compute n mod m */
int my_mod(int n, int m) {
- return(n % m);
+ return(n % m);
}
@@ -174,7 +177,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) :
-
@@ -199,7 +202,7 @@ module that will be created by SWIG. The %{ %} block
provides a location for inserting additional code, such as C header
files or additional C declarations, into the generated C wrapper code.
-
The swig command produced a new file called
example_wrap.c that should be compiled along with the
example.c file. Most operating systems and scripting
@@ -233,7 +235,7 @@ and variables declared in the SWIG interface. A look at the file
example_wrap.c reveals a hideous mess. However, you
almost never need to worry about it.
-
@@ -360,7 +362,7 @@ interface and reuse the code in other applications. It is also
possible to support different types of interfaces depending on the application.
@@ -383,7 +385,7 @@ 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.
@@ -418,7 +420,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.
@@ -192,7 +198,7 @@ Various customisation tips and techniques using SWIG directives are covered.
The latter sections cover the advanced techniques of using typemaps for complete control of the wrapping process.
@@ -209,10 +215,10 @@ The Java module requires your system to support shared libraries and dynamic loa
This is the commonly used method to load JNI code so your system will more than likely support this.
-Android uses Java JNI and also works with SWIG. Please read the Android chapter in conjunction with this one if you are targeting Android.
+Android uses Java JNI and also works with SWIG. Please read the Android chapter in conjunction with this one if you are targeting Android.
@@ -345,8 +351,6 @@ directory. If that doesn't work, you will need to read the man-pages for
your compiler and linker to get the right set of options. You might also
check the SWIG Wiki for
additional information.
-JNI compilation
-is a useful reference for compiling on different platforms.
@@ -360,7 +364,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.
@@ -461,9 +465,9 @@ If you forget to compile and link in the SWIG wrapper file into your native libr
$ java runme
Exception in thread "main" java.lang.UnsatisfiedLinkError: exampleJNI.gcd(II)I
- at exampleJNI.gcd(Native Method)
- at example.gcd(example.java:12)
- at runme.main(runme.java:18)
+ at exampleJNI.gcd(Native Method)
+ at example.gcd(example.java:12)
+ at runme.main(runme.java:18)
@@ -482,7 +486,7 @@ The following section also contains some C++ specific linking problems and solut
-
25.2.7 Compilation problems and compiling with C++
@@ -543,7 +547,7 @@ You will want to produce a DLL that can be loaded by the Java Virtual Machine.
This section covers the process of using SWIG with Microsoft Visual C++ 6 although the procedure may be similar with other compilers.
In order for everything to work, you will need to have a JDK installed on your machine in order to read the JNI header files.
@@ -582,7 +586,7 @@ To run the native code in the DLL (example.dll), make sure that it is in your pa
If the library fails to load have a look at Dynamic linking problems.
@@ -651,7 +655,7 @@ variables are wrapped with JavaBean type getters and setters and so forth.
This section briefly covers the essential aspects of this wrapping.
-
25.3.1 Modules, packages and generated Java classes
@@ -962,7 +966,7 @@ The final two approaches use simple integers for each enum item.
Before looking at the various approaches for wrapping named C/C++ enums, anonymous enums are considered.
@@ -1105,7 +1109,7 @@ 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
+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
@@ -1119,7 +1123,7 @@ When upgrading to JDK 1.5 or later, proper Java enums could be used instead, wit
The following section details proper Java enum generation.
@@ -1220,7 +1224,7 @@ Note that unlike typesafe enums, this approach requires users to mostly use diff
Thus the upgrade path to proper enums provided in JDK 1.5 is more painful.
@@ -1239,7 +1243,7 @@ SWIG-1.3.21 and earlier versions wrapped all enums using this approach.
The type unsafe approach is preferable to this one and this simple approach is only included for backwards compatibility with these earlier versions of SWIG.
@@ -1619,7 +1623,7 @@ Note that Java does not support multiple inheritance so any multiple inheritance
A warning is given when multiple inheritance is detected and only the first base class is used.
-
25.3.10 Pointers, references, arrays and pass by value
@@ -1674,7 +1678,7 @@ to hold the result and a pointer is returned (Java will release this memory
when the returned object's finalizer is run by the garbage collector).
@@ -1698,7 +1702,7 @@ For spam1 and spam4 above the Java null gets translat
The converse also occurs, that is, NULL pointers are translated into null Java objects when returned from a C/C++ function.
@@ -1872,10 +1876,10 @@ submodules or packages. For example, if you have a file like this,
%module example
namespace foo {
- int fact(int n);
- struct Vector {
- double x,y,z;
- };
+ int fact(int n);
+ struct Vector {
+ double x,y,z;
+ };
};
@@ -1903,11 +1907,11 @@ For example:
%rename(Bar_spam) Bar::spam;
namespace Foo {
- int spam();
+ int spam();
}
namespace Bar {
- int spam();
+ int spam();
}
@@ -1946,7 +1950,7 @@ If the resulting use of the nspace feature and hence packages results in a proxy
you will need to open up the visibility for the pointer constructor and getCPtr method from the default 'protected' to 'public' with the SWIG_JAVABODY_PROXY macro. See Java code typemaps.
@@ -1965,12 +1969,12 @@ For example:
template<class T1, class T2>
struct pair {
- typedef T1 first_type;
- typedef T2 second_type;
- T1 first;
- T2 second;
- pair();
- pair(const T1&, const T2&);
+ typedef T1 first_type;
+ typedef T2 second_type;
+ T1 first;
+ T2 second;
+ pair();
+ pair(const T1&, const T2&);
~pair();
};
@@ -1995,7 +1999,21 @@ Obviously, there is more to template wrapping than shown in this example.
More details can be found in the SWIG and C++ chapter.
+The C++11 standard provides std::shared_ptr which was derived from the Boost
+implementation, boost::shared_ptr.
+Both of these are available for Java in the SWIG library and usage is outlined
+in the shared_ptr smart pointer library section.
+
@@ -2271,7 +2289,7 @@ The jniclasscode pragma is quite useful for adding in a static block fo
%pragma(java) jniclasscode=%{
static {
try {
- System.loadLibrary("example");
+ System.loadLibrary("example");
} catch (UnsatisfiedLinkError e) {
System.err.println("Native code library failed to load. \n" + e);
System.exit(1);
@@ -2296,7 +2314,7 @@ For example, let's change the intermediary JNI class access to just the default
All the methods in the intermediary JNI class will then not be callable outside of the package as the method modifiers have been changed from public access to default access. This is useful if you want to prevent users calling these low level functions.
@@ -2327,7 +2345,7 @@ example.egg(new Foo());
The primary reason for having the module class wrapping the calls in the intermediary JNI class is to implement static type checking. In this case only a Foo can be passed to the egg function, whereas any long can be passed to the egg function in the intermediary JNI class.
@@ -2514,9 +2532,9 @@ change the ownership of an object. For instance, consider code like this:
class Obj {};
class Node {
- Obj *value;
+ Obj *value;
public:
- void set_value(Obj *v) { value = v; }
+ void set_value(Obj *v) { value = v; }
};
@@ -2562,7 +2580,7 @@ However, you can tell the proxy class to manage the memory if you specify the
@@ -2590,7 +2608,7 @@ Now add in the %newobject directive:
class Obj {...};
class Factory {
public:
- static Obj *createObj() { return new Obj(); }
+ static Obj *createObj() { return new Obj(); }
};
@@ -2616,7 +2634,7 @@ and
-
@@ -2641,8 +2659,8 @@ The base class is generated much like any other proxy class seen so far:
public class Base {
- private long swigCPtr;
- protected boolean swigCMemOwn;
+ private transient long swigCPtr;
+ protected transient boolean swigCMemOwn;
protected Base(long cPtr, boolean cMemoryOwn) {
swigCMemOwn = cMemoryOwn;
@@ -2682,7 +2700,7 @@ The Derived class extends Base mirroring the C++ class inherit
public class Derived extends Base {
- private long swigCPtr;
+ private transient long swigCPtr;
protected Derived(long cPtr, boolean cMemoryOwn) {
super(exampleJNI.SWIGDerivedUpcast(cPtr), cMemoryOwn);
@@ -2732,7 +2750,7 @@ However, true cross language polymorphism can be achieved using the 25.4.3.3 Proxy classes and garbage collection
+
@@ -3121,7 +3139,7 @@ The Enumerations section discussed these but om
The following sub-sections detail the various types of enum classes that can be generated.
@@ -3205,7 +3223,7 @@ The swigValue method is used for marshalling in the other direction.
The toString method is overridden so that the enum name is available.
@@ -3283,7 +3301,7 @@ These needn't be generated if the enum being wrapped does not have any initializ
Simpler Java enums for enums without initializers section describes how typemaps can be used to achieve this.
+By default SWIG wraps all C++ classes as Java classes.
+As Java only supports derivation from a single base class, SWIG has to ignore all
+bases except the first when a C++ class inherits from more than one base class.
+However, there is a family of SWIG macros that change the default wrapping and allows a C++ class
+to be wrapped as a Java interface instead of a Java class.
+These macros provide a way to support some sort of multiple inheritance as there is no limit to
+the number of interfaces that a Java class can inherit from.
+
+
+
+When a C++ class is wrapped as a Java interface, a Java proxy class is still needed.
+The swiginterface.i library file provides three macros for marking a C++ class to be
+wrapped as a Java interface.
+There is more than one macro in order to provide a choice for choosing the Java interface and Java proxy names.
+
+
+
+
+
Interface Macro Name
+
Description
+
+
+
%interface(CTYPE)
+
For C++ class CTYPE, proxy class name is unchanged without any suffix added, interface name has SwigInterface added as a suffix.
+
+
+
%interface_impl(CTYPE)
+
For C++ class CTYPE, proxy class name has SwigImpl added as a suffix, interface name has no added suffix.
+
+
+
%interface_custom("PROXY", "INTERFACE", CTYPE)
+
For C++ class CTYPE, proxy class name is given by the string PROXY, interface name is given by the string INTERFACE. The PROXY and INTERFACE names can use the string formatting functions used in %rename.
+
+
+
+
+The table below has a few examples showing the resulting proxy and interface names for a C++ class called Base.
+
+The 2nd last example shows the names used in the string formatting functions.
+The input for PROXY that "%s" expands to is the proxy name, that is, Base.
+The input for INTERFACE that "%s" expands to is the proxy name, that is, BaseProxy.
+
+
+The last example shows rstrip and in this case strips the Proxy suffix and then adds on Interface.
+
+By default all classes are wrapped and are available in Java, but, Derived
+has all bases ignored except the first.
+SWIG generates a warning for the above code:
+
+
+
+
+example.i:10: Warning 813: Warning for Derived, base Base2 ignored.
+Multiple inheritance is not supported in Java.
+
+
+
+
+If we decide to wrap the two base classes as interfaces and add the following before SWIG parses the above example code:
+
+then two interface files are generated, Base1.java and Base2.java in addition to proxy class files, Base1SwigImpl.java and Base2SwigImpl.java.
+The contents of interface file Base1.java for Base1 is shown below:
+
+The proxy class in Base1SwigImpl.java for Base1 is as it would have been if %interface was not used,
+except the name has changed to Base1SwigImpl and it implements the appropriate base:
+
+
+
+
+public class Base1SwigImpl implements Base1 {
+...
+ public long Base1_GetInterfaceCPtr() {
+ return exampleJNI.Base1SwigImpl_Base1_GetInterfaceCPtr(swigCPtr);
+ }
+
+ public void Method1() {
+ exampleJNI.Base1SwigImpl_Method1(swigCPtr, this);
+ }
+...
+}
+
+
+
+
+In fact any class deriving from Base will now implement the interface instead of
+deriving from it (or ignoring the base in the case of multiple base classes).
+Hence the Derived proxy class will now implement both bases:
+
+
+
+
+public class Derived implements Base1, Base2 {
+...
+ public long Base1_GetInterfaceCPtr() {
+ return exampleJNI.Derived_Base1_GetInterfaceCPtr(swigCPtr);
+ }
+
+ public long Base2_GetInterfaceCPtr() {
+ return exampleJNI.Derived_Base2_GetInterfaceCPtr(swigCPtr);
+ }
+
+ public void Method1() {
+ exampleJNI.Derived_Method1(swigCPtr, this);
+ }
+
+ public void Method2() {
+ exampleJNI.Derived_Method2(swigCPtr, this);
+ }
+...
+}
+
+
+
+
+Wherever a class marked as an interface is used, such as the UseBases method in the example,
+the interface name is used as the type in the Java layer:
+
+Note that each Java interface has a method added to obtain the correct C++ pointer for passing to the native function -
+Base1_GetInterfaceCPtr for Base1.
+This method is similar to the getCPtr method in the proxy classes.
+In fact, as shown above in the Derived class, the proxy classes implement
+this generated interface by calling a native method (Derived_Base1_GetInterfaceCPtr)
+which calls an appropriate C++ cast of the pointer up the inheritance chain.
+
+
+
+The interface macros are implemented using the interface feature and typemaps.
+For example:
+
+The feature accepts one attribute called name, which is the name of the Java interface mentioned earlier.
+The INTERFACE_TYPEMAPS macro implements the typemaps and can be viewed in the
+swiginterface.i file and contain
+the usual Java typemaps for generating code plus the javainterfacecode
+typemap which is only used when a class is marked with the interface feature.
+See Java code typemaps for details.
+
@@ -3336,7 +3599,7 @@ The upshot is that C++ classes can be extended in Java and from C++ these extens
Neither C++ code nor Java code needs to know where a particular method is implemented: the combination of proxy classes, director classes, and C wrapper functions transparently takes care of all the cross-language method routing.
@@ -3393,18 +3656,18 @@ In the following, class Bar will get a director class that handles the methods o
%feature("director") Foo;
class Foo {
public:
- virtual void one();
- virtual void two();
+ virtual void one();
+ virtual void two();
};
class Bar: public Foo {
public:
- virtual void three();
+ virtual void three();
};
@@ -3555,7 +3818,7 @@ 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.
@@ -3752,7 +4015,7 @@ may need to be attached to specific methods.
of the "directorthrows" typemaps. In this example, a
generic "directorthrows" typemap is appropriate for all three exceptions - all
take single string constructors. If the exceptions had different constructors,
-it would be neccessary to have separate typemaps for each exception type.
+it would be necessary to have separate typemaps for each exception type.
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.
@@ -62,10 +63,10 @@ Javascript has gone beyond being a browser-based scripting language and with node-webkit there is a platform which uses Google's Chromium as Web-Browser widget and node.js for javascript extensions.
The V8 code that SWIG generates should work with most versions from 3.11.10 up to 3.29.14 and later.
-
Specify the V8 version when running SWIG (e.g. 3.25.30)
+
The API headers for V8 >= 4.3.0 define constants which SWIG can use to
+determine the V8 version it is compiling for. For versions < 4.3.0, you
+need to specify the V8 version when running SWIG. This is specified as a hex
+constant, but the constant is read as pairs of decimal digits, so for V8
+3.25.30 use constant 0x032530. This scheme can't represent components > 99,
+but this constant is only useful for V8 < 4.3.0, and no V8 versions from
+that era had a component > 99. For example:
If you're targetting V8 >= 4.3.0, you would just run swig like so:
+
+
+$ swig -c++ -javascript -v8 example.i
+
This creates a C/C++ source file example_wrap.c or example_wrap.cxx. The generated C source file contains the low-level wrappers that need to be compiled and linked with the rest of your C/C++ application to create an extension module.
The name of the wrapper file is derived from the name of the input file. For example, if the input file is example.i, the name of the wrapper file is example_wrap.c. To change this, you can use the -o option. The wrapped module will export one function which must be called to register the module with the Javascript interpreter. For example, if your module is named example the corresponding initializer for JavascriptCore would be
@@ -109,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++.
-
At the moment, the Javascript generators pass all tests syntactically, i.e., the generated source code compiles. However, there are still remaining runtime issues.
@@ -156,17 +168,17 @@ $ make check-javascript-examples V8_VERSION=0x032530 ENGINE=v8
instanceOf does not work under JSC
-
The primary development environment has been Linux (Ubuntu 12.04). Windows and OSX 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.
+
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.
To install node.js you can download an installer from their web-site for OSX 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.
+
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.
Note: ECMAScript 5, the currently implemented Javascript standard, does not have modules. node.js and other implementations provide this mechanism defined by the CommonJS group. For browsers this is provided by Browserify, for instance.
The common example class defines three classes, Shape, Circle, and Square:
@@ -595,12 +607,12 @@ at emitKey (readline.js:1095:12)
Note: In ECMAScript 5 there is no concept for classes. Instead each function can be used as a constructor function which is executed by the 'new' operator. Furthermore, during construction the key property prototype of the constructor function is used to attach a prototype instance to the created object. A prototype is essentially an object itself that is the first-class delegate of a class used whenever the access to a property of an object fails. The very same prototype instance is shared among all instances of one type. Prototypal inheritance is explained in more detail on in Inheritance and the prototype chain, for instance.
-
The Javascript Module implementation has taken a very different approach compared to other language modules in order to support different Javascript interpreters.
The Javascript module is implemented in Source/Modules/javascript.cxx. It dispatches the code generation to a JSEmitter instance, V8Emitter or JSCEmitter. Additionally there are some helpers: Template, for templated code generation, and JSEmitterState, which is used to manage state information during AST traversal. This rough map shall make it easier to find a way through this huge source file:
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.
Template creates a copy of that string and Template::replace uses Swig's Replaceall to replace variables in the template. Template::trim can be used to eliminate leading and trailing whitespaces. Template::print is used to write the final template string to a Swig DOH (based on Printv). All methods allow chaining.
The Javascript module delegates code generation to a JSEmitter instance. The following extract shows the essential interface:
@@ -859,7 +871,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.
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.
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.
@@ -91,7 +92,7 @@ Set the environment variable to hold an alternative library directory.
The directories that are searched are displayed when using -verbose commandline option.
@@ -103,7 +104,7 @@ pointers as class-like objects. Since these functions provide direct access to
memory, their use is potentially unsafe and you should exercise caution.
struct name {
- name(); // Create pointer object
- ~name(); // Delete pointer object
- void assign(type value); // Assign value
- type value(); // Get value
- type *cast(); // Cast the pointer to original type
- static name *frompointer(type *); // Create class wrapper from existing
- // pointer
+ name(); // Create pointer object
+ ~name(); // Delete pointer object
+ void assign(type value); // Assign value
+ type value(); // Get value
+ type *cast(); // Cast the pointer to original type
+ static name *frompointer(type *); // Create class wrapper from existing
+ // pointer
};
@@ -319,7 +320,7 @@ In this example, the function int_to_uint() would be used to cast type
Note: When working with simple pointers, typemaps can often be used to provide more seamless operation.
-
void print_array(double x[10]) {
- int i;
- for (i = 0; i < 10; i++) {
- printf("[%d] = %g\n", i, x[i]);
- }
+ int i;
+ for (i = 0; i < 10; i++) {
+ printf("[%d] = %g\n", i, x[i]);
+ }
}
@@ -435,13 +436,13 @@ interface is as follows:
struct name {
- name(int nelements); // Create an array
- ~name(); // Delete array
- type getitem(int index); // Return item
- void setitem(int index, type value); // Set item
- type *cast(); // Cast to original type
- static name *frompointer(type *); // Create class wrapper from
- // existing pointer
+ name(int nelements); // Create an array
+ ~name(); // Delete array
+ type getitem(int index); // Return item
+ void setitem(int index, type value); // Set item
+ type *cast(); // Cast to original type
+ static name *frompointer(type *); // Create class wrapper from
+ // existing pointer
};
@@ -497,7 +498,7 @@ you should consider using a special array object rather than a bare pointer.
used with types of char or char *.
-
@@ -821,7 +822,7 @@ interpreter and lead to a crash). Furthermore, the default behavior does
not work well with binary data. Instead, strings are assumed to be NULL-terminated.
@@ -863,7 +864,7 @@ In the wrapper function, the passed string will be expanded to a pointer and len
The (char *STRING, int LENGTH) multi-argument typemap is also available in addition to (char *STRING, size_t LENGTH).
@@ -904,7 +905,7 @@ however, you may need to provide your own "newfree" typemap for other types.
See Object ownership and %newobject for more details.
-
@@ -1501,8 +1503,8 @@ instantiate different versions of vector for the types that you want to
%include "std_vector.i"
namespace std {
- %template(vectori) vector<int>;
- %template(vectord) vector<double>;
+ %template(vectori) vector<int>;
+ %template(vectord) vector<double>;
};
@@ -1552,19 +1554,19 @@ To illustrate the use of this library, consider the following functions:
#include <numeric>
double average(std::vector<int> v) {
- return std::accumulate(v.begin(),v.end(),0.0)/v.size();
+ return std::accumulate(v.begin(),v.end(),0.0)/v.size();
}
std::vector<double> half(const std::vector<double>& v) {
- std::vector<double> w(v);
- for (unsigned int i=0; i<w.size(); i++)
- w[i] /= 2.0;
- return w;
+ std::vector<double> w(v);
+ for (unsigned int i=0; i<w.size(); i++)
+ w[i] /= 2.0;
+ return w;
}
void halve_in_place(std::vector<double>& v) {
- std::transform(v.begin(),v.end(),v.begin(),
- std::bind2nd(std::divides<double>(),2.0));
+ std::transform(v.begin(),v.end(),v.begin(),
+ std::bind2nd(std::divides<double>(),2.0));
}
@@ -1583,8 +1585,8 @@ To wrap with SWIG, you might write the following:
%include "std_vector.i"
// Instantiate templates used by example
namespace std {
- %template(IntVector) vector<int>;
- %template(DoubleVector) vector<double>;
+ %template(IntVector) vector<int>;
+ %template(DoubleVector) vector<double>;
}
// Include the header file with above prototypes
@@ -1643,7 +1645,7 @@ make sure you include the appropriate using or typedef directives. For
%include "std_vector.i"
namespace std {
- %template(IntVector) vector<int>;
+ %template(IntVector) vector<int>;
}
using namespace std;
@@ -1665,7 +1667,7 @@ if you want to make their head explode.
details and the public API exposed to the interpreter vary.
@@ -1715,7 +1717,7 @@ 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.
As we mentioned earlier the ideal way to use SWIG is to use interface
@@ -133,17 +134,16 @@ typedef int days;
struct bar {
short p, q;
- char a, b;
- int *z[1000];
- struct bar * n;
+ char a, b;
+ int *z[1000];
+ struct bar * n;
};
struct bar * my_struct;
struct foo {
- int a;
- struct foo * b[100];
-
+ int a;
+ struct foo * b[100];
};
int pointer_func(void (*ClosureFun)( void* _fun, void* _data, void* _evt ), int p);
@@ -219,19 +219,19 @@ The generated SWIG Code will be:
(cl:defconstant x (cl:ash 5 -1))
(cffi:defcstruct bar
- (p :short)
- (q :short)
- (a :char)
- (b :char)
- (z :pointer)
- (n :pointer))
+ (p :short)
+ (q :short)
+ (a :char)
+ (b :char)
+ (z :pointer)
+ (n :pointer))
(cffi:defcvar ("my_struct" my_struct)
:pointer)
(cffi:defcstruct foo
- (a :int)
- (b :pointer))
+ (a :int)
+ (b :pointer))
(cffi:defcfun ("pointer_func" pointer_func) :int
(ClosureFun :pointer)
@@ -247,9 +247,9 @@ The generated SWIG Code will be:
(array :pointer))
(cffi:defcenum color
- :RED
- :BLUE
- :GREEN)
+ :RED
+ :BLUE
+ :GREEN)
@@ -284,9 +284,11 @@ Let's edit the interface file such that the C type "div_t*" is changed
%feature("export");
%feature("inline") lispsort_double;
-
%feature("intern_function", "my-lispify") lispsort_double;
+%feature("export", package="'some-other-package") lispsort_double;
+
%rename func123 renamed_cool_func;
+
%ignore "pointer_func";
%include "test.h"
@@ -310,12 +312,13 @@ The feature intern_function ensures that all C names are
lispsort_double;, here we are using an additional feature
which allows us to use our lispify function.
-
The export feature allows us to export the symbols. The inline
- feature declaims the declared function as inline. The rename
- directive allows us to change the name(it is useful when
- generating C wrapper code for handling overloaded
- functions). The ignore directive ignores a certain
- declaration.
+
The export feature allows us to export the symbols. If
+ the package argument is given, then the symbol will be exported to
+ the specified Lisp package. The inline feature declaims the
+ declared function as inline. The rename directive allows us to
+ change the name(it is useful when generating C wrapper code for handling
+ overloaded functions). The ignore directive ignores a certain
+ declaration.
There are several other things which are possible, to see some
example of usage of SWIG look at the Lispbuilder and wxCL
@@ -332,12 +335,12 @@ The feature intern_function ensures that all C names are
(cl:export '#.(swig-lispify "x" 'constant))
(cffi:defcstruct #.(swig-lispify "bar" 'classname)
- (#.(swig-lispify "p" 'slotname) :short)
- (#.(swig-lispify "q" 'slotname) :short)
- (#.(swig-lispify "a" 'slotname) :char)
- (#.(swig-lispify "b" 'slotname) :char)
- (#.(swig-lispify "z" 'slotname) :pointer)
- (#.(swig-lispify "n" 'slotname) :pointer))
+ (#.(swig-lispify "p" 'slotname) :short)
+ (#.(swig-lispify "q" 'slotname) :short)
+ (#.(swig-lispify "a" 'slotname) :char)
+ (#.(swig-lispify "b" 'slotname) :char)
+ (#.(swig-lispify "z" 'slotname) :pointer)
+ (#.(swig-lispify "n" 'slotname) :pointer))
(cl:export '#.(swig-lispify "bar" 'classname))
@@ -359,8 +362,8 @@ The feature intern_function ensures that all C names are
(cl:export '#.(swig-lispify "my_struct" 'variable))
(cffi:defcstruct #.(swig-lispify "foo" 'classname)
- (#.(swig-lispify "a" 'slotname) :int)
- (#.(swig-lispify "b" 'slotname) :pointer))
+ (#.(swig-lispify "a" 'slotname) :int)
+ (#.(swig-lispify "b" 'slotname) :pointer))
(cl:export '#.(swig-lispify "foo" 'classname))
@@ -381,18 +384,18 @@ The feature intern_function ensures that all C names are
(n :int)
(array :pointer))
-(cl:export '#.(my-lispify "lispsort_double" 'function))
+(cl:export '#.(my-lispify "lispsort_double" 'function) 'some-other-package)
(cffi:defcenum #.(swig-lispify "color" 'enumname)
- #.(swig-lispify "RED" 'enumvalue :keyword)
- #.(swig-lispify "BLUE" 'enumvalue :keyword)
- #.(swig-lispify "GREEN" 'enumvalue :keyword))
+ #.(swig-lispify "RED" 'enumvalue :keyword)
+ #.(swig-lispify "BLUE" 'enumvalue :keyword)
+ #.(swig-lispify "GREEN" 'enumvalue :keyword))
(cl:export '#.(swig-lispify "color" 'enumname))
-
This feature to SWIG (for CFFI) is very new and still far from
@@ -432,44 +435,41 @@ Various features which were available for C headers can also be used
namespace OpenDemo {
class Test
- {
+ {
public:
- float x;
- // constructors
- Test (void) {x = 0;}
- Test (float X) {x = X;}
+ float x;
+ // constructors
+ Test (void) {x = 0;}
+ Test (float X) {x = X;}
- // vector addition
- Test operator+ (const Test& v) const {return Test (x+v.x);}
+ // vector addition
+ Test operator+ (const Test& v) const {return Test (x+v.x);}
// length squared
- float lengthSquared (void) const {return this->dot (*this);}
+ float lengthSquared (void) const {return this->dot (*this);}
- static float distance (const Test& a, const Test& b){return(a-b).length();}
+ static float distance (const Test& a, const Test& b){return(a-b).length();}
- inline Test parallelComponent (const Test& unitBasis) const {
- return unitBasis * projection;
- }
+ inline Test parallelComponent (const Test& unitBasis) const {
+ return unitBasis * projection;
+ }
- Test setYtoZero (void) const {return Test (this->x);}
+ Test setYtoZero (void) const {return Test (this->x);}
- static const Test zero;
- };
+ static const Test zero;
+ };
+ inline Test operator* (float s, const Test& v) {return v*s;}
- inline Test operator* (float s, const Test& v) {return v*s;}
+ inline std::ostream& operator<< (std::ostream& o, const Test& v)
+ {
+ return o << "(" << v.x << ")";
+ }
-
- inline std::ostream& operator<< (std::ostream& o, const Test& v)
- {
- return o << "(" << v.x << ")";
- }
-
-
- inline Test RandomUnitVectorOnXZPlane (void)
- {
- return RandomVectorInUnitRadiusSphere().setYtoZero().normalize();
- }
+ inline Test RandomUnitVectorOnXZPlane (void)
+ {
+ return RandomVectorInUnitRadiusSphere().setYtoZero().normalize();
+ }
}
The interface used is:
@@ -568,7 +568,7 @@ If you have any questions, suggestions, patches, etc., related to CFFI
module feel free to contact us on the SWIG mailing list, and
also please add a "[CFFI]" tag in the subject line.
-
@@ -638,7 +638,7 @@ swig -clisp -module module-namefile-name
interface file for the CLISP module. The CLISP module tries to
produce code which is both human readable and easily modifyable.
If 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.
+externed functions and variables are created.
-generate-typedef
If this option is given then def-c-type will be used to generate
- shortcuts according to the typedefs in the input.
+shortcuts according to the typedefs in the input.
As mentioned earlier the CLISP bindings generated by SWIG may need
- some modifications. The clisp module creates a lisp file with
- the same name as the module name. This
- lisp file contains a 'defpackage' declaration, with the
- package name same as the module name. This package uses the
- 'common-lisp' and 'ffi' packages. Also, package exports all
- the functions, structures and variables for which an ffi
- binding was generated.
- After generating the defpackage statement, the clisp module also
- sets the default language.
+some modifications. The clisp module creates a lisp file with
+the same name as the module name. This
+lisp file contains a 'defpackage' declaration, with the
+package name same as the module name. This package uses the
+'common-lisp' and 'ffi' packages. Also, package exports all
+the functions, structures and variables for which an ffi
+binding was generated.
+After generating the defpackage statement, the clisp module also
+sets the default language.
struct bar {
- short x, y;
- char a, b;
- int *z[1000];
- struct bar * n;
+ short x, y;
+ char a, b;
+ int *z[1000];
+ struct bar * n;
};
#define max 1000
@@ -795,7 +795,7 @@ struct bar {
@@ -82,14 +83,14 @@ Lua is an extension programming language designed to support general procedural
eLua stands for Embedded Lua (can be thought of as a flavor of Lua) and offers the full implementation of the Lua programming language to the embedded world, extending it with specific features for efficient and portable software embedded development. eLua runs on smaller devices like microcontrollers and provides the full features of the regular Lua desktop version. More information on eLua can be found here: http://www.eluaproject.net
-
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'.
@@ -137,7 +138,7 @@ $ swig -lua -eluac example.i
The -elua option puts all the C function wrappers and variable get/set wrappers in rotables. It also generates a metatable which will control the access to these variables from eLua. It also offers a significant amount of module size compression. On the other hand, the -eluac option puts all the wrappers in a single rotable. With this option, no matter how huge the module, it will consume no additional microcontroller SRAM (crass compression). There is a catch though: Metatables are not generated with -eluac. To access any value from eLua, one must directly call the wrapper function associated with that value.
@@ -201,8 +202,8 @@ int main(int argc,char* argv[])
return 0;
}
L=lua_open();
- luaopen_base(L); // load basic libs (eg. print)
- luaopen_example(L); // load the wrapped module
+ luaopen_base(L); // load basic libs (eg. print)
+ luaopen_example(L); // load the wrapped module
if (luaL_loadfile(L,argv[1])==0) // load and run the file
lua_pcall(L,0,0,0);
else
@@ -249,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
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.
@@ -476,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.
@@ -520,9 +521,9 @@ Enums are exported into a class table. For example, given some enums:
%module example
enum Days { SUNDAY = 0, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY };
struct Test {
- enum { TEST1 = 10, TEST2 = 20 };
+ enum { TEST1 = 10, TEST2 = 20 };
#ifdef __cplusplus // There are no static members in C
- static const int ICONST = 12;
+ static const int ICONST = 12;
#endif
};
@@ -567,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.
-
@@ -644,12 +645,12 @@ Like the pointer in the previous section, this is held as a userdata. However, a
const members of a structure are read-only. Data members can also be forced to be read-only using the immutable directive. As with other immutables, setting attempts will be cause an error. For example:
struct Foo {
- ...
- %immutable;
- int x; // Read-only members
- char *name;
- %mutable;
- ...
+ ...
+ %immutable;
+ int x; // Read-only members
+ char *name;
+ %mutable;
+ ...
};
@@ -660,11 +661,11 @@ When a member of a structure is itself a structure, it is handled as a pointer.
struct Foo {
- int a;
+ int a;
};
struct Bar {
- Foo f;
+ Foo f;
};
@@ -694,8 +695,8 @@ Because the pointer points inside the structure, you can modify the contents and
For eLua with the -eluac option, structure manipulation has to be performed with specific structure functions generated by SWIG. Let's say you have the following structure definition:
struct data {
- int x, y;
- double z;
+ int x, y;
+ double z;
};
> --From eLua
@@ -709,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)
-
@@ -748,8 +749,8 @@ Class data members are accessed in the same manner as C structures. Static class
class Spam {
public:
- static void foo();
- static int bar;
+ static void foo();
+ static int bar;
};
@@ -784,7 +785,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.
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.
@@ -926,7 +927,7 @@ Please refer to the "SWIG and C++" chapter for more information about overloadin
Dealing with the Lua coercion mechanism, the priority is roughly (integers, floats, strings, userdata). But it is better to rename the functions rather than rely upon the ordering.
@@ -1060,7 +1061,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.
@@ -1116,15 +1118,15 @@ 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).
Obviously, there is more to template wrapping than shown in this example. More details can be found in the SWIG and C++ chapter. Some more complicated examples will appear later.
In certain C++ programs, it is common to use classes that have been wrapped by so-called "smart pointers." Generally, this involves the use of a template class that implements operator->() like this:
template<class T> class SmartPtr {
- ...
- T *operator->();
- ...
+ ...
+ T *operator->();
+ ...
}
@@ -1192,8 +1194,8 @@ Then, if you have a class like this,
class Foo {
public:
- int x;
- int bar();
+ int x;
+ int bar();
};
@@ -1227,7 +1229,7 @@ If you ever need to access the underlying pointer returned by operator->(
> f = p:__deref__() -- Returns underlying Foo *
-
If SWIG is launched without -no-old-metatable-bindings option, then it enters backward-compatible mode. While in this mode, it tries
@@ -1481,7 +1483,7 @@ surrounding scope without any prefixing. Pretending that Test2 is a struct, not
>
-
This section explains what typemaps are and how to use them. The default wrapping behaviour of SWIG is enough in most cases. However sometimes SWIG may need a little additional assistance to know which typemap to apply to provide the best wrapping. This section will be explaining how to use typemaps to best effect
A typemap is nothing more than a code generation rule that is attached to a specific C datatype. For example, to convert integers from Lua to C, you might define a typemap like this:
@@ -1535,8 +1537,8 @@ function
%module example
%typemap(in) int {
- $1 = (int) lua_tonumber(L,$input);
- printf("Received an integer : %d\n",$1);
+ $1 = (int) lua_tonumber(L,$input);
+ printf("Received an integer : %d\n",$1);
}
%inline %{
extern int fact(int n);
@@ -1555,7 +1557,7 @@ Received an integer : 6
720
There are many ready written typemaps built into SWIG for all common types (int, float, short, long, char*, enum and more), which SWIG uses automatically, with no effort required on your part.
@@ -1563,17 +1565,17 @@ Received an integer : 6
However for more complex functions which use input/output parameters or arrays, you will need to make use of <typemaps.i>, which contains typemaps for these situations. For example, consider these functions:
void add(int x, int y, int *result) {
- *result = x + y;
+ *result = x + y;
}
int sub(int *x1, int *y1) {
- return *x1-*y1;
+ return *x1-*y1;
}
void swap(int *sx, int *sy) {
- int t=*sx;
- *sx=*sy;
- *sy=t;
+ int t=*sx;
+ *sx=*sy;
+ *sy=t;
}
@@ -1608,7 +1610,7 @@ void swap(int *sx, int *sy);
Note: C++ references must be handled exactly the same way. However SWIG will automatically wrap a const int& as an input parameter (since that it obviously input).
Arrays present a challenge for SWIG, because like pointers SWIG does not know whether these are input or output values, nor
@@ -1672,7 +1674,7 @@ and Lua tables to be 1..N, (the indexing follows the norm for the language). In
Note: SWIG also can support arrays of pointers in a similar manner.
Several C++ libraries use a pointer-pointer functions to create its objects. These functions require a pointer to a pointer which is then filled with the pointer to the new object. Microsoft's COM and DirectX as well as many other libraries have this kind of function. An example is given below:
@@ -1706,7 +1708,7 @@ int Create_Math(iMath** pptr); // its creator (assume it mallocs)
ptr=nil -- the iMath* will be GC'ed as normal
-
This section describes how you can modify SWIG's default wrapping behavior for various C/C++ datatypes using the %typemap directive. This is an advanced topic that assumes familiarity with the Lua C API as well as the material in the "Typemaps" chapter.
@@ -1715,7 +1717,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).
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.
@@ -1728,7 +1730,7 @@ ptr=nil -- the iMath* will be GC'ed as normal
(the syntax for the typecheck is different from the typemap, see typemaps for details).
This section explains the SWIG specific Lua-C API. It does not cover the main Lua-C api, as this is well documented and not worth covering.
@@ -1738,7 +1740,7 @@ ptr=nil -- the iMath* will be GC'ed as normal
This is the standard function used for converting a Lua userdata to a void*. It takes the value at the given index in the Lua state and converts it to a userdata. It will then provide the necessary type checks, confirming that the pointer is compatible with the type given in 'type'. Then finally setting '*ptr' to the pointer.
If flags is set to SWIG_POINTER_DISOWN, this is will clear any ownership flag set on the object.
-The returns a value which can be checked with the macro SWIG_IsOK()
+This returns a value which can be checked with the macro SWIG_IsOK()
@@ -1805,7 +1807,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.
@@ -1843,7 +1845,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.
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)'.
@@ -1994,7 +1996,7 @@ Note: Both the opaque structures (like the FILE*) and normal wrapped classes/str
Note: Operator overloads are basically done in the same way, by adding functions such as '__add' & '__call' to the class' metatable. The current implementation is a bit rough as it will add any member function beginning with '__' into the metatable too, assuming its an operator overload.
diff --git a/Doc/Manual/Makefile b/Doc/Manual/Makefile
index 5112afa33..ee9a0af34 100644
--- a/Doc/Manual/Makefile
+++ b/Doc/Manual/Makefile
@@ -1,15 +1,17 @@
# Makefile for generating the SWIG documentation
#
-# Note that the htmldoc package needs to be installed, but requires patching (using the
-# margin-left.patch file from this directory) in order to correctly generate the pdf docs.
+# Note that the htmldoc package needs to be installed. wkhtmltopdf patched with qt is also required
+# and can be installed from http://wkhtmltopdf.org/downloads.html.
+#
# The .html files are first processed and updated with chapter numbering and anchor names
# are added to the HTML headings using the python scripts. The htmldoc program is then
-# used to generate the PDF document and single page HTML version of the documentation.
+# used to generate the single page HTML version of the documentation.
+# wkhtmltopdf is used to generate the pdf document from the single page html file.
# HTML TIDY (package also known as tidy) is also required and is used as an aid to HTML
# validation.
#
# Additional html validation can be done using the validate target.
-# Additional link checking can be done using the linkchecker target.
+# Additional link checking can be done using the linkchecker1 and linkchecker2 target.
#
# Note the # and " are escaped
@@ -19,31 +21,35 @@ HTMLDOC_OPTIONS = "--book --toclevels 4 --no-numbered --toctitle \"Table of Cont
all: maketoc check generate
-maketoc: CCache.html
+maketoc:
python maketoc.py
+# Use this to regenerate CCache.html should this ever be needed
CCache.html: ../../CCache/ccache.yo
yodl2html -o CCache.html ../../CCache/ccache.yo
+# Tabs in the html files will stop the build as wkhtmltopdf does not expand them correctly - replace them with the appropriate number of tabs
# Use htmltidy to warn about some HTML errors. Note that it is not used to clean/tidy the HTML,
# it is just used as a primitive HTML checker.
# CCache.html is generated by yodl2html and has a few insignificant problems, so we don't put it through tidy
check:
- tidy -errors --gnu-emacs yes -quiet index.html
- tidy -errors --gnu-emacs yes -quiet Sections.html
- all=`sed '/^#/d' chapters | grep -v CCache.html`; for a in $$all; do tidy -errors --gnu-emacs yes -quiet $$a; done;
+ all="index.html Sections.html `sed '/^#/d' chapters | grep -v CCache.html`" && for a in $$all; do echo "Check for tabs $$a" && if grep -P '\t' $$a; then echo "Please delete the tabs from the lines above" && exit 1; fi; done && for a in $$all; do echo "HTML tidy check $$a" && tidy -errors --gnu-emacs yes -quiet $$a; done;
-generate: swightml.book swigpdf.book
+# Note wkhtmltopdf limitations for generating pdf docs:
+# 1)
@@ -242,7 +243,7 @@ can peacefully coexist. So the type structures are separated by the
is empty. Only modules compiled with the same pair will share type information.
@@ -292,7 +293,7 @@ into it. This is very often NOT what you want and it can lead to unexpect
behavior. When working with dynamically loadable modules, you should try to work exclusively with shared libraries.
@@ -300,7 +301,7 @@ Due to the complexity of working with shared libraries and multiple modules, it
an outside reference. John Levine's "Linkers and Loaders" is highly recommended.
@@ -36,12 +36,12 @@ Example interface file:
/* define a macro for the struct creation */
%define handle_ptr(TYPE,NAME)
%typemap(argout) TYPE *NAME{
- Scheme_Object *o = SWIG_NewStructFromPtr($1, $*1_mangle);
- SWIG_APPEND_VALUE(o);
+ Scheme_Object *o = SWIG_NewStructFromPtr($1, $*1_mangle);
+ SWIG_APPEND_VALUE(o);
}
%typemap(in,numinputs=0) TYPE *NAME (TYPE temp) {
- $1 = &temp;
+ $1 = &temp;
}
%enddef
@@ -56,16 +56,16 @@ Then in scheme, you can use regular struct access procedures like
- ; suppose a function created a struct foo as
- ; (define foo (make-diag-cntrs (#x1 #x2 #x3) (make-inspector))
- ; Then you can do
- (format "0x~x" (diag-cntrs-field1 foo))
- (format "0x~x" (diag-cntrs-field2 foo))
- ;etc...
+ ; suppose a function created a struct foo as
+ ; (define foo (make-diag-cntrs (#x1 #x2 #x3) (make-inspector))
+ ; Then you can do
+ (format "0x~x" (diag-cntrs-field1 foo))
+ (format "0x~x" (diag-cntrs-field2 foo))
+ ;etc...
The above requests mzc to create an extension using the CGC garbage-collector. The alternative -- the 3m collector -- has generally better performance, but work is still required for SWIG to emit code which is compatible with it.
@@ -101,7 +102,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.
@@ -124,7 +125,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).
@@ -472,10 +473,10 @@ functions imported from different modules. You must convert values to master
values using the swig_val function before sharing them with another module.
@@ -509,7 +510,7 @@ SWIG can't predict which of these methods will be used in the array,
so you have to specify it for yourself in the form of a typemap.
@@ -830,7 +831,7 @@ In this example, I'll examine the objective caml code involved in providing
an overloaded class. This example is contained in Examples/ocaml/shapes.
@@ -847,9 +848,9 @@ let triangle_class pts ob meth args =
"cover" ->
(match args with
C_list [ x_arg ; y_arg ] ->
- let xa = x_arg as float
- and ya = y_arg as float in
- (point_in_triangle pts xa ya) to bool
+ let xa = x_arg as float
+ and ya = y_arg as float in
+ (point_in_triangle pts xa ya) to bool
| _ -> raise (Failure "cover needs two double arguments."))
| _ -> (invoke ob) meth args ;;
@@ -889,7 +890,7 @@ in a more effortless style in ocaml, while leaving the "engine" part of the
program in C++.
-
@@ -941,7 +942,7 @@ well as a function return value in the same way you provide function arguments,
and to receive arguments the same way you normally receive function returns.
@@ -980,7 +981,7 @@ In the event that you don't specify all of the necessary values, integral
values will read zero, and struct or object returns have undefined results.
As of SWIG 3.0.7, the Octave module is regularly tested with Octave versions 3.2.4, 3.8.1, and 4.0.0.
Use of older Octave versions is not recommended, as these versions are no longer tested with SWIG.
+The SWIG runtime exports the function swig_octave_prereq() for checking the version of Octave.
@@ -95,7 +101,7 @@ The -c++ option is also required when wrapping C++ code:
This creates a C++ source file "example_wrap.cpp". A C++ file is generated even when wrapping C code as Octave is itself written in C++ and requires wrapper code to be in the same language. The generated C++ source file contains the low-level wrappers that need to be compiled and linked with the rest of your C/C++ application (in this case, the gcd implementation) to create an extension module.
@@ -118,7 +124,7 @@ The special name "." loads C global variables into the module namespace, i.e. al
The -opprefix options sets the prefix of the names of global/friend operator functions.
C/C++ pointers are fully supported by SWIG. Furthermore, SWIG has no problem working with incomplete type information. Given a wrapping of the <file.h> interface:
- C/C++ pointers are fully supported by SWIG. Furthermore, SWIG has no problem working with incomplete type information. Given a wrapping of the <file.h> interface:
+ C/C++ pointers are fully supported by SWIG. Furthermore, SWIG has no problem working with incomplete type information. Given a wrapping of the <file.h> interface:
%module swigexample
@@ -350,7 +356,7 @@ octave:2> f=swigexample.fopen("not there","r");
error: value on right hand side of assignment is undefined
error: evaluating assignment expression near line 2, column 2
@@ -485,7 +491,7 @@ ans = 1
Depending on the ownership setting of a swig_ref, it may call C++ destructors when its reference count goes to zero. See the section on memory management below for details.
@@ -494,7 +500,7 @@ This information contains the full class hierarchy. When an indexing operation (
the tree is walked to find a match in the current class as well as any of its bases. The lookup is then cached in the swig_ref.
@@ -504,7 +510,7 @@ The dispatch function selects which overload to call (if any) based on the passe
typecheck typemaps are used to analyze each argument, as well as assign precedence. See the chapter on typemaps for details.
@@ -512,7 +518,7 @@ C++ operator overloading is supported, in a way similar to other modules.
The swig_ref type supports all unary and binary operators between itself and all other types that exist in the system at module load time. When an operator is used (where one of the operands is a swig_ref), the runtime routes the call to either a member function of the given object, or to a global function whose named is derived from the types of the operands (either both or just the lhs or rhs).
-For example, if a and b are SWIG variables in Octave, a+b becomes a.__add(b). The wrapper is then free to implement __add to do whatever it wants. A wrapper may define the __add function manually, %rename some other function to it, or %rename a C++ operator to it.
+For example, if a and b are SWIG variables in Octave, a+b becomes a.__add__(b). The wrapper is then free to implement __add__ to do whatever it wants. A wrapper may define the __add__ function manually, %rename some other function to it, or %rename a C++ operator to it.
By default the C++ operators are renamed to their corresponding Octave operators. So without doing any work, the following interface
@@ -539,87 +545,87 @@ assert(c.value==5);
Octave operators are mapped in the following way:
-__brace a{args}
-__brace_asgn a{args} = rhs
-__paren a(args)
-__paren_asgn a(args) = rhs
-__str generates string rep
-__not !a
-__uplus +a
-__uminus -a
-__transpose a.'
-__hermitian a'
-__incr a++
-__decr a--
-__add a + b
-__sub a - b
-__mul a * b
-__div a / b
-__pow a ^ b
-__ldiv a \ b
-__lshift a << b
-__rshift a >> b
-__lt a < b
-__le a <= b
-__eq a == b
-__ge a >= b
-__gt a > b
-__ne a != b
-__el_mul a .* b
-__el_div a ./ b
-__el_pow a .^ b
-__el_ldiv a .\ b
-__el_and a & b
-__el_or a | b
+__brace__ a{args}
+__brace_asgn__ a{args} = rhs
+__paren__ a(args)
+__paren_asgn__ a(args) = rhs
+__str__ generates string rep
+__not__ !a
+__uplus__ +a
+__uminus__ -a
+__transpose__ a.'
+__hermitian__ a'
+__incr__ a++
+__decr__ a--
+__add__ a + b
+__sub__ a - b
+__mul__ a * b
+__div__ a / b
+__pow__ a ^ b
+__ldiv__ a \ b
+__lshift__ a << b
+__rshift__ a >> b
+__lt__ a < b
+__le__ a <= b
+__eq__ a == b
+__ge__ a >= b
+__gt__ a > b
+__ne__ a != b
+__el_mul__ a .* b
+__el_div__ a ./ b
+__el_pow__ a .^ b
+__el_ldiv__ a .\ b
+__el_and__ a & b
+__el_or__ a | b
On the C++ side, the default mappings are as follows:
The %extend directive works the same as in other modules.
-You can use it to define special behavior, like for example defining Octave operators not mapped to C++ operators, or defining certain Octave mechanisms such as how an object prints. For example, the octave_value::{is_string,string_value,print} functions are routed to a special method __str that can be defined inside an %extend.
+You can use it to define special behavior, like for example defining Octave operators not mapped to C++ operators, or defining certain Octave mechanisms such as how an object prints. For example, the octave_value::{is_string,string_value,print} functions are routed to a special method __str__ that can be defined inside an %extend.
+The C++11 standard provides std::shared_ptr which was derived from the Boost
+implementation, boost::shared_ptr.
+Both of these are available for Octave in the SWIG library and usage is outlined
+in the shared_ptr smart pointer library section.
+
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.
@@ -844,14 +873,14 @@ The %newobject directive may be used to control this behavior for pointers retur
In the case where one wishes for the C++ side to own an object that was created in Octave (especially a Director object), one can use the __disown() method to invert this logic. Then letting the Octave reference count go to zero will not destroy the object, but destroying the object will invalidate the Octave-side object if it still exists (and call destructors of other C++ bases in the case of multiple inheritance/subclass()'ing).
# File : Makefile.PL
use ExtUtils::MakeMaker;
WriteMakefile(
- `NAME' => `example', # Name of package
- `LIBS' => [`-lm'], # Name of custom libraries
- `OBJECT' => `example.o example_wrap.o' # Object files
+ `NAME' => `example', # Name of package
+ `LIBS' => [`-lm'], # Name of custom libraries
+ `OBJECT' => `example.o example_wrap.o' # Object files
);
@@ -241,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.
-
@@ -606,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.
@@ -715,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.
@@ -725,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.
@@ -891,9 +892,9 @@ To check to see if a value is the NULL pointer, use the
if (defined($ptr)) {
- print "Not a NULL pointer.";
+ print "Not a NULL pointer.";
} else {
- print "Is a NULL pointer.";
+ print "Is a NULL pointer.";
}
@@ -916,9 +917,9 @@ dereference them as follows:
if ($$a == $$b) {
- print "a and b point to the same thing in C";
+ print "a and b point to the same thing in C";
} else {
- print "a and b point to different objects.";
+ print "a and b point to different objects.";
}
@@ -939,12 +940,12 @@ example:
%inline %{
/* C-style cast */
Bar *FooToBar(Foo *f) {
- return (Bar *) f;
+ return (Bar *) f;
}
/* C++-style cast */
Foo *BarToFoo(Bar *b) {
- return dynamic_cast<Foo*>(b);
+ return dynamic_cast<Foo*>(b);
}
Foo *IncrFoo(Foo *f, int i) {
@@ -967,7 +968,7 @@ as XS and xsubpp. Given the advancement of the SWIG typesystem and the
SWIG and XS, this is no longer supported.
-
@@ -1166,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.
@@ -1613,7 +1614,7 @@ class DoubleArray {
}
// Destroy an array
~DoubleArray() {
- delete ptr;
+ delete ptr;
}
// Return the length of the array
int length() {
@@ -1752,7 +1753,7 @@ This is still supported, but it is deprecated. The newer %exception di
functionality, but it has additional capabilities that make it more powerful.
@@ -2142,65 +2143,65 @@ reference to be used as a char ** datatype.
// This tells SWIG to treat char ** as a special case
%typemap(in) char ** {
- AV *tempav;
- I32 len;
- int i;
- SV **tv;
- if (!SvROK($input))
- croak("Argument $argnum is not a reference.");
- if (SvTYPE(SvRV($input)) != SVt_PVAV)
- croak("Argument $argnum is not an array.");
- tempav = (AV*)SvRV($input);
- len = av_len(tempav);
- $1 = (char **) malloc((len+2)*sizeof(char *));
- for (i = 0; i <= len; i++) {
- tv = av_fetch(tempav, i, 0);
- $1[i] = (char *) SvPV(*tv,PL_na);
- }
- $1[i] = NULL;
+ AV *tempav;
+ I32 len;
+ int i;
+ SV **tv;
+ if (!SvROK($input))
+ croak("Argument $argnum is not a reference.");
+ if (SvTYPE(SvRV($input)) != SVt_PVAV)
+ croak("Argument $argnum is not an array.");
+ tempav = (AV*)SvRV($input);
+ len = av_len(tempav);
+ $1 = (char **) malloc((len+2)*sizeof(char *));
+ for (i = 0; i <= len; i++) {
+ tv = av_fetch(tempav, i, 0);
+ $1[i] = (char *) SvPV(*tv,PL_na);
+ }
+ $1[i] = NULL;
};
// This cleans up the char ** array after the function call
%typemap(freearg) char ** {
- free($1);
+ free($1);
}
// Creates a new Perl array and places a NULL-terminated char ** into it
%typemap(out) char ** {
- AV *myav;
- SV **svs;
- int i = 0,len = 0;
- /* Figure out how many elements we have */
- while ($1[len])
- len++;
- svs = (SV **) malloc(len*sizeof(SV *));
- for (i = 0; i < len ; i++) {
- svs[i] = sv_newmortal();
- sv_setpv((SV*)svs[i],$1[i]);
- };
- myav = av_make(len,svs);
- free(svs);
- $result = newRV_noinc((SV*)myav);
- sv_2mortal($result);
- argvi++;
+ AV *myav;
+ SV **svs;
+ int i = 0,len = 0;
+ /* Figure out how many elements we have */
+ while ($1[len])
+ len++;
+ svs = (SV **) malloc(len*sizeof(SV *));
+ for (i = 0; i < len ; i++) {
+ svs[i] = sv_newmortal();
+ sv_setpv((SV*)svs[i],$1[i]);
+ };
+ myav = av_make(len,svs);
+ free(svs);
+ $result = newRV_noinc((SV*)myav);
+ sv_2mortal($result);
+ argvi++;
}
// Now a few test functions
%inline %{
-int print_args(char **argv) {
+ int print_args(char **argv) {
int i = 0;
while (argv[i]) {
- printf("argv[%d] = %s\n", i,argv[i]);
- i++;
+ printf("argv[%d] = %s\n", i,argv[i]);
+ i++;
}
return i;
-}
+ }
-// Returns a char ** list
-char **get_args() {
+ // Returns a char ** list
+ char **get_args() {
static char *values[] = { "Dave", "Mike", "Susan", "John", "Michelle", 0};
return &values[0];
-}
+ }
%}
@@ -2219,7 +2220,7 @@ print @$b,"\n"; # Print it out
-
%typemap(memberin) int [ANY] {
- int i;
- for (i = 0; i < $1_dim0; i++) {
- $1[i] = $input[i];
- }
+ int i;
+ for (i = 0; i < $1_dim0; i++) {
+ $1[i] = $input[i];
+ }
}
@@ -2365,7 +2366,7 @@ the "in" typemap in the previous section would be used to convert an
to copy the converted array into a C data structure.
-
@@ -2547,7 +2554,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.
-SWIG supports generating wrappers for PHP5. Support for PHP4 was removed
-in SWIG 1.3.37. The PHP developers are no longer making new PHP4 releases,
-and won't even be patching critical security issues after 2008-08-08, so it
-doesn't make much sense for SWIG to continue to support PHP4 now. If you
-really need to continue to use PHP4, just stick with SWIG 1.3.36.
-
-
-
-Currently any PHP5 release should work, but we don't regularly test with
-PHP < 5.3.
-
-
In this chapter, we discuss SWIG's support of PHP. The PHP module
was extensively rewritten in release 1.3.26, and support for generating
@@ -70,7 +57,17 @@ of the features available in some of the other languages.
-In order to use this module, you will need to have a copy of the PHP5
+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.
+
+
+
+In order to use this module, you will need to have a copy of the PHP
include files to compile the SWIG generated files. If you installed
PHP from a binary package, you may need to install a "php-dev" or "php-devel"
package for these to be installed. You can find out where these files are
@@ -80,16 +77,17 @@ your extension into php directly, you will need the complete PHP source tree
available.
-To build a PHP extension, run swig using the -php option as
-follows:
+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):
-swig -php example.i
+swig -php7 example.i
@@ -102,13 +100,18 @@ The third file,
example.php can be included by PHP scripts. It attempts to
dynamically load the extension and contains extra php code specified
in the interface file. If wrapping C++ code with PHP classes, it will
-also contain PHP5 class wrappers.
+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.
+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
+different extension for the C++ wrapper using -cppext -
+e.g. if you want example_wrap.cc use -cppext cc.
@@ -125,7 +128,7 @@ and it doesn't play nicely with package system. We don't recommend
this approach, or provide explicit support for it.
@@ -199,7 +202,7 @@ other symbols unless care is taken to %rename them. At present
SWIG doesn't have support for the namespace feature added in PHP 5.3.
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!
+would be treated as false! Modern versions of PHP will at least issue
+a PHP notice by default when this happens.
include("example.php");
print seki_get();
-seki_set( seki_get() * 2); # The C variable is now 4.
+seki_set( seki_get() * 2); # The C variable is now 4.
print seki_get();
@@ -325,7 +329,7 @@ undefined.
At this time SWIG does not support custom accessor methods.
-
@@ -348,7 +352,7 @@ Will be accessed in PHP like this :
include("example.php");
$a = foo(2);
$b = bar(3.5, -1.5);
-$c = bar(3.5); # Use default argument for 2nd parameter
+$c = bar(3.5); # Use default argument for 2nd parameter
@@ -378,7 +382,7 @@ print $s; # The value of $s was not changed.
-->
-
The -noproxy option flattens the object structure and
generates collections of named functions (these are the functions
-which the PHP5 class wrappers call). The above example results
+which the PHP class wrappers call). The above example results
in the following PHP functions:
@@ -722,7 +726,7 @@ returns the current value of the class variable. For example
%module example
class Ko {
- static int threats;
+ static int threats;
};
@@ -750,7 +754,7 @@ Ko::threats(10);
echo "There have now been " . Ko::threats() . " threats\n";
-
@@ -878,7 +882,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.
@@ -1230,7 +1234,7 @@ optimized by selectively enabling director methods (using the %feature
directive) for only those methods that are likely to be extended in PHP.
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 44c6930f8..22ab4e2a2 100644
--- a/Doc/Manual/Pike.html
+++ b/Doc/Manual/Pike.html
@@ -1,12 +1,13 @@
-
+
@@ -58,7 +59,7 @@ has since evolved into a general purpose tool that is used in a wide
variety of applications--in fact almost anything where C/C++ programming
is involved.
-
@@ -70,7 +71,7 @@ An official stable version was released along with the decision to make SWIG
license changes and this gave rise to version 2.0.0 in 2010.
@@ -86,7 +87,7 @@ under license terms of the user's choice/requirements and at the same time the S
source was placed under the GNU General Public License version 3.
@@ -151,7 +152,7 @@ However, this isn't meant to be a tutorial on C++ programming. For many
of the gory details, you will almost certainly want to consult a good C++ reference. If you don't program
in C++, you may just want to skip those parts of the manual.
-
@@ -211,7 +212,7 @@ Note: The version symbol is not defined in the generated SWIG
wrapper file. The SWIG preprocessor has defined SWIG_VERSION since SWIG-1.3.11.
@@ -220,7 +221,7 @@ contain, respectively, detailed release notes for the current version,
detailed release notes for previous releases and summary release notes from SWIG-1.3.22 onwards.
@@ -233,7 +234,7 @@ who have made contributions at all levels over time. Contributors
are mentioned either in the COPYRIGHT file or CHANGES files shipped with SWIG or in submitted bugs.
-Please see the dedicated Windows chapter for instructions on installing
+Please see the dedicated Windows chapter for instructions on installing
SWIG on Windows and running the examples. The Windows distribution is
called swigwin and includes a prebuilt SWIG executable, swig.exe, included in
the top level directory. Otherwise it is exactly the same as
the main SWIG distribution. There is no need to download anything else.
+These installation instructions are for using the distributed tarball,
+for example, swig-3.0.8.tar.gz.
+If you wish to build and install from source on Github, extra steps are required.
+Please see the Bleeding Edge page on the SWIG website.
+
@@ -332,7 +340,7 @@ be configured with a subset of target languages.
SWIG used to include a set of runtime libraries for some languages for working
with multiple modules. These are no longer built during the installation stage.
However, users can build them just like any wrapper module as described in
-the Modules chapter.
+the Modules chapter.
The CHANGES file shipped with SWIG in the top level directory
also lists some examples which build the runtime library.
@@ -350,7 +358,7 @@ a number of packages to be installed. Full instructions at
@@ -378,7 +386,7 @@ Darwin's two-level namespaces. Some details about this can be found here
Needless to say, you might have to experiment a bit to get things working at first.
-
@@ -63,7 +64,7 @@ By default, the #include is ignored unless you run SWIG with the
is that you often don't want SWIG to try and wrap everything included
in standard header system headers and auxiliary files.
-
@@ -92,7 +93,7 @@ The -importall directive tells SWIG to follow all #include sta
as imports. This might be useful if you want to extract type definitions from system
header files without generating any wrappers.
-
@@ -124,7 +125,9 @@ SWIGMZSCHEME Defined when using Mzscheme
SWIGOCAML Defined when using Ocaml
SWIGOCTAVE Defined when using Octave
SWIGPERL Defined when using Perl
-SWIGPHP Defined when using PHP
+SWIGPHP Defined when using PHP5 or PHP7
+SWIGPHP5 Defined when using PHP5
+SWIGPHP7 Defined when using PHP7
SWIGPIKE Defined when using Pike
SWIGPYTHON Defined when using Python
SWIGR Defined when using R
@@ -156,7 +159,7 @@ SWIG (except for the symbol `SWIG' which is only defined
within the SWIG compiler).
@@ -313,14 +316,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.
@@ -333,7 +336,7 @@ if you write code like this,
%{
#ifdef NEED_BLAH
int blah() {
- ...
+ ...
}
#endif
%}
@@ -345,7 +348,7 @@ the contents of the %{ ... %} block are copied without
modification to the output (including all preprocessor directives).
@@ -387,7 +390,7 @@ to actually go into the wrapper file, prefix the preprocessor directives with % and leave the preprocessor directive in the code.
-
@@ -468,7 +471,7 @@ Instead the results after the preprocessor has run are displayed.
This might be useful as an aid to debugging and viewing the results of macro expansions.
@@ -271,13 +285,13 @@ The following sections have further practical examples and details on
how you might go about compiling and using the generated files.
The preferred approach to building an extension module for python is to compile it with
distutils, which comes with all recent versions of python
-(Distutils Docs).
+(Distutils Docs).
@@ -363,7 +377,7 @@ This same approach works on all platforms if the appropriate compiler is install
can even build extensions to the standard Windows Python using MingGW)
You will need to supply the same libraries that were used to build Python the first
@@ -484,18 +498,18 @@ hassle in the opinion of this author).
Compatibility note: The embed.i library file is
-deprecated and has not been maintained for several years. Even though it
-appears to "work" with Python 2.1, no future support is guaranteed.
+deprecated and has not been actively maintained for many years. Even though it
+appears to "work" with Python 2.7, no future support is guaranteed.
If using static linking, you might want to rely on a different approach
(perhaps using distutils).
@@ -739,7 +753,7 @@ erratic program behavior. If working with lots of software components, you
might want to investigate using a more formal standard such as COM.
@@ -914,7 +928,7 @@ to your C/C++ code. Functions are wrapped as functions, classes are wrapped as
This section briefly covers the essential aspects of this wrapping.
@@ -1129,7 +1143,7 @@ other object. Unfortunately, there is no easy way for SWIG to
generate code that prevents this. You will just have to be careful.
@@ -1876,7 +1889,7 @@ Also, be aware that certain operators don't map cleanly to Python. For instance
overloaded assignment operators don't map to Python semantics and will be ignored.
@@ -1890,10 +1903,10 @@ submodules or packages. For example, if you have a file like this,
%module example
namespace foo {
- int fact(int n);
- struct Vector {
- double x,y,z;
- };
+ int fact(int n);
+ struct Vector {
+ double x,y,z;
+ };
};
@@ -1943,7 +1956,7 @@ utilizes thousands of small deeply nested namespaces each with
identical symbol names, well, then you get what you deserve.
+The C++11 standard provides std::shared_ptr which was derived from the Boost
+implementation, boost::shared_ptr.
+Both of these are available for Python in the SWIG library and usage is outlined
+in the shared_ptr smart pointer library section.
+
The entire justification for the -builtin option is improved
@@ -2466,56 +2493,114 @@ automatically converted to python slot operators, refer to the file
python/pyopers.swig in the SWIG library.
-
There are other very useful python slots that you
-may explicitly define using %feature directives. For example,
-suppose you want to use instances of a wrapped class as keys in a native python
-dict. That will work as long as you define a hash function for
-instances of your class, and use it to define the python tp_hash
-slot:
+
+
+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.
+
+
+
+To dispatch to a statically defined function, use %feature("python:<slot>"),
+where <slot> is the name of a field in a PyTypeObject, PyNumberMethods,
+PyMappingMethods, PySequenceMethods or PyBufferProcs.
+You may override (almost) all of these slots.
+
+
+
+
+Let's consider an example setting the tp_hash slot for the MyClass type.
+This is akin to providing a __hash__ method (for non-builtin types) to make a type hashable.
+The hashable type can then for example be added to a Python dict.
+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:
+
+NOTE: It is the responsibility of the programmer (that's you!) to ensure
+that a statically defined slot function has the correct signature, the hashfunc
+typedef in this case.
+
+
+
+If, instead, you want to dispatch to an instance method, you can
+use %feature("python:slot"). For example:
+
This will allow you to write python code like this:
+
+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
+the "functype" attribute of the feature enables SWIG to generate
+the chosen closure function.
+
Because you defined the tp_hash slot, Cheese objects may
-be used as hash keys; and when the cheeseHashFunc method is invoked
-by a python dict, it will not go through named method dispatch.
-A more detailed discussion about %feature("python:slot") can be found
+
+There is further information on %feature("python:slot")
in the file python/pyopers.swig in the SWIG library.
-You can read about all of the available python slots here:
You may override (almost) all of the slots defined in the PyTypeObject,
-PyNumberMethods, PyMappingMethods, PySequenceMethods, and PyBufferProcs
-structs.
NOTE: Although this section refers to proxy objects, everything here also applies
@@ -2663,10 +2748,10 @@ change the ownership of an object. For instance, consider code like this:
@@ -2720,7 +2805,7 @@ in Python-2.2, an entirely new type of class system was introduced.
This new-style class system offers many enhancements including static
member functions, properties (managed attributes), and class methods.
Details about all of these changes can be found on www.python.org and is not repeated here.
+href="https://www.python.org">www.python.org and is not repeated here.
@@ -2735,7 +2820,7 @@ old-style classes are used instead.
This dual-nature of the wrapper code means that you can create extension
modules with SWIG and those modules will work with all versions of Python
-ranging from Python-1.4 to the very latest release. Moreover, the wrappers take
+ranging from Python-2.0 to the very latest release. Moreover, the wrappers take
advantage of Python-2.2 features when available.
@@ -2747,7 +2832,7 @@ class itself. In Python-2.1 and earlier, they have to be accessed as a global
function or through an instance (see the earlier section).
-
@@ -3233,16 +3318,16 @@ functions. Just use the %inline directive. For example:
%inline %{
/* Note: double[4][4] is equivalent to a pointer to an array double (*)[4] */
double (*new_mat44())[4] {
- return (double (*)[4]) malloc(16*sizeof(double));
+ return (double (*)[4]) malloc(16*sizeof(double));
}
void free_mat44(double (*x)[4]) {
- free(x);
+ free(x);
}
void mat44_set(double x[4][4], int i, int j, double v) {
- x[i][j] = v;
+ x[i][j] = v;
}
double mat44_get(double x[4][4], int i, int j) {
- return x[i][j];
+ return x[i][j];
}
%}
@@ -3270,7 +3355,7 @@ hard to implement. It is possible to clean this up using Python code, typemaps,
customization features as covered in later sections.
@@ -3288,12 +3373,12 @@ void set_transform(Image *im, double x[4][4]);
/* Rewrite the high level interface to set_transform */
%pythoncode %{
def set_transform(im,x):
- a = new_mat44()
- for i in range(4):
- for j in range(4):
- mat44_set(a,i,j,x[i][j])
- _example.set_transform(im,a)
- free_mat44(a)
+ a = new_mat44()
+ for i in range(4):
+ for j in range(4):
+ mat44_set(a,i,j,x[i][j])
+ _example.set_transform(im,a)
+ free_mat44(a)
%}
@@ -3443,11 +3528,11 @@ proxy, just before the return statement.
// Add python code to bar()
%feature("pythonprepend") Foo::bar(int) %{
- #do something before C++ call
+ #do something before C++ call
%}
%feature("pythonappend") Foo::bar(int) %{
- #do something after C++ call
+ #do something after C++ call
%}
@@ -3472,11 +3557,11 @@ SWIG version 1.3.28 you can use the directive forms
// Add python code to bar()
%pythonprepend Foo::bar(int) %{
- #do something before C++ call
+ #do something before C++ call
%}
%pythonappend Foo::bar(int) %{
- #do something after C++ call
+ #do something after C++ call
%}
@@ -3501,11 +3586,11 @@ as it will then get attached to all the overloaded C++ methods. For example:
// Add python code to bar()
%pythonprepend Foo::bar %{
- #do something before C++ call
+ #do something before C++ call
%}
%pythonappend Foo::bar %{
- #do something after C++ call
+ #do something after C++ call
%}
@@ -3522,7 +3607,7 @@ The same applies for overloaded constructors.
@@ -3630,8 +3715,8 @@ or a NULL pointer perhaps). Here is a simple example of how you might handle th
%exception malloc {
$action
if (!result) {
- PyErr_SetString(PyExc_MemoryError,"Not enough memory");
- return NULL;
+ PyErr_SetString(PyExc_MemoryError,"Not enough memory");
+ SWIG_fail;
}
}
void *malloc(size_t nbytes);
@@ -3660,11 +3745,11 @@ that. For example:
When raising a Python exception from C, use the PyErr_SetString()
-function as shown above. The following exception types can be used as the first argument.
+function as shown above followed by SWIG_fail.
+The following exception types can be used as the first argument.
@@ -3732,12 +3818,19 @@ PyExc_ZeroDivisionError
+
+SWIG_fail is a C macro which when called within the context of SWIG wrapper function,
+will jump to the error handler code. This will call any cleanup code (freeing any temp variables)
+and then return from the wrapper function so that the Python interpreter can raise the Python exception.
+This macro should always be called after setting a Python error in code snippets, such as typemaps and %exception, that are ultimately generated into the wrapper function.
+
+
The language-independent exception.i library file can also be used
to raise exceptions. See the SWIG Library chapter.
C++ default argument code generation is documented in the main
-Default arguments section.
+Default arguments section.
There is also an optional Python specific feature that can be used called the python:cdefaultargsfeature flag.
By default, SWIG attempts to convert C++ default argument values
@@ -4260,7 +4353,7 @@ Versions of SWIG prior to this varied in their ability to convert C++ default va
equivalent Python default argument values.
@@ -4277,7 +4370,7 @@ Typemaps are only used if you want to change some aspect of the primitive
C-Python interface or if you want to elevate your guru status.
@@ -4290,8 +4383,8 @@ you might define a typemap like this:
%module example
%typemap(in) int {
- $1 = (int) PyLong_AsLong($input);
- printf("Received an integer : %d\n",$1);
+ $1 = (int) PyLong_AsLong($input);
+ printf("Received an integer : %d\n",$1);
}
%inline %{
extern int fact(int n);
@@ -4328,11 +4421,11 @@ You can refine this by supplying an optional parameter name. For example:
%module example
%typemap(in) int nonnegative {
- $1 = (int) PyLong_AsLong($input);
- if ($1 < 0) {
- PyErr_SetString(PyExc_ValueError,"Expected a nonnegative value.");
- return NULL;
- }
+ $1 = (int) PyLong_AsLong($input);
+ if ($1 < 0) {
+ PyErr_SetString(PyExc_ValueError,"Expected a nonnegative value.");
+ SWIG_fail;
+ }
}
%inline %{
extern int fact(int nonnegative);
@@ -4354,8 +4447,8 @@ the typemap system follows typedef declarations. For example:
%typemap(in) int n {
- $1 = (int) PyLong_AsLong($input);
- printf("n = %d\n",$1);
+ $1 = (int) PyLong_AsLong($input);
+ printf("n = %d\n",$1);
}
%inline %{
typedef int Integer;
@@ -4371,8 +4464,8 @@ Typemaps can also be defined for groups of consecutive arguments. For example:
%typemap(in) (char *str, int len) {
- $1 = PyString_AsString($input);
- $2 = PyString_Size($input);
+ $1 = PyString_AsString($input);
+ $2 = PyString_Size($input);
};
int count(char c, char *str, int len);
@@ -4393,7 +4486,7 @@ parameter is omitted):
@@ -4664,18 +4757,18 @@ object to be used as a char ** object.
$1 = (char **) malloc((size+1)*sizeof(char *));
for (i = 0; i < size; i++) {
PyObject *o = PyList_GetItem($input,i);
- if (PyString_Check(o))
- $1[i] = PyString_AsString(PyList_GetItem($input,i));
- else {
- PyErr_SetString(PyExc_TypeError,"list must contain strings");
- free($1);
- return NULL;
+ if (PyString_Check(o)) {
+ $1[i] = PyString_AsString(PyList_GetItem($input,i));
+ } else {
+ free($1);
+ PyErr_SetString(PyExc_TypeError,"list must contain strings");
+ SWIG_fail;
}
}
$1[i] = 0;
} else {
PyErr_SetString(PyExc_TypeError,"not a list");
- return NULL;
+ SWIG_fail;
}
}
@@ -4687,12 +4780,12 @@ object to be used as a char ** object.
// Now a test function
%inline %{
int print_args(char **argv) {
- int i = 0;
- while (argv[i]) {
- printf("argv[%d] = %s\n", i,argv[i]);
- i++;
- }
- return i;
+ int i = 0;
+ while (argv[i]) {
+ printf("argv[%d] = %s\n", i,argv[i]);
+ i++;
+ }
+ return i;
}
%}
@@ -4705,7 +4798,7 @@ follows :
>>> from argv import *
->>> print_args(["Dave","Mike","Mary","Jane","John"])
+>>> print_args(["Dave", "Mike", "Mary", "Jane", "John"])
argv[0] = Dave
argv[1] = Mike
argv[2] = Mary
@@ -4722,7 +4815,7 @@ memory allocation is used to allocate memory for the array, the
the C function.
-
36.9.2 Expanding a Python object into multiple arguments
+If you don't you'll get an error message along the lines of:
+
+
+
+
+Traceback (most recent call last):
+ File "runme.py", line 3, in >module<
+ example.foo(["foo", "bar", "spam", "1"])
+NotImplementedError: Wrong number or type of arguments for overloaded function 'foo'.
+ Possible C/C++ prototypes are:
+ foo(int,char **)
+ foo()
+
@@ -4812,10 +4945,10 @@ arguments rather than in the return value of a function. For example:
/* Returns a status value and two values in out1 and out2 */
int spam(double a, double b, double *out1, double *out2) {
- ... Do a bunch of stuff ...
- *out1 = result1;
- *out2 = result2;
- return status;
+ ... Do a bunch of stuff ...
+ *out1 = result1;
+ *out2 = result2;
+ return status;
}
@@ -4831,23 +4964,23 @@ A typemap can be used to handle this case as follows :
// is guaranteed to be a List object by SWIG.
%typemap(argout) double *OutValue {
- PyObject *o, *o2, *o3;
- o = PyFloat_FromDouble(*$1);
- if ((!$result) || ($result == Py_None)) {
- $result = o;
- } else {
- if (!PyTuple_Check($result)) {
- PyObject *o2 = $result;
- $result = PyTuple_New(1);
- PyTuple_SetItem(target,0,o2);
- }
- o3 = PyTuple_New(1);
- PyTuple_SetItem(o3,0,o);
- o2 = $result;
- $result = PySequence_Concat(o2,o3);
- Py_DECREF(o2);
- Py_DECREF(o3);
+ PyObject *o, *o2, *o3;
+ o = PyFloat_FromDouble(*$1);
+ if ((!$result) || ($result == Py_None)) {
+ $result = o;
+ } else {
+ if (!PyTuple_Check($result)) {
+ PyObject *o2 = $result;
+ $result = PyTuple_New(1);
+ PyTuple_SetItem($result,0,o2);
}
+ o3 = PyTuple_New(1);
+ PyTuple_SetItem(o3,0,o);
+ o2 = $result;
+ $result = PySequence_Concat(o2,o3);
+ Py_DECREF(o2);
+ Py_DECREF(o3);
+ }
}
int spam(double a, double b, double *OutValue, double *OutValue);
@@ -4869,7 +5002,7 @@ no meaningful input value), an additional typemap can be written. For example:
@@ -4912,12 +5045,12 @@ This too, can be handled used typemaps as follows :
if (PyTuple_Check($input)) {
if (!PyArg_ParseTuple($input,"dddd",temp,temp+1,temp+2,temp+3)) {
PyErr_SetString(PyExc_TypeError,"tuple must have 4 elements");
- return NULL;
+ SWIG_fail;
}
$1 = &temp[0];
} else {
PyErr_SetString(PyExc_TypeError,"expected a tuple.");
- return NULL;
+ SWIG_fail;
}
}
@@ -4938,7 +5071,7 @@ array, such an approach would not be recommended for huge arrays, but
for small structures, this approach works fine.
@@ -5214,7 +5349,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.
-
Level "2" results in the function prototype as per level "0". In addition, a line of
-documentation is generated for each parameter. Using the previous example, the generated
-code will be:
+documentation is generated for each parameter using numpydoc style.
+Using the previous example, the generated code will be:
@@ -5283,11 +5418,12 @@ def function_name(*args, **kwargs):
"""
function_name(x, y, foo=None, bar=None) -> bool
- Parameters:
- x: int
- y: int
- foo: Foo *
- bar: Bar *
+ Parameters
+ ----------
+ x: int
+ y: int
+ foo: Foo *
+ bar: Bar *
"""
...
@@ -5315,20 +5451,21 @@ resulting in
def function_name(*args, **kwargs):
- """
+ """
function_name(x, y, foo=None, bar=None) -> bool
- Parameters:
- x (C++ type: int) -- Input x dimension
- y: int
- foo: Foo *
- bar: Bar *
+ Parameters
+ ----------
+ x (C++ type: int) -- Input x dimension
+ y: int
+ foo: Foo *
+ bar: Bar *
"""
Python has concepts of modules and packages. Modules are separate units of
@@ -5457,12 +5595,29 @@ They should be created by other means. Both files (module *.py and
directories in order to obtain a desirable package/module hierarchy.
+
+Python3 adds another option for packages with
+PEP 0420 (implicit
+namespace packages). Implicit namespace packages no longer use
+__init__.py files. SWIG generated Python modules support implicit
+namespace packages. See
+36.11.5 Implicit Namespace
+Packages for more information.
+
+
+
+If you place a SWIG generated module into a Python package then there
+are details concerning the way SWIG
+searches for the wrapper module
+that you may want to familiarize yourself with.
+
+
The way Python defines its modules and packages impacts SWIG users. Some
users may need to use special features such as the package option in the
%module directive or import related command line options. These are
explained in the following sections.
Suppose, we have the following hierarchy of files:
@@ -5616,8 +5771,9 @@ class M2(pkg2.mod3.M3): pass
By default, SWIG would generate mod2.py proxy file with
import directive as in point 1. This can be changed with the
-relativeimport command line option. The -relativeimport instructs
-SWIG to organize imports as in point 2 (for Python 2.x) or as in point 4 (for
-Python 3, that is when the -py3 command line option is enabled). In short, if you have
+SWIG to organize imports as in point 2 (for Python < 2.7.0) or as in point 4
+for Python 2.7.0 and newer. This is a check done at the time the module is
+imported. In short, if you have
mod2.i and mod3.i as above, then without
-relativeimport SWIG will write
You should avoid using relative imports and use absolute ones whenever
possible. There are some cases, however, when relative imports may be
necessary. The first example is, when some (legacy) Python code refers entities
@@ -5655,7 +5806,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).
As you may know, there is an incompatibility in import semantics (for the
@@ -5669,7 +5820,7 @@ import foo
refers to a top-level module or to another module inside the current
package. In Python 3 it always refers to a top-level module
-(see PEP 328).
+(see PEP 328).
To instruct Python 2.5 through 2.7 to use new semantics (that is import
foo is interpreted as absolute import), one has to put the following
line
@@ -5692,7 +5843,7 @@ from __future__ import absolute_import
-
Imports in __init__.py are handy when you want to populate a
@@ -5802,8 +5953,295 @@ class Bar(pkg3.foo.Foo): pass
effect (note, that the Python 2 case also needs the -relativeimport
workaround).
Python 3.3 introduced
+PEP 0420 which
+implements implicit namespace packages. In a nutshell, implicit namespace
+packages remove the requirement of an __init__.py file and allow packages
+to be split across multiple PATH elements. For example:
+
If PYTHONPATH is set to "/fragment1:/fragment2:/fragment3", then mod1, mod2
+and mod3 will be part of pkg1. This allows for splitting of packages into
+separate pieces. This can be useful for SWIG generated wrappers in the
+following way.
+
+
+
Suppose you create a SWIG wrapper for a module called robin. The SWIG
+generated code consists of two files robin.py and _robin.so. You wish to
+make these modules part of a subpackage (brave.sir). With implicit namespace
+packages you can place these files in the following configurations:
+
Finally suppose that your pure python code is stored in a .zip file or
+some other way (database, web service connection, etc). Python can load the
+robin.py module using a custom importer. But the _robin.so module will need
+to be located on a file system. Implicit namespace packages make this
+possible. For example, using PYTHONPATH="/some/path/foo.zip:/some/other/path"
+
+
Contents of foo.zip
+
+
+brave/
+brave/sir/
+brave/sir/robin.py
+
+
+
+
File system contents
+
+
+/some/other/path/brave/sir/_robin.so
+
+
+
+
Support for implicit namespace packages was added to python-3.3. The
+zipimporter requires python-3.5.1 or newer to work with subpackages.
+
+
+
+Compatibility Note: Support for implicit namespace packages was added in SWIG-3.0.9.
+
+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
+file really defines two Python modules. How these two modules are loaded is
+covered next.
+
+
+
+The pure Python module needs to load the C/C++ module in order to link
+to the wrapped C/C++ methods. To do this it must make some assumptions
+about what package the C/C++ module may be located in. The approach the
+pure Python module uses to find the C/C++ module is as follows:
+
+
+
+
The pure Python module, foo.py, tries to load the C/C++ module, _foo, from the same package foo.py is
+ located in. The package name is determined from the __name__
+ attribute given to foo.py by the Python loader that imported
+ foo.py. If foo.py is not in a package then _foo is loaded
+ as a global module.
+
+
If the above import of _foo results in an ImportError
+ being thrown, then foo.py makes a final attempt to load _foo
+ as a global module.
+
+
+
+
+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.
+The custom code can be specified by setting the moduleimport option of the %module directive with the appropriate import code. For example:
+
+
+
+
+%module(moduleimport="import _foo") foo
+
+
+
+
+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
+readability of the %module directive by using a macro. For
+example:
+
+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:
+
+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.
+
It is strongly recommended to use dynamically linked modules for the C
+portion of your pair of Python modules.
+If for some reason you still need
+to link the C module of the pair of Python modules generated by SWIG into
+your interpreter, then this section provides some details on how this impacts
+the pure Python modules ability to locate the other part of the pair.
+Please also see the Static Linking section.
+
+
+
When Python is extended with C code the Python interpreter needs to be
+informed about details of the new C functions that have been linked into
+the executable. The code to do this is created by SWIG and is automatically
+called in the correct way when the module is dynamically loaded. However
+when the code is not dynamically loaded (because it is statically linked)
+Then the initialization method for the module created by SWIG is not
+called automatically and the Python interpreter has no idea that the
+new SWIG C module exists.
+
+
+
Before Python 3, one could simply call the init method created by SWIG
+which would have normally been called when the shared object was dynamically
+loaded. The specific name of this method is not given here because statically
+linked modules are not encouraged with SWIG
+(Static Linking). However one can find this
+init function in the C file generated by SWIG.
+
+
+
If you are really keen on static linking there are two ways
+to initialize the SWIG generated C module with the init method. Which way
+you use depends on what version of Python your module is being linked with.
+Python 2 and Python 3 treat this init function differently. And the way
+they treat it affects how the pure Python module will be able to
+locate the C module.
+
+
+
The details concerning this are covered completly in the documentation
+for Python itself. Links to the relavent sections follow:
+
There are two keys things to understand. The first is that in
+Python 2 the init() function returns void. In Python 3 the init() function
+returns a PyObject * which points to the new module. Secondly, when
+you call the init() method manually, you are the Python importer. So, you
+determine which package the C module will be located in.
+
+
+
So, if you are using Python 3 it is important that you follow what is
+described in the Python documentation linked above. In particular, you can't
+simply call the init() function generated by SWIG and cast the PyObject
+pointer it returns over the side. If you do then Python 3 will have no
+idea that your C module exists and the pure Python half of your wrapper will
+not be able to find it. You need to register your module with the Python
+interpreter as described in the Python docs.
+
+
+
With Python 2 things are somewhat more simple. In this case the init function
+returns void. Calling it will register your new C module as a global
+module. The pure Python part of the SWIG wrapper will be able to find it
+because it tries both the pure Python module it is part of and the global
+module. If you wish not to have the statically linked module be a global
+module then you will either need to refer to the Python documentation on how
+to do this (remember you are now the Python importer) or use dynamic linking.
+
For more details about the surrogateescape error handler, please see
-PEP 383.
+PEP 383.
+
+
+
+In some cases, users may wish to instead handle all byte strings as bytes
+objects in Python 3. This can be accomplished by adding
+SWIG_PYTHON_STRICT_BYTE_CHAR to the generated code:
+
+This will modify the behavior so that only Python 3 bytes objects will be
+accepted and converted to a C/C++ string, and any string returned from C/C++
+will be converted to a bytes object in Python 3:
+
+
+
+>>> from char_to_bytes import *
+>>> charstring(b"hi") # Byte string
+b'hi'
+>>> charstring("hi") # Unicode string
+Traceback (most recent call last):
+ File "<stdin>", line 1, in ?
+TypeError: in method 'charstring', argument 1 of type 'char *'
+
+
+
+Note that in Python 2, defining SWIG_PYTHON_STRICT_BYTE_CHAR has no
+effect, since strings in Python 2 are equivalent to Python 3 bytes objects.
+However, there is a similar capability to force unicode-only handling for
+wide characters C/C++ strings (wchar_t * or std::wstring
+types) in Python 2. By default, in Python 2 both strings and unicode strings
+are converted to C/C++ wide strings, and returned wide strings are converted
+to a Python unicode string. To instead only convert unicode strings to wide
+strings, users can add SWIG_PYTHON_STRICT_UNICODE_WCHAR to the
+generated code:
+
+This ensures that only unicode strings are accepted by wcharstring in both
+Python 2 and Python 3:
+
+
+
+>>> from wchar_to_unicode import *
+>>> wcharstring(u"hi") # Unicode string
+u'hi'
+>>> wcharstring(b"hi") # Byte string
+Traceback (most recent call last):
+ File "<stdin>", line 1, in ?
+TypeError: in method 'charstring', argument 1 of type 'wchar_t *'
+
+
+
+By defining both SWIG_PYTHON_STRICT_BYTE_CHAR and
+SWIG_PYTHON_STRICT_UNICODE_WCHAR, Python wrapper code can support
+overloads taking both std::string (as Python bytes) and std::wstring
+(as Python unicode).
+
+A Python 3 string is a Unicode string so by default a Python 3 string that contains Unicode
+characters passed to C/C++ will be accepted and converted to a C/C++ string
+(char * or std::string types).
+A Python 2 string is not a unicode string by default and should a Unicode string be
+passed to C/C++ it will fail to convert to a C/C++ string
+(char * or std::string types).
+The Python 2 behavior can be made more like Python 3 by defining
+SWIG_PYTHON_2_UNICODE when compiling the generated C/C++ code.
+By default when the following is wrapped:
+
+Note that defining both SWIG_PYTHON_2_UNICODE and
+SWIG_PYTHON_STRICT_BYTE_CHAR at the same time is not allowed, since
+the first is allowing unicode conversion and the second is explicitly
+prohibiting it.
diff --git a/Doc/Manual/R.html b/Doc/Manual/R.html
index 50e861b22..9b5993bff 100644
--- a/Doc/Manual/R.html
+++ b/Doc/Manual/R.html
@@ -1,12 +1,13 @@
-
+
SWIG and R
+
-
@@ -33,7 +34,7 @@ compile and run an R interface to QuantLib running on Mandriva Linux
with gcc. The R bindings also work on Microsoft Windows using Visual C++.
-
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
-
SWIG 3.0 is known to work with Ruby versions 1.8 and later.
@@ -159,7 +164,7 @@ read the "SWIG Basics"
chapter. It is also assumed that the reader has a basic understanding
of Ruby.
To build a Ruby module, run SWIG using the -ruby
@@ -183,7 +188,7 @@ if compiling a C++ extension) that contains all of the code needed to
build a Ruby extension module. To finish building the module, you need
to compile this file and link it with the rest of your program.
Ruby extension modules are typically compiled into shared
@@ -285,7 +290,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.
An alternative approach to dynamic linking is to rebuild the
@@ -330,7 +335,7 @@ finding the Ruby source, adding an entry to the ext/Setup
file, adding your directory to the list of extensions in the file, and
finally rebuilding Ruby.
Building a SWIG extension to Ruby under Windows 95/NT is
@@ -387,7 +392,7 @@ order to build extensions, you may need to download the source
distribution to the Ruby package, as you will need the Ruby header
files.
The SWIG %module directive specifies
@@ -529,7 +534,7 @@ option to wrap everything into the global module, take care that the
names of your constants, classes and methods don't conflict with any of
Ruby's built-in names.
For the most part, overloaded operators are handled
@@ -1122,7 +1127,7 @@ c = Example.add_complex(a, b)
is discussed in the section
on operator overloading.
SWIG is aware of C++ namespaces, but namespace names do not
@@ -1179,7 +1184,7 @@ and create extension modules for each namespace separately. If your
program utilizes thousands of small deeply nested namespaces each with
identical symbol names, well, then you get what you deserve.
On a related note, the standard SWIG library contains a
@@ -1314,7 +1319,7 @@ puts v
shown in these examples. More details can be found in the SWIG and C++
chapter.
+The C++11 standard provides std::shared_ptr which was derived from the Boost
+implementation, boost::shared_ptr.
+Both of these are available for Ruby in the SWIG library and usage is outlined
+in the shared_ptr smart pointer library section.
+
SWIG's Ruby module supports cross-language polymorphism
@@ -1532,7 +1551,7 @@ module. Rather than duplicate the information presented in the 38.3.17.1 Exception Unrolling
+
Whenever a C++ director class routes one of its virtual
@@ -1555,7 +1574,7 @@ method is "wrapped" using the rb_rescue2()
function from Ruby's C API. If any Ruby exception is raised, it will be
caught here and a C++ exception is raised in its place.
Ruby has several common naming conventions. Constants are
@@ -1593,7 +1612,7 @@ generated
by SWIG, it is turned off by default in SWIG 1.3.28. However, it is
planned to become the default option in future releases.
It's a fairly common practice in the Ruby built-ins and
@@ -1663,7 +1682,7 @@ matching rules used for other kinds of features apply (see the chapter
on "Customization
Features") for more details).
Ruby methods that return a boolean value and end in a
@@ -1712,7 +1731,7 @@ using SWIG's "features" mechanism and so the same name matching rules
used for other kinds of features apply (see the chapter on "Customization
Features") for more details).
Ruby methods that modify an object in-place and end in an
@@ -1744,7 +1763,7 @@ using SWIG's "features" mechanism and so the same name matching rules
used for other kinds of features apply (see the chapter on "Customization
Features") for more details).
Often times a C++ library will expose properties through
@@ -1779,7 +1798,7 @@ irb(main):003:0> puts foo.value
%rename("value=") Foo::setValue(int value);
-
The SWIG %exception directive can be
@@ -2030,7 +2049,7 @@ methods and functions named getitem and setitem.
limited to C++ exception handling. See the chapter on Customization
Features for more examples.
There are three ways to raise exceptions from C++ code to
@@ -2254,7 +2273,7 @@ function. The first argument passed to rb_raise()
is the exception type. You can raise a custom exception type or one of
the built-in Ruby exception types.
This section describes how you can modify SWIG's default
@@ -2306,7 +2325,7 @@ a required part of using SWIG---the default wrapping behavior is enough
in most cases. Typemaps are only used if you want to change some aspect
of the primitive C-Ruby interface.
A typemap is nothing more than a code generation rule that is
@@ -2463,7 +2482,7 @@ to be used as follows (notice how the length parameter is omitted):
A typemap can be deleted by simply defining no code. For
@@ -2576,7 +2595,7 @@ defined by typemaps, clearing a fundamental type like int
will make that type unusable unless you also define a new set of
typemaps immediately after the clear operation.
Typemap declarations can be declared in the global scope,
@@ -2647,13 +2666,13 @@ In this example, this is done using the class declaration class
string
.
The "typecheck" typemap is used to support overloaded
@@ -2742,7 +2761,7 @@ program uses overloaded methods, you should also define a collection of
"typecheck" typemaps. More details about this follow in a later section
on "Typemaps and Overloading."
The "default" typemap is used to turn an argument into a
@@ -2833,7 +2852,7 @@ arguments that follow must have default values. See the 38.7.6.6 "check" typemap
+
The "freearg" typemap is used to cleanup argument data. It is
@@ -2929,7 +2948,7 @@ This code is also placed into a special variable $cleanup
that may be used in other typemaps whenever a wrapper function needs to
abort prematurely.
The "varin" typemap is used to convert objects in the target
language to C for the purposes of assigning to a C/C++ global variable.
This is implementation specific.
The "varout" typemap is used to convert a C/C++ object to an
object in the target language when reading a C/C++ global variable.
This is implementation specific.
The "throws" typemap is only used when SWIG parses a C++
@@ -3026,7 +3045,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.
When you write a typemap, you usually have to work directly
@@ -3293,7 +3312,7 @@ stick to the swig functions instead of the native Ruby functions.
That should help you avoid having to rewrite a lot of typemaps
across multiple languages.
Here, while the Ruby versions return the value directly, the SWIG
@@ -3403,7 +3422,7 @@ versions do not, but return a status value to indicate success (SWIG_OK
-
void rb_raise(VALUE exception, const char *fmt,
@@ -3505,7 +3524,7 @@ message to standard error if Ruby was invoked with the -w
flag. The given format string fmt and remaining
arguments are interpreted as with printf().
-
A common problem in many C programs is the processing of
@@ -3623,7 +3642,7 @@ array. Since dynamic memory allocation is used to allocate memory for
the array, the "freearg" typemap is used to later release this memory
after the execution of the C function.
Another use for macros and type maps is to create a Ruby array
@@ -4015,7 +4034,7 @@ STL with ruby, you are advised to use the standard swig STL library,
which does much more than this. Refer to the section called
the C++ Standard Template Library.
-
Since SWIG does know everything about the function it wraps,
@@ -4100,7 +4119,7 @@ several options for autodoc controlled by the value given to the
feature, described below.
@@ -4204,10 +4223,10 @@ docstring associated with classes, function or methods are output.
If an item already has an autodoc string then it is combined with the
docstring and they are output together.
SWIG allows operator overloading with, by using the %extend
@@ -4388,7 +4407,7 @@ separate method for handling inequality since Ruby
parses the expression a != b as !(a == b).
The Ruby language doesn't support multiple inheritance, but
@@ -4581,7 +4600,7 @@ matching rules used for other kinds of features apply (see the chapter
on "Customization
Features") for more details).
One of the most common issues in generating SWIG bindings for
@@ -4604,7 +4623,7 @@ to C++ (or vice versa) depending on what function or methods are
invoked. Clearly, developing a SWIG wrapper requires a thorough
understanding of how the underlying library manages memory.
Ruby uses a mark and sweep garbage collector. When the garbage
@@ -4618,8 +4637,7 @@ objects that have already been marked). Those objects, in turn, may
reference other objects. This process will continue until all active
objects have been "marked." After the mark phase comes the sweep phase.
In the sweep phase, all objects that have not been marked will be
-garbage collected. For more information about the Ruby garbage
-collector please refer to http://rubygarden.org/ruby/ruby?GCAndExtensions.
+garbage collected.
The Ruby C/API provides extension developers two hooks into
the garbage collector - a "mark" function and a "sweep" function. By
@@ -4636,7 +4654,7 @@ any memory has been allocated in creating the underlying C struct or
C++ struct, then a "free" function must be defined that deallocates
this memory.
The remaining parts of this section will use the class library
@@ -4818,7 +4836,7 @@ public:
class Zoo
{
protected:
- std::vector<animal *=""> animals;
+ std::vector<Animal *> animals;
public:
// Construct an empty zoo
@@ -4941,7 +4959,8 @@ class-by-class basis if needed. To fix the example above:
/* Tell SWIG that create_animal creates a new object */%newobject Zoo::create_animal;
-/* Tell SWIG to keep track of mappings between C/C++ structs/classes. */%trackobjects;
+/* Tell SWIG to keep track of mappings between C/C++ structs/classes. */
+%trackobjects;
%include "example.h"
@@ -5006,7 +5025,7 @@ However, if you implement your own free functions (see below) you may
also have to call the SWIG_RubyRemoveTracking and RubyUnlinkObjects
methods.
-
With a bit more testing, we see that our class library still
@@ -5101,7 +5120,7 @@ static void mark_Zoo(void* ptr) {
Note the mark function is dependent on
the SWIG_RUBY_InstanceFor method, and thus
requires that %trackobjects is enabled. For more
-information, please refer to the track_object.i test case in the SWIG
+information, please refer to the ruby_track_objects.i test case in the SWIG
test suite.
When this code is compiled we now see:
@@ -5135,7 +5154,7 @@ irb(main):016:0>
This code can be seen in swig/examples/ruby/mark_function.
By default, SWIG creates a "free" function that is called when
@@ -5168,21 +5187,23 @@ above.
To show how to use the %freefunc
directive, let's slightly change our example. Assume that the zoo
-object is responsible for freeing animal that it contains. This means
+object is responsible for freeing any animal that it contains. This means
that the Zoo::add_animal
function should be marked with a DISOWN typemap
and the destructor should be updated as below:
@@ -5230,8 +5251,7 @@ existing Ruby object to the destroyed C++ object and raise an exception.
#include "example.h"
%}
-/* Specify that ownership is transferred to the zoo
- when calling add_animal */
+/* Specify that ownership is transferred to the zoo when calling add_animal */
%apply SWIGTYPE *DISOWN { Animal* animal };
/* Track objects */
@@ -5302,7 +5322,7 @@ been freed, and thus raises a runtime exception.
This code can be seen in swig/examples/ruby/free_function.
As has been said, the Ruby GC runs and marks objects before
diff --git a/Doc/Manual/SWIG.html b/Doc/Manual/SWIG.html
index 774e00b23..3c8565fdc 100644
--- a/Doc/Manual/SWIG.html
+++ b/Doc/Manual/SWIG.html
@@ -1,12 +1,13 @@
-
+
@@ -110,7 +111,7 @@ where filename is a SWIG interface file or a C/C++ header file.
Below is a subset of options that can be used.
Additional options are also defined for each target language. A full list
can be obtained by typing swig -help or swig
--lang -help.
+-<lang> -help for language <lang> specific options.
@@ -119,44 +120,50 @@ can be obtained by typing swig -help or swig
-clisp Generate CLISP wrappers
-cffi Generate CFFI wrappers
-csharp Generate C# wrappers
+-d Generate D wrappers
-go Generate Go wrappers
-guile Generate Guile wrappers
-java Generate Java wrappers
+-javascript Generate Javascript wrappers
-lua Generate Lua wrappers
-modula3 Generate Modula 3 wrappers
-mzscheme Generate Mzscheme wrappers
-ocaml Generate Ocaml wrappers
+-octave Generate Octave wrappers
-perl Generate Perl wrappers
--php Generate PHP wrappers
+-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
--c++ Enable C++ parsing
--cppext ext Change file extension of C++ generated files to ext (default is cxx, except for PHP which uses cpp)
+-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
--Fstandard Display error/warning messages in commonly used format
-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
--lfile Include a SWIG library file.
+-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 Show location of SWIG library
--version Show SWIG version number
+-swiglib Report location of SWIG library and exit
+-version Display SWIG version number
@@ -203,7 +210,7 @@ semantics in SWIG is analogous to that of the declarations section
used in input files to parser generation tools such as yacc or bison.
@@ -1052,7 +1058,7 @@ In this case f1, f2, and buffer are all
opaque objects containing C pointers. It doesn't matter what value
they contain--our program works just fine without this knowledge.
@@ -1297,7 +1303,7 @@ don't work correctly if Vector doesn't define a default
constructor. The section on SWIG and C++ has more information about this case.
// File : interface.i
-int a; // Can read/write
+int a; // Can read/write
%immutable;
-int b,c,d // Read only variables
+int b,c,d; // Read only variables
%mutable;
-double x,y // read/write
+double x,y; // read/write
@@ -1668,10 +1674,10 @@ generate a warning message. Simply change the directives to %immutable;%mutable; to silence the warning. Don't forget the extra semicolon!
@@ -1769,7 +1775,7 @@ This directive is still supported, but it is deprecated and should probably be a
directive is more powerful and better supports wrapping of raw header file information.
@@ -1883,6 +1889,13 @@ and a more descriptive one, but the two functions are otherwise equivalent:
literally, e.g. %rename("strip:[wx]")
wxPrint
Print
+
+
rstrip:[suffix]
+
String without the given suffix or the original string if it doesn't
+ end with this suffix. Note that square brackets should be used
+ literally, e.g. %rename("rstrip:[Cls]")
+
PrintCls
Print
+
regex:/pattern/subst/
String after (Perl-like) regex substitution operation. This function
@@ -1971,7 +1984,7 @@ are exactly equivalent and %rename can be used to selectively ignore
multiple declarations using the previously described matching possibilities.
-
@@ -2128,8 +2141,8 @@ default arguments are optional in the target language. For example, this functio
used in Tcl as follows :
-% plot -3.4 7.5 # Use default value
-% plot -3.4 7.5 10 # set color to 10 instead
+% plot -3.4 7.5 # Use default value
+% plot -3.4 7.5 10 # set color to 10 instead
@@ -2301,7 +2314,7 @@ See the Typemaps chapter for more about typ
and individual target language chapters for more on callbacks and the 'director' feature.
@@ -2383,7 +2396,7 @@ delete_Vector(v)
However, most of SWIG's language modules also provide a high-level interface that is more convenient. Keep reading.
-
@@ -2575,7 +2589,7 @@ is a structure or class. For instance, if you had a structure like this,
struct Foo {
- WORD w;
+ WORD w;
};
@@ -2604,7 +2618,7 @@ class, or union. This is unlikely to break existing code. However, if you need
datatype is really a struct, simply use a forward struct declaration such as "struct Foo;".
-
typedef struct Integer {
- int value;
+ int value;
} Int;
%extend Integer { ... } /* Correct name */
%extend Int { ... } /* Incorrect name */
struct Float {
- float value;
+ float value;
};
typedef struct Float FloatValue;
%extend Float { ... } /* Correct name */
@@ -2865,7 +2879,7 @@ There is one exception to this rule and that is when the struct is anonymously n
@@ -3122,7 +3136,7 @@ additional C code to perform initialization or other operations.
There are four common ways to insert code, but it's useful to know how the
output of SWIG is structured first.
@@ -3248,7 +3262,7 @@ there is a special inlined form of code block that is used as follows
%inline %{
/* Create a new vector */
Vector *new_Vector() {
- return (Vector *) malloc(sizeof(Vector));
+ return (Vector *) malloc(sizeof(Vector));
}
%}
@@ -3263,7 +3277,7 @@ declaration. Since the code inside an %inline %{ ... %} block
is given to both the C compiler and SWIG, it is illegal to include any
SWIG directives inside a %{ ... %} block.
@@ -3286,7 +3300,7 @@ This section describes the general approach for building interfaces
with SWIG. The specifics related to a particular scripting language
are found in later chapters.
@@ -3393,7 +3407,7 @@ The main advantage of this approach is minimal maintenance of an interface file
In more complex projects, an interface file containing numerous %include and #include statements like this is one of the most common approaches to interface file design due to lower maintenance overhead.
@@ -231,7 +232,7 @@ details. The SWIG Wiki also has further details.
The -noproxy commandline option is recognised by many target languages and will generate just this
interface as in earlier versions.
-
@@ -302,19 +303,19 @@ For example, in Python, the proxy might look roughly like this:
class Foo:
def __init__(self):
- self.this = new_Foo()
+ self.this = new_Foo()
def __del__(self):
- delete_Foo(self.this)
+ delete_Foo(self.this)
def bar(self,x):
- return Foo_bar(self.this,x)
+ return Foo_bar(self.this,x)
def __getattr__(self,name):
- if name == 'x':
- return Foo_x_get(self.this)
- ...
+ if name == 'x':
+ return Foo_x_get(self.this)
+ ...
def __setattr__(self,name,value):
- if name == 'x':
- Foo_x_set(self.this,value)
- ...
+ if name == 'x':
+ Foo_x_set(self.this,value)
+ ...
@@ -325,7 +326,7 @@ Whenever possible, proxies try to take advantage of language features that are s
might include operator overloading, exception handling, and other features.
-
@@ -479,7 +480,7 @@ every possible memory management problem. However, proxies do provide a mechani
can be used (if necessary) to address some of the more tricky memory management problems.
-
@@ -487,7 +488,7 @@ Language specific details on proxy classes are contained in the chapters describ
chapter has merely introduced the topic in a very general way.
@@ -520,7 +521,7 @@ To generate wrappers for this class, SWIG first reduces the class to a collectio
accessor functions which are then used by the proxy classes.
@@ -703,9 +704,9 @@ First, SWIG won't generate wrappers for protected or private constructors. For
class Foo {
protected:
- Foo(); // Not wrapped.
+ Foo(); // Not wrapped.
public:
- ...
+ ...
};
@@ -719,8 +720,8 @@ pure virtual methods. Here are some examples:
class Bar {
public:
- Bar(); // Not wrapped. Bar is abstract.
- virtual void spam(void) = 0;
+ Bar(); // Not wrapped. Bar is abstract.
+ virtual void spam(void) = 0;
};
class Grok : public Bar {
@@ -753,8 +754,8 @@ non-abstract using this:
class Foo : public Bar {
public:
- Foo(); // Generated no matter what---not abstract.
- ...
+ Foo(); // Generated no matter what---not abstract.
+ ...
};
@@ -763,7 +764,7 @@ public:
More information about %feature can be found in the Customization features chapter.
-
@@ -891,7 +892,7 @@ wrapper functions. However, the name and calling convention of the
low-level procedural wrappers match the accessor function prototype described above.
-
@@ -932,7 +933,7 @@ class List {
public:
...
%immutable;
- int length;
+ int length;
%mutable;
...
};
@@ -947,9 +948,9 @@ Alternatively, you can specify an immutable member in advance like this:
%immutable List::length;
...
class List {
- ...
- int length; // Immutable by above directive
- ...
+ ...
+ int length; // Immutable by above directive
+ ...
};
@@ -1077,7 +1078,7 @@ like this
struct Foo {
- size_t len;
+ size_t len;
};
@@ -1093,7 +1094,7 @@ a few problems related to structure wrapping and some of SWIG's
customization features.
-
@@ -1175,10 +1176,10 @@ The following example illustrates this:
class Foo {
private:
- static const int spam;
+ static const int spam;
public:
- void bar(int x, int y = spam); // Won't work with %feature("compactdefaultargs") -
- // private default value
+ void bar(int x, int y = spam); // Won't work with %feature("compactdefaultargs") -
+ // private default value
};
@@ -1199,7 +1200,7 @@ Keyword arguments are a language feature of some scripting languages, for exampl
SWIG is unable to support kwargs when wrapping overloaded methods, so the default approach cannot be used.
-
@@ -1298,9 +1299,9 @@ namespace bar {
class Foo {
public:
- ...
- friend void blah(Foo *f);
- ...
+ ...
+ friend void blah(Foo *f);
+ ...
};
}
@@ -1310,7 +1311,7 @@ namespace bar {
and a wrapper for the method 'blah' will not be generated.
-
typedef struct {
- ...
+ ...
} Foo;
class Bar : public Foo { // Ok.
@@ -1700,7 +1701,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
@@ -1740,23 +1741,23 @@ inheritance. For example, suppose you had code like this:
class A {
public:
- int x;
+ int x;
};
class B {
public:
- int y;
+ int y;
};
class C : public A, public B {
};
int A_function(A *a) {
- return a->x;
+ return a->x;
}
int B_function(B *b) {
- return b->y;
+ return b->y;
}
@@ -1832,7 +1833,7 @@ int y = B_function((B *) pB);
In practice, the pointer is held as an integral number in the target language proxy class.
-
@@ -2020,7 +2021,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.
@@ -2138,7 +2139,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.
@@ -2442,10 +2443,10 @@ that differ only in their qualifiers, like this:
class Spam {
public:
- ...
- void bar(); // Unqualified member
- void bar() const; // Qualified member
- ...
+ ...
+ void bar(); // Unqualified member
+ void bar() const; // Qualified member
+ ...
};
@@ -2481,6 +2482,7 @@ above:
Currently no resolution is performed in order to match function parameters. This means function parameter types must match exactly.
For example, namespace qualifiers and typedefs will not work. The following usage of typedefs demonstrates this:
+
@@ -2490,11 +2492,11 @@ typedef int Integer;
class Spam {
public:
- void foo(Integer); // Stays 'foo' (not renamed)
+ void foo(Integer); // Stays 'foo' (not renamed)
};
class Ham {
public:
- void foo(int); // Renamed to foo_i
+ void foo(int); // Renamed to foo_i
};
@@ -2509,9 +2511,9 @@ Let's consider the following example class:
@@ -2584,7 +2586,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.
@@ -2761,14 +2763,33 @@ have to handle it like a normal function. For example:
Certain operators are ignored by default. For instance, new and delete operators
-are ignored as well as conversion operators.
-
+are ignored as well as conversion and index operators. A warning such as the one below is shown:
+
+
+
+
+example.i:12: Warning 503: Can't wrap 'operator []' unless renamed to a valid identifier.
+
+
+
+
+
The index operator, operator[], is particularly difficult to overload due to differences in C++
+implementations. Specifically, the get and set operators in other languages typically are separated
+into two methods such that additional logic can be packed into the operations; C# uses
+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.
+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.
+
+
The semantics of certain C++ operators may not match those in the target language.
@@ -3124,7 +3145,7 @@ For example, if you wrote code like this,
%template(intList) List<int>;
...
class UltraList : public List<int> {
- ...
+ ...
};
@@ -3312,8 +3333,8 @@ look like this:
class Foo {
public:
- template<class T> void bar(T x, T y) { ... };
- ...
+ template<class T> void bar(T x, T y) { ... };
+ ...
};
...
@@ -3411,9 +3432,9 @@ template class. Here is a slightly perverse example:
// A template
template<class T> class Foo {
public:
- // A member template
- template<class S> T bar(S x, S y) { ... };
- ...
+ // A member template
+ template<class S> T bar(S x, S y) { ... };
+ ...
};
// Expand a few member templates
@@ -3441,12 +3462,12 @@ and conversions. For example:
@@ -3525,19 +3546,19 @@ included directly in template definitions. For example:
// File : list.h
template<class T> class List {
- ...
+ ...
public:
- %rename(__getitem__) get(int);
- List(int max);
- ~List();
- ...
- T get(int index);
- %extend {
- char *__str__() {
- /* Make a string representation */
- ...
- }
+ %rename(__getitem__) get(int);
+ List(int max);
+ ~List();
+ ...
+ T get(int index);
+ %extend {
+ char *__str__() {
+ /* Make a string representation */
+ ...
}
+ }
};
@@ -3554,14 +3575,14 @@ It is also possible to separate these declarations from the template class. For
%rename(__getitem__) List::get;
%extend List {
- char *__str__() {
- /* Make a string representation */
- ...
- }
- /* Make a copy */
- T *__copy__() {
- return new List<T>(*$self);
- }
+ char *__str__() {
+ /* Make a string representation */
+ ...
+ }
+ /* Make a copy */
+ T *__copy__() {
+ return new List<T>(*$self);
+ }
};
...
@@ -3701,7 +3722,7 @@ as the class name. For example:
Similar changes apply to typemaps and other customization features.
-
@@ -3796,18 +3817,18 @@ namespace A {
}
namespace B {
- namespace C {
- using namespace A;
- }
- typedef C::Foo FooClass;
+ namespace C {
+ using namespace A;
+ }
+ typedef C::Foo FooClass;
}
namespace BIGB = B;
namespace D {
- using BIGB::FooClass;
- class Bar : public FooClass {
- }
+ using BIGB::FooClass;
+ class Bar : public FooClass {
+ }
};
class Spam : public D::Bar {
@@ -3841,12 +3862,12 @@ you have code like this,
@@ -3880,10 +3901,10 @@ namespaces to generate a name conflict in the target language. For example:
namespace A {
- void foo(int);
+ void foo(int);
}
namespace B {
- void foo(double);
+ void foo(double);
}
@@ -3908,10 +3929,10 @@ To resolve this error, simply use %rename to disambiguate the declarati
%rename(B_foo) B::foo;
...
namespace A {
- void foo(int);
+ void foo(int);
}
namespace B {
- void foo(double); // Gets renamed to B_foo
+ void foo(double); // Gets renamed to B_foo
}
@@ -3930,7 +3951,7 @@ system to track type-names. Therefore, if you have code like this:
namespace A {
- typedef int Integer;
+ typedef int Integer;
}
using namespace A;
void foo(Integer x);
@@ -3979,18 +4000,18 @@ typemaps, exception handlers, and so forth. For example, consider the following
namespace foo {
- typedef int Integer;
- class bar {
+ typedef int Integer;
+ class bar {
public:
- ...
- };
+ ...
+ };
}
%extend foo::bar {
- Integer add(Integer x, Integer y) {
- Integer r = x + y; // Error. Integer not defined in this scope
- return r;
- }
+ Integer add(Integer x, Integer y) {
+ Integer r = x + y; // Error. Integer not defined in this scope
+ return r;
+ }
};
@@ -4005,10 +4026,10 @@ To fix the problem, make sure you use fully qualified names. For example:
%extend foo::bar {
- Integer add(Integer x, Integer y) {
- foo::Integer r = x + y; // Ok.
- return r;
- }
+ Integer add(Integer x, Integer y) {
+ foo::Integer r = x + y; // Ok.
+ return r;
+ }
};
@@ -4035,17 +4056,17 @@ these directives, consider the following:
// Good version
%inline %{
namespace foo {
- void bar(int) { ... }
- ...
+ void bar(int) { ... }
+ ...
}
%}
// Bad version. Emitted code not placed in namespace.
namespace foo {
%inline %{
- void bar(int) { ... } /* I'm bad */
- ...
-%}
+ void bar(int) { ... } /* I'm bad */
+ ...
+ %}
}
@@ -4058,12 +4079,12 @@ included in the generated functions. For example, if you have code like this,
namespace foo {
- class bar {
- public:
- %extend {
- int blah(int x);
- };
- };
+ class bar {
+ public:
+ %extend {
+ int blah(int x);
+ };
+ };
}
@@ -4086,13 +4107,13 @@ conflicts in the input, there will be no conflicts in the generated code.
namespace foo {
- class bar;
- class spam {
- public:
- ...
- operator bar(); // Conversion of spam -> bar
- ...
- };
+ class bar;
+ class spam {
+ public:
+ ...
+ operator bar(); // Conversion of spam -> bar
+ ...
+ };
}
@@ -4126,13 +4147,13 @@ Note, however, that if the operator is defined using a qualifier in its name, th
%rename(tofoo) foo::spam::operator bar(); // will not match
%rename(tofoo) foo::spam::operator foo::bar(); // will match
namespace foo {
- class bar;
- class spam {
- public:
- ...
- operator foo::bar();
- ...
- };
+ class bar;
+ class spam {
+ public:
+ ...
+ operator foo::bar();
+ ...
+ };
}
@@ -4150,7 +4171,7 @@ with any namespace awareness. In the future, language modules may or may not p
more advanced namespace support.
-
@@ -4634,8 +4655,8 @@ class Foo { // Ignored
class Bar {
public:
- Foo *operator->();
- ...
+ Foo *operator->();
+ ...
};
@@ -4672,11 +4693,12 @@ p = f.__deref__() # Raw pointer from operator->
Note: Smart pointer support was first added in SWIG-1.3.14.
-
6.25 C++ reference counted objects - ref/unref feature
Another similar idiom in C++ is the use of reference counted objects. Consider for example:
+
@@ -4693,11 +4715,11 @@ public:
return add_ref();
}
- int unref() const {
+ int unref() const {
if (ref_count() == 0 || del_ref() == 0 ) {
- delete this;
- return 0;
- }
+ delete this;
+ return 0;
+ }
return ref_count();
}
};
@@ -4782,14 +4804,14 @@ different to any other regular instance:
def create_A():
- a = A() # SWIG ref 'a' - new object is passed to python (count: 1)
- b1 = B(a) # C++ ref 'a (count: 2)
- if 1 + 1 == 2:
- b2 = B(a) # C++ ref 'a' (count: 3)
- return a # 'b1' and 'b2' are released and deleted, C++ unref 'a' twice (count: 1)
+ a = A() # SWIG ref 'a' - new object is passed to python (count: 1)
+ b1 = B(a) # C++ ref 'a (count: 2)
+ if 1 + 1 == 2:
+ b2 = B(a) # C++ ref 'a' (count: 3)
+ return a # 'b1' and 'b2' are released and deleted, C++ unref 'a' twice (count: 1)
-a = create_A() # (count: 1)
-exit # 'a' is released, SWIG unref 'a' called in the destructor wrapper (count: 0)
+a = create_A() # (count: 1)
+exit # 'a' is released, SWIG unref 'a' called in the destructor wrapper (count: 0)
@@ -4844,7 +4866,7 @@ exit # 'a' is released, SWIG unref 'a' called in the destructor wra
-
@@ -4973,14 +4995,14 @@ won't cause a conflict. For example:
class Foo {
public:
- int blah(int );
- double blah(double);
+ int blah(int );
+ double blah(double);
};
class Bar : public Foo {
public:
- using Foo::blah; // Only imports blah(double);
- int blah(int);
+ using Foo::blah; // Only imports blah(double);
+ int blah(int);
};
@@ -4994,20 +5016,20 @@ imported by using. For example:
%rename(blah_long) Foo::blah(long);
class Foo {
public:
- int blah(int);
- long blah(long); // Renamed to blah_long
+ int blah(int);
+ long blah(long); // Renamed to blah_long
};
class Bar : public Foo {
public:
- using Foo::blah; // Only imports blah(int)
- double blah(double x);
+ using Foo::blah; // Only imports blah(int)
+ double blah(double x);
};
-
@@ -5098,7 +5120,7 @@ void bar(Object *);
...
// C++ code
void blah() {
- bar(foo()); // Error: bar discards const
+ bar(foo()); // Error: bar discards const
};
@@ -5129,7 +5151,7 @@ using another tool if maintaining constness is the most important part
of your project.
@@ -201,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.
@@ -225,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.
@@ -259,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.
-SWIG for Scilab provides only a low-level C interface for Scilab (see Scripting Languages for the general approach to wrapping).
+SWIG for Scilab provides only a low-level C interface for Scilab (see Scripting Languages for the general approach to wrapping).
This means that functions, structs, classes, variables, etc... are interfaced through C functions. These C functions are mapped as Scilab functions.
There are a few exceptions, such as constants and enumerations, which can be wrapped directly as Scilab variables.
@@ -337,7 +338,7 @@ In Scilab 5.x, identifier names are composed of 24 characters maximum (this limi
In these cases, the %rename directive can be used to choose a different Scilab name.
@@ -442,14 +443,15 @@ The example below shows this for a C function returning 2 values and a result:
int divide(int n, int d, int *OUTPUT, int *OUTPUT);
%{
-int divide(int n, int d, int q*, int *r) {
- if (d != 0) {
- *q = n / d;
- *r = n % d;
- return 1;
- }
- else return 0;
-}
+ int divide(int n, int d, int q*, int *r) {
+ if (d != 0) {
+ *q = n / d;
+ *r = n % d;
+ return 1;
+ } else {
+ return 0;
+ }
+ }
%}
@@ -469,7 +471,7 @@ int divide(int n, int d, int q*, int *r) {
-
-C/C++ pointers are fully supported by SWIG. They are mapped to the Scilab pointer type ("pointer", type ID: 128).
+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.
+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.
-Given a wrapping of some of the C file functions:
+Notes:
+
+
+
type tracking needs the SWIG runtime to be first initialized with the appropriate function (see the Module initialization section).
+
for any reason, if a wrapped pointer type is unknown (or if the SWIG runtime is not initialized), SWIG maps it to a Scilab pointer. Also, a Scilab pointer is always accepted as a pointer argument of a wrapped function. The drawaback is that pointer type is lost.
+
+
+
+Following is an example of the wrapping of the C FILE* pointer:
@@ -771,29 +787,35 @@ int fclose(FILE *);
-These functions can be used in a natural way from Scilab:
+These functions can be used the same way as in C from Scilab:
+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).
-Most of time pointer manipulation is not needed in a scripting language such as Scilab.
+As a scripting language, Scilab does not provide functions to manipulate pointers.
However, in some cases it can be useful, such as for testing or debugging.
@@ -805,7 +827,11 @@ SWIG comes with two pointer utility functions:
SWIG_ptr(): creates a pointer from an address value
-
Following illustrates their use on the last example:
+
+Note: a pointer created by SWIG_ptr() does not have any type and is mapped as a Scilab pointer.
+
+
+
Following we use the utility functions on the previous example:
--> f = fopen("junk", "w");
@@ -816,15 +842,21 @@ SWIG comes with two pointer utility functions:
8219088.
--> p = SWIG_ptr(addr);
+--> typeof(p)
+ans =
+
+ pointer
+
--> fputs(" World", p);
--> fclose(f);
By default, Scilab does not provide a way to test or create null pointers.
-But it is possible to have a null pointer by using the previous functions SWIG_this() and SWIG_ptr(), like this:
+
+Using the previous SWIG_this() and SWIG_ptr(), it is possible to create and check null pointers:
@@ -836,7 +868,7 @@ But it is possible to have a null pointer by using the previous functions SW
@@ -981,7 +1027,25 @@ ans =
--> delete_Point(p2);
-
39.3.9 C++ inheritance
+
+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:
+
+
+
+--> function %_p_Point_p(p)
+--> mprintf('[%d, %d]\n', Point_x_get(p), Point_y_get(p));
+--> endfunction
+
+--> example_Init();
+--> p = new_Point(1, 2)
+ p =
+
+[1, 2]
+
+--> delete_Point(p);
+
+As explained in 6.15 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:
+
@@ -1114,7 +1218,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.
@@ -1122,8 +1226,7 @@ As in other languages, function and class templates are supported in SWIG Scilab
-You have to tell SWIG to create wrappers for a particular
-template instantiation. The %template directive is used for this purpose.
+You have to tell SWIG to create wrappers for a particular template instantiation. The %template directive is used for this purpose.
For example:
@@ -1174,7 +1277,7 @@ Then in Scilab:
More details on template support can be found in the templates documentation.
-
@@ -1388,17 +1491,17 @@ More complex or custom exception types require specific exception typemaps to be
See the SWIG C++ documentation for more details.
@@ -68,7 +69,7 @@ languages can be used for rapid prototyping, interactive debugging,
scripting, and access to high-level data structures such associative
arrays.
@@ -165,7 +167,7 @@ Python. Both require special wrappers to be written and both need
additional initialization code. Only the specific details are
different.
-
@@ -109,7 +110,7 @@ build a Tcl extension module. To finish building the module, you
need to compile this file and link it with the rest of your program.
@@ -440,7 +441,7 @@ erratic program behavior. If working with lots of software components, you
might want to investigate using a more formal standard such as COM.
@@ -836,8 +837,8 @@ access constants in procedure bodies. For example:
proc blah {} {
- global FOO
- bar $FOO
+ global FOO
+ bar $FOO
}
@@ -864,7 +865,7 @@ its actual value or a symbolic identifier name. For example:
proc blah {} {
- bar FOO
+ bar FOO
}
@@ -874,7 +875,7 @@ When an identifier name is given, it is used to perform an implicit hash-table l
conversion. This allows the global statement to be omitted.
-
@@ -1661,10 +1661,10 @@ submodules or packages. For example, if you have a file like this,
%module example
namespace foo {
- int fact(int n);
- struct Vector {
- double x,y,z;
- };
+ int fact(int n);
+ struct Vector {
+ double x,y,z;
+ };
};
@@ -1711,7 +1711,7 @@ utilizes thousands of small deeply nested namespaces each with
identical symbol names, well, then you get what you deserve.
@@ -2327,7 +2327,7 @@ class DoubleArray {
}
// Destroy an array
~DoubleArray() {
- delete ptr;
+ delete ptr;
}
// Return the length of the array
int length() {
@@ -2435,7 +2435,7 @@ Since SWIG's exception handling is user-definable, you are not limited to C++ ex
See the chapter on "Customization Features" for more examples.
@@ -2465,8 +2465,9 @@ you might define a typemap like this:
%module example
%typemap(in) int {
- if (Tcl_GetIntFromObj(interp,$input,&$1) == TCL_ERROR) return TCL_ERROR;
- printf("Received an integer : %d\n",$1);
+ if (Tcl_GetIntFromObj(interp,$input,&$1) == TCL_ERROR)
+ return TCL_ERROR;
+ printf("Received an integer : %d\n",$1);
}
%inline %{
extern int fact(int n);
@@ -2503,8 +2504,9 @@ You can refine this by supplying an optional parameter name. For example:
%module example
%typemap(in) int n {
- if (Tcl_GetIntFromObj(interp,$input,&$1) == TCL_ERROR) return TCL_ERROR;
- printf("n = %d\n",$1);
+ if (Tcl_GetIntFromObj(interp,$input,&$1) == TCL_ERROR)
+ return TCL_ERROR;
+ printf("n = %d\n",$1);
}
%inline %{
extern int fact(int n);
@@ -2526,8 +2528,9 @@ the typemap system follows typedef declarations. For example:
%typemap(in) int n {
- if (Tcl_GetIntFromObj(interp,$input,&$1) == TCL_ERROR) return TCL_ERROR;
- printf("n = %d\n",$1);
+ if (Tcl_GetIntFromObj(interp,$input,&$1) == TCL_ERROR)
+ return TCL_ERROR;
+ printf("n = %d\n",$1);
}
%inline %{
typedef int Integer;
@@ -2569,7 +2572,7 @@ parameter is omitted):
@@ -2851,21 +2854,21 @@ function argument. For example :
// A typemap defining how to return an argument by appending it to the result
%typemap(argout) double *outvalue {
- Tcl_Obj *o = Tcl_NewDoubleObj($1);
- Tcl_ListObjAppendElement(interp,$result,o);
+ Tcl_Obj *o = Tcl_NewDoubleObj($1);
+ Tcl_ListObjAppendElement(interp,$result,o);
}
// A typemap telling SWIG to ignore an argument for input
// However, we still need to pass a pointer to the C function
%typemap(in,numinputs=0) double *outvalue (double temp) {
- $1 = &temp;
+ $1 = &temp;
}
// Now a function returning two values
int mypow(double a, double b, double *outvalue) {
- if ((a < 0) || (b < 0)) return -1;
- *outvalue = pow(a,b);
- return 0;
+ if ((a < 0) || (b < 0)) return -1;
+ *outvalue = pow(a,b);
+ return 0;
};
@@ -2882,7 +2885,7 @@ result, a Tcl function using these typemaps will work like this :
%
-
@@ -3153,8 +3161,8 @@ subdirectory which has the same name as the package. For example :
./example/
- pkgIndex.tcl # The file created by pkg_mkIndex
- example.so # The SWIG generated module
+ pkgIndex.tcl # The file created by pkg_mkIndex
+ example.so # The SWIG generated module
@@ -3191,7 +3199,7 @@ As a final note, most SWIG examples do not yet use the
to use the load command instead.
-
40.9 Building new kinds of Tcl interfaces (in Tcl)
set a [Array double 100] ;# Create a double [100]
for {set i 0} {$i < 100} {incr i 1} { ;# Clear the array
- $a set $i 0.0
+ $a set $i 0.0
}
$a set 3 3.1455 ;# Set an individual element
set b [$a get 10] ;# Retrieve an element
set ia [Array int 50] ;# Create an int[50]
for {set i 0} {$i < 50} {incr i 1} { ;# Clear it
- $ia set $i 0
+ $ia set $i 0
}
$ia set 3 7 ;# Set an individual element
set ib [$ia get 10] ;# Get an individual element
@@ -3290,7 +3298,7 @@ danger of blowing something up (although it is easily accomplished
with an out of bounds array access).
-
@@ -112,7 +116,7 @@ to re-read the earlier chapters if you have found your way to this
chapter with only a vague idea of what SWIG already does by default.
@@ -306,7 +310,7 @@ parts of the generated wrapper functions. Because arbitrary code can be insert
possible to completely change the way in which values are converted.
-
@@ -319,7 +323,7 @@ it is applied to all future occurrences of that type in the input file. For exa
/* Convert from Perl --> C */
%typemap(in) int {
- $1 = SvIV($input);
+ $1 = SvIV($input);
}
...
@@ -340,12 +344,12 @@ underlying type. For example, you could have code like this:
/* Convert from Ruby--> C */
%typemap(in) int {
- $1 = NUM2INT($input);
+ $1 = NUM2INT($input);
}
...
typedef int Integer;
namespace foo {
- typedef Integer Number;
+ typedef Integer Number;
};
int foo(int x);
@@ -369,11 +373,11 @@ example, you could write a typemap like this:
%typemap(in) double nonnegative {
- $1 = PyFloat_AsDouble($input);
- if ($1 < 0) {
- PyErr_SetString(PyExc_ValueError,"argument must be nonnegative.");
- return NULL;
- }
+ $1 = PyFloat_AsDouble($input);
+ if ($1 < 0) {
+ PyErr_SetString(PyExc_ValueError,"argument must be nonnegative.");
+ SWIG_fail;
+ }
}
...
@@ -395,8 +399,8 @@ consecutive arguments. For example:
%typemap(in) (char *str, int len) {
- $1 = PyString_AsString($input); /* char *str */
- $2 = PyString_Size($input); /* int len */
+ $1 = PyString_AsString($input); /* char *str */
+ $2 = PyString_Size($input); /* int len */
}
...
int count(char *str, int len, char c);
@@ -408,7 +412,7 @@ In this case, a single input object is expanded into a pair of C arguments. Thi
provides a hint to the unusual variable naming scheme involving $1, $2, and so forth.
-
@@ -430,12 +434,12 @@ A more general form of copying is found in the %apply directive like th
%typemap(in) int {
- /* Convert an integer argument */
- ...
+ /* Convert an integer argument */
+ ...
}
%typemap(out) int {
- /* Return an integer value */
- ...
+ /* Return an integer value */
+ ...
}
/* Apply all of the integer typemaps to size_t */
@@ -464,7 +468,7 @@ typedef int size_t;
then SWIG already knows that the int typemaps apply. You don't have to do anything.
-
@@ -545,7 +549,7 @@ int foo(int x, double y, char *s);
struct Foo {
- int x[20];
+ int x[20];
};
@@ -576,7 +580,7 @@ typemaps that expand upon this list. For example, the Java module defines a var
aspects of the Java bindings. Consult language specific documentation for further details.
-
@@ -653,11 +657,11 @@ The %feature.
+SWIG can also be viewed as has having a second set of aspects based around %feature.
Features such as %exception are also cross-cutting concerns as they encapsulate code that can be used to add logging or exception handling to any function.
@@ -677,14 +681,14 @@ of "The C Programming Language" by Kernighan and Ritchie or
"The C++ Programming Language" by Stroustrup before going any further.
Note that the preprocessor will expand code within the {} delimiters, but not in the last two styles of delimiters,
-see Preprocessor and Typemaps.
+see Preprocessor and Typemaps.
Here are some examples of valid typemap specifications:
@@ -755,21 +759,21 @@ Here are some examples of valid typemap specifications:
/* Simple typemap declarations */
%typemap(in) int {
- $1 = PyInt_AsLong($input);
+ $1 = PyInt_AsLong($input);
}
%typemap(in) int "$1 = PyInt_AsLong($input);";
%typemap(in) int %{
- $1 = PyInt_AsLong($input);
+ $1 = PyInt_AsLong($input);
%}
/* Typemap with extra argument name */
%typemap(in) int nonnegative {
- ...
+ ...
}
/* Multiple types in one typemap */
%typemap(in) int, short, long {
- $1 = SvIV($input);
+ $1 = SvIV($input);
}
/* Typemap with modifiers */
@@ -779,15 +783,15 @@ Here are some examples of valid typemap specifications:
%typemap(in) (char *str, int len),
(char *buffer, int size)
{
- $1 = PyString_AsString($input);
- $2 = PyString_Size($input);
+ $1 = PyString_AsString($input);
+ $2 = PyString_Size($input);
}
/* Typemap with extra pattern parameters */
%typemap(in, numinputs=0) int *output (int temp),
long *output (long temp)
{
- $1 = &temp;
+ $1 = &temp;
}
@@ -797,7 +801,7 @@ Admittedly, it's not the most readable syntax at first glance. However, the pur
individual pieces will become clear.
-
@@ -833,7 +837,7 @@ subject to the typemap rules that are in effect at the point where the class its
class Foo {
- ...
+ ...
};
%typemap(in) int {
@@ -841,13 +845,13 @@ class Foo {
}
%extend Foo {
- int blah(int x); // typemap has no effect. Declaration is attached to Foo which
- // appears before the %typemap declaration.
+ int blah(int x); // typemap has no effect. Declaration is attached to Foo which
+ // appears before the %typemap declaration.
};
@@ -1026,7 +1030,7 @@ The section describes the pattern matching rules by which C/C++ datatypes are as
The matching rules can be observed in practice by using the debugging options also described.
@@ -1889,11 +1893,11 @@ for use during typemap execution. For example:
%typemap(in) short {
- long temp; /* Temporary value */
- if (Tcl_GetLongFromObj(interp, $input, &temp) != TCL_OK) {
- return TCL_ERROR;
- }
- $1 = (short) temp;
+ long temp; /* Temporary value */
+ if (Tcl_GetLongFromObj(interp, $input, &temp) != TCL_OK) {
+ return TCL_ERROR;
+ }
+ $1 = (short) temp;
}
@@ -1926,7 +1930,7 @@ a block scope when it is emitted. This sometimes results in a less complicated
Note that only the third of the three typemaps have the typemap code passed through the SWIG preprocessor.
-
@@ -1962,11 +1966,11 @@ then pass a pointer to the object. To do this, simply specify the typemap with
%typemap(in) std::string * (std::string temp) {
- unsigned int len;
- char *s;
- s = SvPV($input,len); /* Extract string data */
- temp.assign(s,len); /* Assign to temp */
- $1 = &temp; /* Set argument to point to temp */
+ unsigned int len;
+ char *s;
+ s = SvPV($input,len); /* Extract string data */
+ temp.assign(s,len); /* Assign to temp */
+ $1 = &temp; /* Set argument to point to temp */
}
@@ -1979,16 +1983,16 @@ the scope of the entire wrapper function. For example:
@@ -2357,7 +2361,7 @@ it is done during the SWIG parsing/compilation stages.
The following special variable macros are available across all language modules.
+Special variables can also be used within special variable macros.
+The special variables are expanded before they are used in the special variable macros.
+
@@ -2512,6 +2586,7 @@ to see whether or not it matches a specific type. For example:
For typechecking, the $1 variable is always a simple integer that is set to 1 or 0 depending on whether or not
the input argument is the correct type.
+Set to 1 if the input argument is the correct type otherwise set to 0.
@@ -2519,7 +2594,7 @@ If you define new "in" typemaps and your program uses overloaded method
"typecheck" typemaps. More details about this follow in the Typemaps and overloading section.
@@ -2550,7 +2625,7 @@ $symname - Name of function/method being wrapped
The "out" typemap supports an optional attribute flag called "optimal". This is for code optimisation and is detailed in the Optimal code generation when returning by value section.
-
%typemap(default) int flags {
- $1 = DEFAULT_FLAGS;
+ $1 = DEFAULT_FLAGS;
}
...
int foo(int x, int y, int flags);
@@ -2602,7 +2677,7 @@ See the Default/optional arguments sec
for further information on default argument wrapping.
-
@@ -2635,12 +2710,12 @@ with an "in" typemap---possibly to ignore the input value. For example:
/* Set the input argument to point to a temporary variable */
%typemap(in, numinputs=0) int *out (int temp) {
- $1 = &temp;
+ $1 = &temp;
}
%typemap(argout) int *out {
- // Append output value $1 to $result
- ...
+ // Append output value $1 to $result
+ ...
}
@@ -2667,7 +2742,7 @@ return values are often appended to return value of the function.
See the typemaps.i library file for examples.
-
// Get a list of integers
%typemap(in) int *items {
- int nitems = Length($input);
- $1 = (int *) malloc(sizeof(int)*nitems);
+ int nitems = Length($input);
+ $1 = (int *) malloc(sizeof(int)*nitems);
}
// Free the list
%typemap(freearg) int *items {
- free($1);
+ free($1);
}
@@ -2700,7 +2775,7 @@ be used in other typemaps whenever a wrapper function needs to abort
prematurely.
-
+The "ret" typemap is not used very often, but can be useful for anything associated with
+the return type, such as resource management, return value error checking, etc.
+Usually this can all be done in the "out" typemap, but sometimes it is handy to use the
+"out" typemap code untouched and add to the generated code using the code in the "ret" typemap.
+One such case is memory clean up. For example, a stringheap_t type is defined indicating
+that the returned memory must be deleted and a string_t type is defined indicating
+that the returned memory must not be deleted.
+
+The "ret" typemap above will only be used for MakeString2, but both functions
+will use the default "out" typemap for char * provided by SWIG.
+The code above would ensure the appropriate memory is freed in all target languages as the need
+to provide custom "out" typemaps (which involve target language specific code) is not necessary.
+
+
+
+This approach is an alternative to using the "newfree" typemap and %newobject as there
+is no need to list all the functions that require the memory cleanup, it is purely done on types.
+
@@ -2751,7 +2865,7 @@ It is rarely necessary to write "memberin" typemaps---SWIG already provides
a default implementation for arrays, strings, and other objects.
-
@@ -2759,7 +2873,7 @@ The "varin" typemap is used to convert objects in the target language to C for t
purposes of assigning to a C/C++ global variable. This is implementation specific.
@@ -2767,7 +2881,7 @@ The "varout" typemap is used to convert a C/C++ object to an object in the targe
language when reading a C/C++ global variable. This is implementation specific.
@@ -2813,7 +2926,7 @@ Note that if your methods do not have an exception specification yet they do thr
For a neat way to handle these, see the Exception handling with %exception section.
-
@@ -2851,11 +2964,11 @@ similar to this:
int i;
if (!PySequence_Check($input)) {
PyErr_SetString(PyExc_ValueError,"Expected a sequence");
- return NULL;
+ SWIG_fail;
}
if (PySequence_Length($input) != 4) {
PyErr_SetString(PyExc_ValueError,"Size mismatch. Expected 4 elements");
- return NULL;
+ SWIG_fail;
}
for (i = 0; i < 4; i++) {
PyObject *o = PySequence_GetItem($input,i);
@@ -2863,7 +2976,7 @@ similar to this:
temp[i] = (float) PyFloat_AsDouble(o);
} else {
PyErr_SetString(PyExc_ValueError,"Sequence elements must be numbers");
- return NULL;
+ SWIG_fail;
}
}
$1 = temp;
@@ -2896,11 +3009,11 @@ If you wanted to generalize the typemap to apply to arrays of all dimensions you
int i;
if (!PySequence_Check($input)) {
PyErr_SetString(PyExc_ValueError,"Expected a sequence");
- return NULL;
+ SWIG_fail;
}
if (PySequence_Length($input) != $1_dim0) {
PyErr_SetString(PyExc_ValueError,"Size mismatch. Expected $1_dim0 elements");
- return NULL;
+ SWIG_fail;
}
for (i = 0; i < $1_dim0; i++) {
PyObject *o = PySequence_GetItem($input,i);
@@ -2908,7 +3021,7 @@ If you wanted to generalize the typemap to apply to arrays of all dimensions you
temp[i] = (float) PyFloat_AsDouble(o);
} else {
PyErr_SetString(PyExc_ValueError,"Sequence elements must be numbers");
- return NULL;
+ SWIG_fail;
}
}
$1 = temp;
@@ -2924,7 +3037,7 @@ array dimensions. Multidimensional arrays can be matched in a similar manner.
@@ -2940,11 +3053,11 @@ as shown. To work with heap allocated data, the following technique can be use
int i;
if (!PySequence_Check($input)) {
PyErr_SetString(PyExc_ValueError,"Expected a sequence");
- return NULL;
+ SWIG_fail;
}
if (PySequence_Length($input) != $1_dim0) {
PyErr_SetString(PyExc_ValueError,"Size mismatch. Expected $1_dim0 elements");
- return NULL;
+ SWIG_fail;
}
$1 = (float *) malloc($1_dim0*sizeof(float));
for (i = 0; i < $1_dim0; i++) {
@@ -2952,14 +3065,14 @@ as shown. To work with heap allocated data, the following technique can be use
if (PyNumber_Check(o)) {
$1[i] = (float) PyFloat_AsDouble(o);
} else {
- PyErr_SetString(PyExc_ValueError,"Sequence elements must be numbers");
free($1);
- return NULL;
+ PyErr_SetString(PyExc_ValueError,"Sequence elements must be numbers");
+ SWIG_fail;
}
}
}
%typemap(freearg) float value[ANY] {
- if ($1) free($1);
+ if ($1) free($1);
}
@@ -2978,8 +3091,8 @@ For example, suppose you had a structure like this:
@@ -3080,7 +3193,7 @@ Now, you will find that member access is quite nice:
useless and has since been eliminated. To return structure members, simply use the "out" typemap.
-
@@ -3093,9 +3206,9 @@ checking the values of function arguments. For example:
%module math
%typemap(check) double posdouble {
- if ($1 < 0) {
- croak("Expecting a positive number");
- }
+ if ($1 < 0) {
+ croak("Expecting a positive number");
+ }
}
...
@@ -3114,10 +3227,10 @@ pointers. For example:
%typemap(check) Vector * {
- if ($1 == 0) {
- PyErr_SetString(PyExc_TypeError,"NULL Pointer not allowed");
- return NULL;
- }
+ if ($1 == 0) {
+ PyErr_SetString(PyExc_TypeError,"NULL Pointer not allowed");
+ SWIG_fail;
+ }
}
@@ -3128,7 +3241,7 @@ a NULL pointer. As a result, SWIG can often prevent a potential
segmentation faults or other run-time problems by raising an exception
rather than blindly passing values to the underlying C/C++ program.
-
@@ -3347,7 +3460,7 @@ example.i:7: Warning 475: optimal attribute usage in the out typemap.
However, it doesn't always get it right, for example when $1 is within some commented out code.
@@ -3395,16 +3508,16 @@ maps perform the conversion described for the above example:
int i;
if (!PyList_Check($input)) {
PyErr_SetString(PyExc_ValueError, "Expecting a list");
- return NULL;
+ SWIG_fail;
}
$1 = PyList_Size($input);
$2 = (char **) malloc(($1+1)*sizeof(char *));
for (i = 0; i < $1; i++) {
PyObject *s = PyList_GetItem($input,i);
if (!PyString_Check(s)) {
- free($2);
- PyErr_SetString(PyExc_ValueError, "List items must be strings");
- return NULL;
+ free($2);
+ PyErr_SetString(PyExc_ValueError, "List items must be strings");
+ SWIG_fail;
}
$2[i] = PyString_AsString(s);
}
@@ -3412,7 +3525,12 @@ maps perform the conversion described for the above example:
}
%typemap(freearg) (int argc, char *argv[]) {
- if ($2) free($2);
+ if ($2) free($2);
+}
+
+/* Required for C++ method overloading */
+%typecheck(SWIG_TYPECHECK_STRING_ARRAY) (int argc, char *argv[]) {
+ $1 = PyList_Check($input) ? 1 : 0;
}
@@ -3481,6 +3599,11 @@ Other directives such as %apply and %clear also work with mult
+
+Don't forget to also provide a suitable typemap for overloaded functions, such as %typecheck shown for foo above.
+This is only required if the function is overloaded in C++.
+
+
Although multi-argument typemaps may seem like an exotic, little used feature, there
are several situations where they make sense. First, suppose you wanted to wrap
@@ -3508,38 +3631,38 @@ might write typemaps like this:
// typemap for an outgoing buffer
%typemap(in) (void *wbuffer, size_t len) {
- if (!PyString_Check($input)) {
- PyErr_SetString(PyExc_ValueError, "Expecting a string");
- return NULL;
- }
- $1 = (void *) PyString_AsString($input);
- $2 = PyString_Size($input);
+ if (!PyString_Check($input)) {
+ PyErr_SetString(PyExc_ValueError, "Expecting a string");
+ SWIG_fail;
+ }
+ $1 = (void *) PyString_AsString($input);
+ $2 = PyString_Size($input);
}
// typemap for an incoming buffer
%typemap(in) (void *rbuffer, size_t len) {
- if (!PyInt_Check($input)) {
- PyErr_SetString(PyExc_ValueError, "Expecting an integer");
- return NULL;
- }
- $2 = PyInt_AsLong($input);
- if ($2 < 0) {
- PyErr_SetString(PyExc_ValueError, "Positive integer expected");
- return NULL;
- }
- $1 = (void *) malloc($2);
+ if (!PyInt_Check($input)) {
+ PyErr_SetString(PyExc_ValueError, "Expecting an integer");
+ SWIG_fail;
+ }
+ $2 = PyInt_AsLong($input);
+ if ($2 < 0) {
+ PyErr_SetString(PyExc_ValueError, "Positive integer expected");
+ SWIG_fail;
+ }
+ $1 = (void *) malloc($2);
}
// Return the buffer. Discarding any previous return result
%typemap(argout) (void *rbuffer, size_t len) {
- Py_XDECREF($result); /* Blow away any previous result */
- if (result < 0) { /* Check for I/O error */
- free($1);
- PyErr_SetFromErrno(PyExc_IOError);
- return NULL;
- }
- $result = PyString_FromStringAndSize($1,result);
- free($1);
+ Py_XDECREF($result); /* Blow away any previous result */
+ if (result < 0) { /* Check for I/O error */
+ free($1);
+ PyErr_SetFromErrno(PyExc_IOError);
+ return NULL;
+ }
+ $result = PyString_FromStringAndSize($1,result);
+ free($1);
}
@@ -3594,13 +3717,13 @@ this, you could write a multi-argument typemap like this:
%typemap(in) (double *mat, int rows, int columns) {
- MatrixObject *a;
- a = GetMatrixFromObject($input); /* Get matrix somehow */
+ MatrixObject *a;
+ a = GetMatrixFromObject($input); /* Get matrix somehow */
- /* Get matrix properties */
- $1 = GetPointer(a);
- $2 = GetRows(a);
- $3 = GetColumns(a);
+ /* Get matrix properties */
+ $1 = GetPointer(a);
+ $2 = GetRows(a);
+ $3 = GetColumns(a);
}
@@ -3614,7 +3737,7 @@ with non-consecutive C/C++ arguments; a workaround such as a helper function re-
the arguments to make them consecutive will need to be written.
-
@@ -3793,9 +3916,9 @@ A fragment can use one or more additional fragments, for example:
... some marshalling code ...
if (ival < CHAR_MIN /*defined in <limits.h>*/) {
- ...
+ ...
} else {
- ...
+ ...
}
...
return value;
@@ -3876,7 +3999,7 @@ fragment usage unless a desire to really get to grips
with some powerful but tricky macro and fragment usage that is used in parts of the SWIG typemap library.
@@ -3903,13 +4026,13 @@ struct A {
}
%typemap(in, fragment="incode"{A<T>}) {
- ... here we use the 'type specialized' fragment "incode"{A<T>} ...
+ ... here we use the 'type specialized' fragment "incode"{A<T>} ...
}
};
-
11.11.2 Fragments and automatic typemap specialization
class Foo {
- int x;
+public:
+ int x;
};
class Bar {
- int y;
+public:
+ int y;
};
class FooBar : public Foo, public Bar {
- int z;
+public:
+ int z;
};
@@ -4058,12 +4184,15 @@ handling of pointer values (and to make adjustments when needed).
In the wrapper code generated for each language, pointers are handled through
the use of special type descriptors and conversion functions. For example,
-if you look at the wrapper code for Python, you will see code like this:
+if you look at the wrapper code for Python, you will see code similar to the following
+(simplified for brevity):
@@ -4075,8 +4204,10 @@ target language, a list of equivalent typenames (via typedef or
inheritance), and pointer value handling information (if applicable).
The SWIG_ConvertPtr() function is simply a utility function
that takes a pointer object in the target language and a
-type-descriptor objects and uses this information to generate a C++
-pointer. However, the exact name and calling conventions of the conversion
+type-descriptor object and uses this information to generate a C++ pointer.
+The SWIG_IsOK macro checks the return value for errors and
+SWIG_exception_fail can be called to raise an exception in the target language.
+However, the exact name and calling conventions of the conversion
function depends on the target language (see language specific chapters for details).
@@ -4167,7 +4298,7 @@ structures rather than creating new ones. These swig_module_info
structures are chained together in a circularly linked list.
-
@@ -4775,7 +4883,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.
@@ -412,7 +413,7 @@ mixed argument types such as printf(). Providing general purpose
wrappers to such functions presents special problems (covered shortly).
@@ -605,7 +606,7 @@ you need to bring out some bigger guns.
One way to do this is to use a special purpose library such as libffi
(http://sources.redhat.com/libffi).
+href="http://www.sourceware.org/libffi/">http://www.sourceware.org/libffi/).
libffi is a library that allows you to dynamically construct
call-stacks and invoke procedures in a relatively platform independent
manner. Details about the library can be found in the libffi
@@ -625,23 +626,23 @@ example. For example:
of strings */
%typemap(in) (...) {
- char **argv;
- int argc;
- int i;
+ char **argv;
+ int argc;
+ int i;
- argc = PyTuple_Size(varargs);
- argv = (char **) malloc(sizeof(char *)*(argc+1));
- for (i = 0; i < argc; i++) {
- PyObject *o = PyTuple_GetItem(varargs,i);
- if (!PyString_Check(o)) {
- PyErr_SetString(PyExc_ValueError,"Expected a string");
- free(argv);
- return NULL;
- }
- argv[i] = PyString_AsString(o);
- }
- argv[i] = NULL;
- $1 = (void *) argv;
+ argc = PyTuple_Size(varargs);
+ argv = (char **) malloc(sizeof(char *)*(argc+1));
+ for (i = 0; i < argc; i++) {
+ PyObject *o = PyTuple_GetItem(varargs,i);
+ if (!PyString_Check(o)) {
+ free(argv);
+ PyErr_SetString(PyExc_ValueError,"Expected a string");
+ SWIG_fail;
+ }
+ argv[i] = PyString_AsString(o);
+ }
+ argv[i] = NULL;
+ $1 = (void *) argv;
}
/* Rewrite the function call, using libffi */
@@ -675,11 +676,11 @@ example. For example:
&ffi_type_uint, types) == FFI_OK) {
ffi_call(&cif, (void (*)()) execlp, &result, values);
} else {
- PyErr_SetString(PyExc_RuntimeError, "Whoa!!!!!");
free(types);
free(values);
free(arg3);
- return NULL;
+ PyErr_SetString(PyExc_RuntimeError, "Whoa!!!!!");
+ SWIG_fail;
}
free(types);
free(values);
@@ -743,8 +744,8 @@ As a more extreme example of libffi, here is some code that attempts to wrap
-
@@ -964,7 +965,7 @@ design or to provide an alternative interface using a helper function than it is
fully general wrapper to a varargs C++ member function.
-
@@ -986,10 +987,10 @@ you might structure your interface like this:
%typemap(const char *fmt, ...) {
- ...
+ ...
}
%feature("action") traceprintf {
- ...
+ ...
}
/* Include some header file with traceprintf in it */
@@ -1010,7 +1011,7 @@ to control this:
@@ -111,16 +112,16 @@ suppress a warning for a method in a class hierarchy, you could do this:
%warnfilter(501) Object::foo;
class Object {
public:
- int foo(int);
- int foo(double); // Silently ignored
- ...
+ int foo(int);
+ int foo(double); // Silently ignored
+ ...
};
class Derived : public Object {
public:
- int foo(int);
- int foo(double); // Silently ignored
- ...
+ int foo(int);
+ int foo(double); // Silently ignored
+ ...
};
@@ -135,7 +136,7 @@ Warnings can be suppressed for an entire class by supplying a class name. For e
class Object {
public:
- ... // All 501 warnings ignored in class
+ ... // All 501 warnings ignored in class
};
@@ -147,7 +148,7 @@ your interface. Ignore the warning messages at your own peril.
-
@@ -105,7 +106,7 @@ If you don't want to use environment variables then change all occurrences of th
If you are interested in how the project files are set up there is explanatory information in some of the language module's documentation.
If you do not have access to Visual C++ you will have to set up project files / Makefiles for your chosen compiler. There is a section in each of the language modules detailing what needs setting up using Visual C++ which may be of some guidance. Alternatively you may want to use Cygwin as described in the following section.
SWIG can also be compiled and run using Cygwin or MinGW which provides a Unix like front end to Windows and comes free with gcc, an ANSI C/C++ compiler. However, this is not a recommended approach as the prebuilt executable is supplied.
@@ -223,7 +224,7 @@ This information is provided for those that want to modify the SWIG source code
Normally this is not needed, so most people will want to ignore this section.
@@ -352,7 +353,7 @@ Note that the Cygwin environment will also allow one to regenerate the autotool
These files are generated using the autogen.sh script and will only need regenerating in circumstances such as changing the build system.
@@ -371,7 +372,7 @@ The modules which are known to work are Python, Tcl, Perl, Ruby, Java and C#.
Follow the Unix instructions in the README file in the SWIG root directory to build the examples.
diff --git a/Doc/Manual/margin-left.patch b/Doc/Manual/margin-left.patch
deleted file mode 100644
index 8bef6305c..000000000
--- a/Doc/Manual/margin-left.patch
+++ /dev/null
@@ -1,277 +0,0 @@
-# This patch is against htmldoc 1.8.27, and it hacks in support for
-# correctly indenting the
-This example illustrates how to use directors to implement C++
-callbacks in Go.
-
-
-
-Because Go and C++ use inheritance differently, you must call a
-different function to create a class which uses callbacks. Instead of
-calling the usual constructor function whose name is New
-followed by the capitalized name of the class, you call a function
-named NewDirector followed by the capitalized name of the
-class.
-
-
-
-The first argument to the NewDirector function is an instance
-of a type. The NewDirector function will return an interface
-value as usual. However, when calling any method on the returned
-value, the program will first check whether the value passed
-to NewDirector implements that method. If it does, the
-method will be called in Go. This is true whether the method is
-called from Go code or C++ code.
-
-
-
-Note that the Go code will be called with just the Go value, not the
-C++ value. If the Go code needs to call a C++ method on itself, you
-need to get a copy of the C++ object. This is typically done as
-follows:
-
-
-
-type Child struct { abi Parent }
-func (p *Child) ChildMethod() {
- p.abi.ParentMethod()
-}
-func f() {
- p := &Child{nil}
- d := NewDirectorParent(p)
- p.abi = d
- ...
-}
-
-
-
-In other words, we first create the Go value. We pass that to
-the NewDirector function to create the C++ value; this C++
-value will be created with an association to the Go value. We then
-store the C++ value in the Go value, giving us the reverse
-association. That permits us to call parent methods from the child.
-
-
-
-
-To delete a director object, use the function DeleteDirector
-followed by the capitalized name of the class.
+This example illustrates how to use directors to implement C++ callbacks in Go.
+See the Go Director
+Classes documentation subsection for an in-depth explanation how to use the
+director feature.
-This example illustrates the extending of a C++ class with cross
-language polymorphism.
-
+This example illustrates how to inherit from a C++ class in Go.
+See the Go Director
+Classes documentation subsection for an in-depth explanation how to use the
+director feature.
diff --git a/Examples/go/extend/runme.go b/Examples/go/extend/runme.go
index 770e27802..a56968937 100644
--- a/Examples/go/extend/runme.go
+++ b/Examples/go/extend/runme.go
@@ -7,19 +7,12 @@ import (
"fmt"
)
-type CEO struct{}
-
-func (p *CEO) GetPosition() string {
- return "CEO"
-}
-
func main() {
// Create an instance of CEO, a class derived from the Go
// proxy of the underlying C++ class. The calls to getName()
// and getPosition() are standard, the call to getTitle() uses
// the director wrappers to call CEO.getPosition().
-
- e := NewDirectorManager(new(CEO), "Alice")
+ e := NewCEO("Alice")
fmt.Println(e.GetName(), " is a ", e.GetPosition())
fmt.Println("Just call her \"", e.GetTitle(), "\"")
fmt.Println("----------------------")
@@ -27,7 +20,6 @@ func main() {
// Create a new EmployeeList instance. This class does not
// have a C++ director wrapper, but can be used freely with
// other classes that do.
-
list := NewEmployeeList()
// EmployeeList owns its items, so we must surrender ownership
@@ -49,15 +41,13 @@ func main() {
// CEO, but now Go thinks the object is an instance of class
// Employee. So the call passes through the Employee proxy
// class and on to the C wrappers and C++ director, eventually
- // ending up back at the Java CEO implementation of
+ // ending up back at the Go CEO implementation of
// getPosition(). The call to GetTitle() for item 3 runs the
// C++ Employee::getTitle() method, which in turn calls
// GetPosition(). This virtual method call passes down
- // through the C++ director class to the Java implementation
+ // through the C++ director class to the Go implementation
// in CEO. All this routing takes place transparently.
-
fmt.Println("(position, title) for items 0-3:")
-
fmt.Println(" ", list.Get_item(0).GetPosition(), ", \"", list.Get_item(0).GetTitle(), "\"")
fmt.Println(" ", list.Get_item(1).GetPosition(), ", \"", list.Get_item(1).GetTitle(), "\"")
fmt.Println(" ", list.Get_item(2).GetPosition(), ", \"", list.Get_item(2).GetTitle(), "\"")
@@ -66,11 +56,11 @@ func main() {
// Time to delete the EmployeeList, which will delete all the
// Employee* items it contains. The last item is our CEO,
- // which gets destroyed as well.
+ // which gets destroyed as well and hence there is no need to
+ // call DeleteCEO.
DeleteEmployeeList(list)
fmt.Println("----------------------")
// All done.
-
fmt.Println("Go exit")
}
diff --git a/Examples/go/funcptr/Makefile b/Examples/go/funcptr/Makefile
index 82031c9d5..efeb6e860 100644
--- a/Examples/go/funcptr/Makefile
+++ b/Examples/go/funcptr/Makefile
@@ -1,5 +1,6 @@
TOP = ../..
-SWIG = $(TOP)/../preinst-swig
+SWIGEXE = $(TOP)/../swig
+SWIG_LIB_DIR = $(TOP)/../$(TOP_BUILDDIR_TO_TOP_SRCDIR)Lib
SRCS = funcptr.c
TARGET = example
INTERFACE = example.i
@@ -9,7 +10,8 @@ check: build
$(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run
build:
- $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \
+ $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \
+ SWIG_LIB_DIR='$(SWIG_LIB_DIR)' SWIGEXE='$(SWIGEXE)' \
SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go
clean:
diff --git a/Examples/go/index.html b/Examples/go/index.html
index 21dda21b5..467f4ecb7 100644
--- a/Examples/go/index.html
+++ b/Examples/go/index.html
@@ -23,6 +23,7 @@ certain C declarations are turned into constants.
director. Example how to utilize the director feature.
Compilation Issues
@@ -37,20 +38,23 @@ certain C declarations are turned into constants.
On Unix the compilation of examples is done using the
-file Example/Makefile. This makefile performs a manual
-module compilation which is platform specific. When using
-the 6g or 8g compiler, the steps look like this
+file Example/Makefile. Normally builds are done simply
+using go build. For testing purposes this makefile performs
+a manual module compilation that is platform specific. When using
+the gc compiler, the steps look approximately like this
(GNU/Linux):